Reputation: 582
I have a problem with C++.
I want to create two classes, A and B.
Class A has some methods that take an argument that is an instance of class B. But in Class B I also have some methods which take an argument that is an instance of class A.
I tried to forward declare class A and then define class B. Finally, I define class A.
Some code:
class A;
class B
{
void Method1(A* instaceOfA)
{
instaceOfA->MethodX();
}
.......
};
class A
{
Method1(B* instaceOfB);
MethodX();
.......
};
I code in Visual Studio 2010, and it shows an error because I invoke MethodX
in class A but class A is not defined completely.
How can I solve this problem?
Upvotes: 2
Views: 176
Reputation: 8709
Is there a reason you need to implement class B inline? If you seperate the class definitions from the implentations (ideally putting them in .h and .cpp files), this problem will go away..
//blah.h
class A;
class B
{
void Method1(A* instaceOfA);
.......
};
class A
{
Method1(B* instaceOfB);
MethodX();
.......
}l
//blah.cpp
#include "blah.h"
class B
{
void Method1(A* instaceOfA)
{
instaceOfA->MethodX();
}
.......
};
class A
{
Method1(B* instaceOfB)#
{
instaceOfB->Method1();
}
MethodX();
.......
}
Upvotes: 0
Reputation: 4863
Put the definition of B::Method1
after declaration of class A
//header file
class A;
class B
{
void Method1(A* instaceOfA);
.......
};
class A
{
Method1(B* instaceOfB);
MethodX();
.......
};
// cpp file
void B::Method1(A* instaceOfA);
{
instaceOfA->MethodX();
}
This is the purpose of .cpp file. You declare the classes and methods in a header file then, add the definitions to the .cpp file.
Upvotes: 4
Reputation: 509
Is your impl code in the header file? If so, try moving it to a cpp file and #include A and B
Upvotes: 0
Reputation: 10764
I suggest moving implementations of methods outside class declarations, like this:
class A;
class B {
public:
void Method1(A* instanceOfA);
...
};
class A {
public:
void Method1(B* instanceOfB);
void MethodX();
...
};
void B::Method1(A* instanceOfA) {
...
}
Upvotes: 1
Reputation: 409136
Define and declare the classes the other way around?
class B;
class A
{
Method1(B* instaceOfB);
MethodX();
};
class B
{
void Method1(A* instaceOfA)
{
instaceOfA->MethodX();
}
};
Of course, this does not work if the A::Method1
function also is inline.
Upvotes: 0