In the book "C++ primer" there is a section about class declarations and definitions. I don't understand everything about this sentence :
data members can be specified to be of a class type only if the class has been defined.
I don't understand the logic behind this sentence. How do you specify a data member to be of a class type, what does this action mean?
It means, for declaration of a non-static class data member of class type T
, T
is required to be complete.
(In general, when the size and layout of
T
must be known.)
e.g.
class foo; // forward declaration
class bar {
foo f; // error; foo is incomplete
};
On the other hand,
class foo {}; // definition
class bar {
foo f; // fine; foo is complete
};
I believe it means that this will compile:
class A
{
public:
A() {/* empty */}
};
class B
{
public:
B() {/* empty */}
private:
A myClassMember; // ok
};
.... but this will not:
class A; // forward declaration only!
class B
{
public:
B() {/* empty */}
private:
A myClassMember; // error, class A has only been declared, not defined!
};
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