Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why data members can be specified to be of a class type only if the class has been defined? (from the book "C++ primer")

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?

like image 346
gigi Avatar asked Dec 11 '22 13:12

gigi


2 Answers

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
};
like image 184
songyuanyao Avatar answered Jan 19 '23 00:01

songyuanyao


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!
 };
like image 44
Jeremy Friesner Avatar answered Jan 19 '23 00:01

Jeremy Friesner