mangenouilles mangenouilles - 8 days ago 5
C++ Question

class constructor with const reference

in this class

class Foo {
public:
Foo(){}
Foo(Foo const &) {}
};


when would
Foo(Foo const &)
ever be called? I do not understand this kind of constructor

Answer

This is called copy constructor. When you want to initialize a class instance by copying an existing instance, you'd probably want to use it.

const - you don't want to change the object you are copying.

reference - you don't want to copy the existing instance into the constructor, just to copy it again in the initialization.

Comments