This is admittedly a bit of a newbie question. I have looked at the C++ documentation and not found it.
class A
{
public:
struct B {
};
B b;
B b1;
};
main() {
A a;
}
In main(), how do we declare and define a pointer of the type of a.b?
Or, do we need to move the declaration for struct B outside of class A?
The pointer will later be set to &a.b or &a.b1; So ideally, we want to initialize it as null.
So, while auto could work, it might be a less than ideal solution.
You might access/name B with A::B, so
int main() {
A a;
A::B* p = &a.b;
}
Example:
class A
{
public:
// Nested type declaration and definition.
// "B" is declared inside "A", so its fully qualified name is "A::B".
// A nested class in C++ does NOT capture an implicit pointer/reference
// to the enclosing class. "A::B" is an independent type.
struct B {
// Empty struct: trivially constructible, destructible, and copyable.
};
// Data member of type "A::B". This subobject is named "b" and lives
// inside each instance of "A".
B b;
};
int main() {
// Default-construct an object "a" of type A.
// Since A has a member "b" of type A::B, construction of "a" creates
// a subobject "a.b".
A a;
// Construct an independent object "d" of the nested type.
// Note: you do NOT need an A object to create an A::B; you only need
// to qualify the name with "A::".
A::B d;
// Take the address of the member subobject "a.b".
// "auto" deduces the type as "A::B*".
auto b = &a.b;
// Take the address of the standalone object "d".
// "auto" deduces the same pointer type "A::B*".
auto c = &d;
// Explicit pointer types:
A::B* pb_member = &a.b; // pointer to the member subobject inside "a"
A::B* pc_standalone = &d; // pointer to the separate object "d"
// Explicit reference types (no pointers involved):
A::B& rb_member = a.b; // reference bound to the member subobject
A::B& rd_standalone = d; // reference bound to the separate object
// At this point:
// - b and c have the same static type (A::B*) via deduction.
// - pb_member and pc_standalone are explicitly typed as A::B*.
// - rb_member and rd_standalone are explicitly typed as A::B&.
// - b/pb_member point to the subobject inside "a".
// - c/pc_standalone point to the separate object "d".
// - All objects here have automatic storage and will be destroyed
// at the end of main().
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With