Why are iostreams not copyable?

Copying and moving are value-semantic operations. To define them, you first have to decide what properties of a class give its objects distinct values. This point was at first largely sidestepped for the iostreams library, and then C++11 took a different direction incompatible with such a copy constructor. The state of a stream object comprises … Read more

C++ Copy constructor gets called instead of initializer_list

As pointed out by Nicol Bolas, the original version of this answer was incorrect: cppreference at the time of writing incorrectly documented the order in which constructors were considered in list-initialization. Below is an answer using the rules as they exist in the n4140 draft of the standard, which is very close to the official … Read more

Why aren’t copy constructors “chained” like default constructors and destructors?

The copy constructor doesn’t (can’t) really make a copy of the object because Derived::Derived(const Derived&) can’t access pdata to change it. Sure it can: Derived(const Derived& d) : Base(d) { cout << “Derived::Derived(const B&)” << endl; } If you don’t specify a base class constructor in the initializer list, its default constructor is called. If … Read more

Copying derived entities using only base class pointers, (without exhaustive testing!) – C++

This approach is the preferred way of copying polymorphic objects because it offloads the responsibility of determining how to copy an object of an arbitrary type to that object, rather than trying to determine it at compile-time. More generally, if you don’t know what the base class pointer points at at compile-time, you can’t possibly … Read more

Why is the copy constructor called when we pass an object as an argument by value to a method?

To elaborate the two answers already given a bit: When you define variables to be “the same as” some other variable, you have basically two possibilities: ClassA aCopy = someOtherA; //copy ClassA& aRef = someOtherA; //reference Instead of non-const lvalue references, there are of course const references and rvalue references. The main thing I want … Read more

Calling assignment operator in copy constructor

Yes, that’s a bad idea. All member variables of user-defined types will be initialized first, and then immediately overwritten. That swap trick is this: Foo& operator=(Foo rhs) // note the copying { rhs.swap(*this); //swap our internals with the copy of rhs return *this; } // rhs, now containing our old internals, will be deleted

Explicit copy constructor

The explicit copy constructor means that the copy constructor will not be called implicitly, which is what happens in the expression: CustomString s = CustomString(“test”); This expression literally means: create a temporary CustomString using the constructor that takes a const char*. Implicitly call the copy constructor of CustomString to copy from that temporary into s. … Read more