invalid use of incomplete type while implementing nested class in separate files

Viewed 29

I want to add a class (B inherit the exception class) inside a base class (A) of another derived class (D), and then call a function in that derived class (fn) that throw a class of type B, it it works just fine until i split the implementation in a separate file:

this is the code of the class A in A.hpp :

#pragma once
#include <iostream>

class A
{
    public:
    class B;
};

and this is the implementation of class A::B in A.cpp :

#include "A.hpp"

class A::B {
    // other code
};

this is the code of the main.cpp :

#include "A.hpp"
#include <iostream>

using namespace std;

class D : public A
{
    public:
    void fn()
    {
        throw A::B(); // This is an error!
    }
};

int main()
{
    try {
        D ff;
        ff.fn();
    }
    catch(std::exception &e)
    {
        std::cout << "Error!\n";
    }
    return 0;
}

this will throw an error in the terminal something like this :

main.cpp:11:9: error: invalid use of incomplete type 'A::B'
                throw A::B();
                      ^~~~~~
./A.hpp:7:8: note: forward declaration of 'A::B'
        class B;
              ^
1 error generated.

if I implement the class B inside the class A it works!

My question is how can i retrieve the first implementation without going with the second solution ?

0 Answers
Related