How to initialize member variables before inherited classes

Viewed 115

I'm trying to make one class which requires member variables to be initialized first. I know why this happens, but is there a way around this?

Current print order: second first

Wanted print order: first second

#include <iostream>

struct A {
    A() {
        std::cout << "first" << '\n';
    }
};

struct B {
    B() {
        std::cout << "second" << '\n';
    }
};

struct C : public B {

    C() : a(), B() {

    }

    A a;

};

int main() {

    C c;

    return 0;
} 
3 Answers

Stick your members that need initializing first in a struct and inherit privately from that, before B.

struct A {
    A() { std::cout << "first" << '\n'; }
};

struct B {
    B() { std::cout << "second" << '\n'; }
};

struct Members { A a; };

struct C : private Members, public B {
    C() : Members(), B() {}
};

int main() {
    C c;
} 

The downside with this is that there is no way to avoid exposing the "member struct" to the outside world, but that shouldn't be a problem in practice.

In C++ base classes will be initialized before any member variables of a derived class.

The best recourse given the information you've provided is to prefer composition over inheritance:

struct A {
    A() {
        std::cout << "first" << '\n';
    }
};

struct B {
    B() {
        std::cout << "second" << '\n';
    }
};

struct C {
    A a;
    B b;
};

This will exhibit the desired behavior

Make A a needed reference for C:

#include <iostream>

struct A {
    A() {
        std::cout << "first" << '\n';
    }
};

struct B {
    B() {
        std::cout << "second" << '\n';
    }
};

struct C : public B {
    C(const A& a) : _A(a), B() {}
    const A& _A;
};

int main() {
    A a;
    C c(a);
    return 0;
}
Related