When you use class MyClass;
to forward declare your class, this only declares that the thing with the name MyClass
is a class
, it does not declare the internal methods of the class.
Whenever you need to use one of the internal methods (such as a non-trivial destructor) you need to include the full declaration of the class (this means include the header file containing the class definition). Without this, the compiler has no way of knowing what the internal structure of your class actually looks like.
Here is an example:
// main.cpp
#include "head1.hpp" // An instance of Head1 is created in this file
#include "head2.hpp" // An instance of Head2 is created in this file
int main(int argc, char** argv)
{
Head1 head1(true);
Head2 head2(true);
return 0;
}
// head1.hpp
#ifndef HEAD1_HPP
#define HEAD1_HPP
class Head2; // A pointer to a class is declared, but no instance is created
// so here we only need a forward declaration
class Head1
{
public:
Head1(bool real=false);
~Head1();
private:
Head2* myHead2;
};
#endif /* #ifndef HEAD1_HPP */
// head2.hpp
#ifndef HEAD2_HPP
#define HEAD2_HPP
class Head1; // Same as above
class Head2
{
public:
Head2(bool real=false);
~Head2();
private:
Head1* myHead1;
};
#endif /* #ifndef HEAD2_HPP */
// head1.cpp
#include "head1.hpp" // Include the header we are defining methods for
#include "head2.hpp" // We also create an instance of Head2 in here
#include <iostream>
using namespace std;
Head1::Head1(bool real) {
myHead2 = real ? new Head2() : NULL;
cout << "Hello Head 1" << endl;
}
Head1::~Head1() {
cout << "Bye Head 1" << endl;
if (myHead2 != NULL) delete myHead2;
}
// head2.cpp
#include "head2.hpp" // As above
#include "head1.hpp"
#include <iostream>
using namespace std;
Head2::Head2(bool real) {
myHead1 = real ? new Head1() : NULL;
cout << "Hello Head 2" << endl;
}
Head2::~Head2() {
cout << "Bye Head 2" << endl;
if (myHead1 != NULL) delete myHead1;
}