I'm having trouble figuring out how to call a function from inside a class to a class which holds the object.
It's a bit hard for me to explain, because I'm mixing up the different terminologies, so here's an example of what I mean:
class A
{
A();
B *objectB;
void Function01 (int a);
}
class B
{
B();
void Function02 (int a); //
}
A::A()
{
objectB = new B();
}
A::Function01(int a)
{
//Do things
}
B::B()
{
//.....
}
B::Function02 (int a)
{
//Call to Function01
}
In the above example how would I call Function01 from function02?
Thanks in advance!
class A
{
A()
{
};
int Function1()
{
//Do something
}
}
class B
{
private:
A *objectA ;
public:
B()
{
objectA = new A();
}
void Function2()
{
objectA->Function1();
}
}
but there are other ways such as friend functions and friend classes, I encourage you to look at those.
class A
{
B* b;
void func_a();
A();
//..
};
class B
{
A* owner;
void func_b()
{
owner->func_a();
}
B(A* own) : owner(own)
{}
};
A::A()
{
b = new B(this); // this is the owner
}
But again -- avoid if you can. Ask yourself: "Does B really need to know about A?"
Thanks for the response!
I did try the method you described, but somehow the compiler says that the class name doesn't name a type (even though I included the class header file). I'll take a look at friend classes and friend functions next.
I did try the method you described, but somehow the compiler says that the class name doesn't name a type (even though I included the class header file). I'll take a look at friend classes and friend functions next.
Friends won't help you. Friends just let you get around private/protected access issues. That's not your problem here.
You shouldn't be including carelessly. Instead you should be forward declaring:
1 2 3 4 5 6 7 8 9 10 11 12
// a.h
#ifndef A_H_INCLUDED
#define A_H_INCLUDED
class B; // forward declare
class A
{
// ...
};
#endif // A_H_INCLUDED
1 2 3 4 5 6
// a.cpp
#include "a.h" // include them both here
#include "b.h"
//...
I found the solution to my problem. jsmiths post hinted me that it had something to do with how I included the different headers, so first I tried to include the 'B' class in A's .cpp file instead of in its header. This did the trick.
Forward declaring would not have worked in my case I think, because I used functions of 'B' in 'A'.
Thanks for all the replies!