Search code examples
c++inheritanceheader-files

Error: base class undefined in deriving class Son from baseclass Father


I made two classes Father and Son, split into .h and .cpp. Why do I get the above Error? I have another Solution with basicly the same includes and no error. Sorry if this is trivial but I'm new to c++ and confused why it works in one Solution but not the other.

Edit: When I run the program, the Terminal still opens and shows the cout lines of the Father, the error seems to happen after that. I know about the soution with including the Father.h inside Son.h. but why doesn't it work the way I wrote it? I like the Idea of including header files inside the cpp files.

Father.h

#pragma once
class Father
{
public:
    Father();
    ~Father();
};

Father.cpp:

#include "Father.h"
#include <iostream>
using namespace std;

Father::Father()
{
    cout << "I am the father constructor" << endl;
}

Father::~Father()
{
    cout << "I am the father deconstructor" << endl;
}

Son.h:

#pragma once
class Son : public Father
{
public:
    void Talk();
};

Son.cpp:

#include "Father.h"
#include "Son.h"
#include <iostream>
using namespace std;

void Son::Talk()
{
    cout << "I'am the son" << endl;
}

Main.cpp:

#include "Son.h"
#include <iostream>
using namespace std;

int main()
{
    Son Bernd;
}

Solution

  • why doesn't it work the way I wrote it?

    Son.cpp compiles fine, because it includes the declaration of Father from Father.h before the declaration of Son from Son.h.

    The problem occurs in Main.cpp. Here you only include the declaration of Son from Son.h. The class Father is not known to this compilation unit.

    Make sure, that each header includes all of it's dependencies and add

    #include "Father.h"
    

    to Son.h.