My question is simple, is the following code safe?
struct Parent {
B* _a;
Parent(B* a) : _a(a) {}
};
struct Child : public Parent {
B _b;
Child() : Parent(&_b), _b(2){};
};
int main() {
Child c;
return 0;
}
Two more points:
- I'm interested in the part of passing a reference to a member object to the parent object.
- In safe, I mean that it
_bwill be allocated (and its memory address) and that this code will work no matter which compiler I use.
Thanks in advance.
clarification
on safe I actually meant that the memory address was valid, since I already knew that it was not initialized.
other notes
In my actual code, I wanted to save the type object Bas a pointer to its base class A, for example:
struct Parent {
A* _a;
Parent(A* a) : _a(a) {}
};
struct Child : public Parent {
B _b;
Child() : Parent(&_b), _b(2){};
};
int main() {
Child c;
return 0;
}
, AndreyT, . , -, . ( , - ).