Roar RaizZer
Roar RaizZer

Reputation: 197

How to inherit from a class that has been declared forwardly

I have declared classes: Another and Klass. class Another is only defined in another.hpp, class Klass is declared in klass.hpp and defined in klass.cpp.

I have included another.hpp inside klass.cpp and forward-declared class Another in klass.hpp.

// klass.cpp
#include "klass.hpp"
#include "another.hpp"

Klass::Klass()
{

}

// klass.hpp
#pragma once

class Another;

class Klass : public Another
{
public:
    Klass();
};

// another.hpp
#pragma once

class Another
{
protected:
    int a;
    char b;
};

Upvotes: 1

Views: 95

Answers (1)

jfMR
jfMR

Reputation: 24738

In your file klass.hpp:

#pragma once

class Another;

class Klass : public Another
{
public:
    Klass();
};

class Another; is a forward declaration: It just introduces the name Another into a C++ scope. This forward declaration simply includes a partial classification of the name Another (i.e., that it is about a class). It doesn't provide all the details for creating a complete declaration (e.g., it doesn't give the details for inferring its size).

As such, Another above is an incomplete type and its size is unknown to the compiler. Therefore, you can't provide a definition of the class Klass by inheriting from Another, an incomplete type. If you could, what should be then the size of Klass?.

Upvotes: 1

Related Questions