~/okanakyuz
← all posts

Delete, Default and Delegating Constructors

How = default, = delete and delegating constructors (C++11) help you control which constructors the compiler generates for a class.

2 March 2020updated 25 November 20261 min read

If you are using modern C++ (C++11 and later), there are three important concepts for managing the special methods of a class.

If you write a class without your own constructor (or copy constructor), the compiler generates one for you. The generated default constructor default-initializes the members (an int member is simply left uninitialized unless you give it a default member initializer), and the generated copy constructor copies the members one by one. It looks like it does nothing, but it is really necessary.

Think about a scenario where you write your own constructor, but this constructor takes a parameter. What happens if you don’t provide a constructor without parameters? The answer is that the compiler doesn’t generate a default constructor for you anymore. This is where = default helps: it tells the compiler to generate that method anyway. On the other hand, = delete tells the compiler not to provide the method at all, and any code that tries to call it fails to compile. Let’s see it below.

class MyClass {
public:
    // tell the compiler to generate the default constructor for us
    MyClass() = default;
    MyClass(int initvalue);
    // do not allow copying this class
    MyClass(const MyClass& refObject) = delete;
};

Note that once you declare the copy constructor, even as deleted, the compiler doesn’t generate a move constructor either. So the class above can be neither copied nor moved.

In some cases, you don’t want to implement every version of the constructor from scratch, because another constructor already does most of the work. Then you can delegate the call to that constructor.

class MyClass {
private:
    int x,y,z;
public:
    // our own default constructor
    MyClass() {
        x = 10;
        y = 15;
        z = 20;
    }
    //delegates to MyClass()
    //first sets x = 10, y = 15 and z = 20
    //then sets x from the parameter
    MyClass(int newx) : MyClass(){
        this->x = newx;
    }
    //delegates to MyClass(newx)
    //MyClass(newx) delegates to MyClass()
    //which sets x = 10, y = 15 and z = 20
    //then MyClass(newx) sets x from the parameter
    //and finally this constructor sets y from the parameter
    MyClass(int newx, int newy) : MyClass(newx){
        this->y = newy;
    }
};

Keep in mind, the delegated constructor runs completely before the body of your constructor. Also, when you delegate, the delegation must be the only thing in the initializer list. You can’t initialize other members there.