Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize member variables before inherited classes

Tags:

c++

class

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;
} 
like image 828
pesuww Avatar asked Jan 24 '23 08:01

pesuww


1 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.

like image 56
molbdnilo Avatar answered Jan 26 '23 21:01

molbdnilo