I'm trying to get along with C++ and polymorpism. Therefore I created the following code example. When try to compile i'm getting the following error message. Actually the code sample was Java exam and and now i try to translate it to C++.
Code:
$ g++ main.cpp -o main
main.cpp: In member function `void A::func5(C*)':
main.cpp:18: Fehler: invalid use of undefined type `struct C'
main.cpp:6: Fehler: forward declaration of `struct C'
Can anyone help me what's wrong with the example below. I guess it's related to forward declaration but don't know what's wrong. Any code improvements are appreciated as well.
Code:
#include <iostream>
using namespace std;
class C; // forward declaration
class A
{
public:
A() { cout << "A::A()" << endl; }
virtual ~A() { cout << "A::~A()" << endl; }
virtual void func1() { cout << "A::func1()" << endl; }
virtual void func2() { cout << "A::func2()" << endl; }
virtual void func3() { cout << "A::func3()" << endl; }
void func4(A* pA) { cout << "A::func4()" << endl; pA->func1(); }
void func5(C* pC) { cout << "A::func5()" << endl; pC->func1(); }
};
class B : public A
{
public:
B() { cout << "B::B()" << endl; }
~B() { cout << "B::~C()" << endl; }
void func1() { cout << "B::func1()" << endl; }
void func2(int* pI) { cout << "B::func2" << endl; }
};
class C : public B
{
public:
C() { cout << "C::C()" << endl; }
~C() { cout << "C::~B()" << endl; }
virtual void func1() { cout << "C::func1()" << endl; }
virtual void func2() { cout << "C::func2()" << endl; }
virtual void func3() { cout << "C::func3()" << endl; }
void func4() { cout << "C::func4()" << endl; }
};
int main()
{
A* ap = new C();
cout << endl;
ap->func1();
ap->func2();
ap->func3();
ap->func4(ap);
((C*)ap)->func4();
// static_cast<B*>(ap)->p()
cout << endl;
delete ap;
return 0;
}
Commenting out the line "void func5(C* pC) ..." and the program works...
Code:
A::A()
B::B()
C::C()
C::func1()
C::func2()
C::func3()
A::func4()
C::func1()
C::func4()
C::~B()
B::~C()
A::~A()