Search code examples
c++classoopinstantiation

Can you construct after instantiation? Avoiding empty constructor


I have a class which has a member attribute consisting of an object defined elsewhere. In the code below, A contains a public attribute var which is a B:

class B {
    public:
    int x, y;
    std::vector<int> z;
        B(int a, int b, std::vector<int> c) {
            x = a; y = b; z = c;
        }
};

class A {
    public:
        B var;
        A(int i, int j) {
            std::vector<int> someVector;
            B(i, j, someVector);
        }
};

int main() {
    A foo(5, 3);
    return 0;
}

This (obviously) doesn't compile as var is instantiated upon an instantiation of A, too late for it to be constructed.

The best way I can do something similar is modify some code:

class B {
    public:
    int x, y;
    std::vector<int> z;
        B() {}
        void setAttributes(int a, int b, std::vector<int> c) {
            x = a; y = b; z = c;
        }
};

class A {
    public:
        B var;
        A(int i, int j) {
            std::vector<int> someVector;
            B.setAttributes(i, j, someVector);
        }
};

This does compile because attributes are set after instantiation.

But is there a way to remain closer to the first code snippet?


Solution

  • A(int i, int j) : var(i, j, {}) {}
    

    Also, in your code B(i, j, someVector); does not initialize member variable var, and B.setAttributes(i, j, someVector); wouldn't compile at all.