I have a class which passes the address of one data member to the constructor of another:
class MemberA {
public:
MemberA(MemberB* ptr) : ptr_(ptr) {}
private:
MemberB* ptr_;
};
struct MemberB {
public:
MemberB(int x) : x_(x) {}
private:
int x_;
};
class Foo {
public:
Foo() : a(&b), b(1) {}
private:
MemberA a;
MemberB b;
};
In this example, a
is constructed before b
, but depends on the address of b
. Would this work? My intuition says that data members are allocated at the start, so that Foo
knows how large it needs to be, and also because they're allocated on the stack. However, I don't know this for a fact and would like to verify.
As an aside, I know that flipping the order would resolve this issue entirely; if b
were declared and initialized before a
, then I'd know that it would work. I also realize that even if the address is known, that dereferencing b_
before it's initialized is undefined behavior. However, I'm really just curious if the above scenario is even legal
Thanks!