lundi 10 février 2020

Why cant we delay initialise a class member with a non default constructor?

I have a class like below:

#pragma once
#include <atomic>

class MyClassAnother {
public:
    MyClassAnother(int val) : m_val(val) {
    }

private:
    int m_val;
};

There is another class which holds an object to MyClassAnother

#pragma once
#include "MyClassAnother.hpp"

class MyClass {
public:
    MyClass() {

    }

    void Func() {
        anotherClassObject = MyClassAnother(2);
    }

private:
    MyClassAnother anotherClassObject;
};

And here is the main.cpp

#include "MyClass.hpp"
#include <iostream>

int main() {
   MyClass object;
}

Of course the program does not compile. And its because of the following error

error: constructor for 'MyClass' must explicitly initialize the member 'anotherClassObject' which does not have a default constructor

Question:
But why? Why can't I delay initialise the class member? Is the workaround to have a default constructor and delay initialise it with the real constructor later? Is it an anti pattern to do it this way then?

I know that this can be resolved by making MyClassAnother anotherClassObject a pointer. But I want to have MyClassAnother anotherClassObject as a member object or a reference member in this case.

Aucun commentaire:

Enregistrer un commentaire