Search code examples
c++inheritanceforward-declaration

How to derive from incomplete class in C++


I have 3 classes: Context, A, and B.

B should inherit from A, and should use Context and A in its methods.

A is an abstract class. A and Context dependent classes with forward declaration in headers.

Code in Context:

#pragma once
#include "A.h"

class A;

class Context {
    ...
    A* someMethod();

};

Code in A:

#pragma once
#include "Context.h"

class Context;

class A {
    ...
    Context* someOtherMethod();
    ...
};

This is working fine, but when I try to add class B, I get a lot of errors:

#pragma once
#include "A.h"

// class A; // with this definition also have errors

class B : public A {
    A* method(Context* context) { ... };
};

error: invalid use of incomplete type ‘class A’

error: expected ‘;’ at end of member declaration

What am I doing wrong? Is it possible to write class B in such a way that this problem disappears? The fact is that the program should have many classes that are inherited from class A.


Solution

  • If you have forward declarations, then you usually do not need to include the specified header.

    Context.h should NOT include A.h, nor apparently should A.h include Context.h.

    Since B actually uses the A class directly (you cannot derived from an incomplete class), it will need to include A.h.

    Code in Context:

    #pragma once
    
    class A; //pointers do not require an include
    
    class Context {
        ...
        A* someMethod();
    
    };
    

    Code in A:

    #pragma once
    
    class Context; //pointers do not require an include
    
    class A {
        ...
        Context* someOtherMethod();
        ...
    };
    

    Code in B:

    #pragma once
    #include "A.h" //inheritance requires include
    
    class B : public A {
        A* method(Context* context) { ... };
    };