What is object slicing?

“Slicing” is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information – some of it is “sliced” away. For example, So an object of type B has two data members, foo and bar. Then if you were to write this: Then the information in b about member bar is lost in a.

std::wstring VS std::string

I am not able to understand the differences between std::string and std::wstring. I know wstring supports wide characters such as Unicode characters. I have got the following questions: When should I use std::wstring over std::string? Can std::string hold the entire ASCII character set, including the special characters? Is std::wstring supported by all popular C++ compilers? … Read more

gcc/g++: “No such file or directory”

Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds: or The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the … Read more

What is std::move(), and when should it be used?

Wikipedia Page on C++11 R-value references and move constructors In C++11, in addition to copy constructors, objects can have move constructors.(And in addition to copy assignment operators, they have move assignment operators.) The move constructor is used instead of the copy constructor, if the object has type “rvalue-reference” (Type &&). std::move() is a cast that produces … Read more

What are the differences between struct and class in C++?

You forget the tricky 2nd difference between classes and structs. Quoth the standard (§11.2.2 in C++98 through C++11): In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class. And just for completeness’ sake, the more widely known difference between class and … Read more

How to write C++ getters and setters

There are two distinct forms of “properties” that turn up in the standard library, which I will categorise as “Identity oriented” and “Value oriented”. Which you choose depends on how the system should interact with Foo. Neither is “more correct”. Identity oriented Here we return a reference to the underlying X member, which allows both sides of the call site … Read more

What is move semantics?

I find it easiest to understand move semantics with example code. Let’s start with a very simple string class which only holds a pointer to a heap-allocated block of memory: Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and … Read more