I have a project that I am working on and I am forced to use forward declaration, but member variables are said to be undeclaraed, Here is an example of what I am talking about.
#include <iostream>
usingnamespace std;
class B;
class A
{
public:
A(B* PointB):
PointB(PointB)
{
}
~A()
{
}
void func(B* b)
{
b->func();
}
B* PointB;
};
class B
{
public:
B()
{
PointA = new A(this);
}
~B()
{
}
void func()
{
cout<< "func b \n";
}
A* PointA;
};
int main()
{
B* TestB;
TestB = new B;
return 0;
}
The problem is, b (thats lowercase b) from classs A is said to be undeclared, so it doesnt compile, could anyone give me reasons.
As you could see b is never inniallized untiled invoked.
This is undefined because. You have forward declared that a class called "B" exists. However, that is all the information you have declared. So A is unable to call any functions on B because it doesn't know what B is exposing. This is one of the reasons why you use Header files (.h) to prevent crap like this :P
Thanks for the reply, and the answer, but this was really an example of my problem, my problem is really more deeper, I have multiple class (all declarations in .h files all definitions in .cpp), say one class is movements, one animal and another is dog which is derived from animal. here is how its presented. (example again, my codes are using 3rd party libraries so I cant use it)
mevement.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include "dog.h"
#include <set>
class movement
{
public:
movement();
~movement();
void func(animal* anim);
void make();
private:
animal* anim[10];
int i;
std::set<animal*>RegisterAnimal;
};
movement.cpp
1 2 3 4 5 6 7 8 9 10 11
void movement::func(animal* anim)
{
RegisterAnimal.insert(anim);
}
void movement::make()
{
//i = 0; decalred as 0 in another function
anim[i] = new dog(this);
i++
}
dog.h
1 2 3 4 5 6 7 8 9 10 11 12
#include "animal"
class dog: public animal
{
public:
dog(movement* move);
~dog();
/* use member functions and variables
inherited from animal*/
private:
};
dog.cpp
1 2 3 4
dog::dog(movement *move):
animal(move)
{
}
animal.h
1 2 3 4 5 6 7 8 9 10 11
class movement;
class animal
{
public:
animal(movement* move);
~animal();
/* house many data members*/
protected:
movement* movepointer;
};
as you can see I cant include movement.h in animal (gonna cause recursion) so I used forward declaration but It wont compile because the movepointer member varaible in animal is said to be undefined.
anyone got any ideas how to solve this problem.
Rofl I went to bed and had a dream about doing the same thing, now it works like a charm :D,
Yeah I gotta really avoid doing stuff like this though.I am gonna see how I could avoid this.