tejusadiga2004
tejusadiga2004

Reputation: 311

Forward Declaration of class in C++, incomplete type

I have an issue with Forward Declaration in C++ using clang compiler. Here is my code. It points data in CReference member as incomplete type. Please Help

class Internal;

class CReference {
private:
    Internal data;
public:

    CReference () {}    
    ~CReference (){}
};

class Internal {
public:
    Internal () {}
    ~Internal () {}
};

Upvotes: 10

Views: 16302

Answers (4)

Kiril Kirov
Kiril Kirov

Reputation: 38163

Forward declarations are useful when the compiler does not need the complete definition of the type. In other words, if you change your Internal data; to Internal* data or Internal& data, it will work.

Using Internal data;, the compiler needs to know the whole definition of Internal, to be able to create the structure of CReference class.

Upvotes: 22

Samuel
Samuel

Reputation: 6490

As mentioned above. Forward declaration has it's use to avoid header hell in header files when using only a plain pointer of a class in the header.

You usually want to keep includes in header files as few as possible. This can be achieved by forward declaring a class, but only if it is not a nested class and only if the pointer is used in header, as for this the pointer size is the required information, which is provided by the forward decl.

Upvotes: 0

Matthew Walton
Matthew Walton

Reputation: 9959

To use a type as a member of a class the compiler has to know how big it is, so that the size of the class can be correctly calculated. A forward declaration doesn't provide that information (C++ won't look ahead and try to find it, especially since the body might be declared in another translation unit), so you can't use it as a by-value member.

You can use a pointer or a reference instead, because pointers and references are the same size no matter what type they refer to. Then the compiler only needs to know the size of that type once you start manipulating it, and so you can get away without the full declaration until then.

Upvotes: 1

Andrew
Andrew

Reputation: 24846

Forward declaration only allows you to use pointers and references to it, until full declaration is available

Upvotes: 3

Related Questions