Search code examples
c++declarationdefinitionincomplete-type

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?


Solution

  • 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
    };