If you want to use some functions provided by ClassA from ClassB, then you can do it this way
ClassB::methodB()
{
ClassA objectA;
if(test_condition)
objectA.methodA();
}
ClassB::methodB()
{
ClassA objectA;
if(test_condition)
objectA.methodA();
}
To copy to clipboard, switch view to plain text mode
This is sufficient if methodA() is defined in public interface, if methodA() is a private, then declare ClassB as friend of ClassA.
If you feel by design that ClassB is a kind of ClassA with added functions / features, then make methodA() as protected in ClassA and derive ClassB from ClassA, then no need to declare as friend.
from your example code, looks like you need have a kind of parent-child / or ownership relationship between ClassA and ClassB then you can use as in this example
//ClassA.h
class ClassB;
class ClassA
{
public:
ClassA();
void methodA();
private:
ClassB* memberB;
};
//ClassA.cpp
#include "ClassA.h"
#include "ClassB.h"
ClassA::ClassA() : memberB(new ClassB(this))
{
}
ClassB::methodA()
{
//do anything, except calling memberB->methodB(), this will cause recurssion
}
//ClassB.h
class ClassA;
class ClassB
{
public:
explicit ClassB(ClassA * parent);
methodB();
private:
ClassA* parentA;
}
//ClassB.cpp
#include "ClassA.h"
#include "ClassB.h"
ClassB::ClassB(ClassA * parent) : parentA(parent)
{
;
}
ClassB::methosB()
{
parentA->methodA();
}
//ClassA.h
class ClassB;
class ClassA
{
public:
ClassA();
void methodA();
private:
ClassB* memberB;
};
//ClassA.cpp
#include "ClassA.h"
#include "ClassB.h"
ClassA::ClassA() : memberB(new ClassB(this))
{
}
ClassB::methodA()
{
//do anything, except calling memberB->methodB(), this will cause recurssion
}
//ClassB.h
class ClassA;
class ClassB
{
public:
explicit ClassB(ClassA * parent);
methodB();
private:
ClassA* parentA;
}
//ClassB.cpp
#include "ClassA.h"
#include "ClassB.h"
ClassB::ClassB(ClassA * parent) : parentA(parent)
{
;
}
ClassB::methosB()
{
parentA->methodA();
}
To copy to clipboard, switch view to plain text mode
Bookmarks