I have a base class from which I'm trying to inherit members for various other classes. The only problem is that if I split up the derived class into a header and a cpp file, it won't compile. I've got the shortest example I can come up with.
1 2 3 4 5 6 7 8 9
|
//Base.h
class Base
{
private:
int pVar;
protected:
Base(int theVar) : pVar(theVar) {};
int getBase() {return pVar;};
};
|
1 2 3 4 5 6 7 8 9
|
//Deriv.h
#include <iostream>
class Deriv : public Base
{
public:
Deriv() : Base(5) {};;
~Deriv();
void test() {std::cout << getBaseVar();};
};
|
1 2 3 4 5 6 7 8 9
|
//main.cpp
#include <cstdlib>
#include <iostream>
#include "Base.h"
#include "Deriv.h"
int main(int argc, char *argv[])
{
return 0;
}
|
The code above will compile. However, if I try to separate Deriv into 2 separate files as follow, the compile will fail:
1 2 3 4 5 6 7 8
|
//Deriv.h
class Deriv : public Base
{
public:
Deriv() : Base(5) {};
~Deriv();
void test();
};
|
1 2 3 4 5 6
|
//Deriv.cpp
#include <iostream>
void Deriv::test()
{
std::cout << getBaseVar();
}
|
the compiler will complain that Deriv has not been declared in the cpp file. I can solve this problem by adding
#include "Deriv.h"
at the top of Deriv.cpp, only to have the compiler complain about an expected class-name before '{' token on line 2 of Deriv.h. THIS I can fix by adding
#include "Base.h"
at the top of Deriv.h, at which point the compiler complains about class redefinition. At that point, I can compile and run the program by removing
#include "Base.h"
from main.cpp. However, as I have already included Base.h in Deriv.h at that point, I am unable to include it anywhere else to derive any more classes from it, as the compiler will complain about redefinition. Thus, the only way I can derive multiple classes from a given class is to contain all of my code in the derivative classes' header files.