I have two class as below: I want to test how class to work:
#include <iostream>
using namespace std;
class A
{
private:
B bInstance;
public:
A()
{
cout<<"A class is created! B class is invoked"<<endl;
}
};
class B
{
private:
A aInstance;
public:
B()
{
cout<<"B class is created! A class is invoked"<<endl;
}
};
int main()
{
A a;
B b;
}
but when I compile them in a file , I always get an error :(ClassThink.cpp is the name of saved file)
ClassThink.cpp:8: error: 'B' does not name a type
BTW, I use g++ compiler , thanks in advance
You haven't declared the 'B' class before your declaration of your 'A' class. So when you try to make an instance of the aforementioned class, it throws an error. The compiler doesn't know what you're talking about.
Actually the main problem here is that A contains a B. However, B also contains an A. And it goes in circles forever...You'll need to change them to pointers or something probably (or at least one to a pointer).
Then you can forward declare in .hpp and #include in the .cpp.