PDA

View Full Version : How to access to methods of parent class



tonnot
28th June 2011, 19:45
I dont know if what I want have to be done using inheritance or simply writing correct 'friend' keyword.

I have the next code :

ClassA
public :
void methodA
private :
ClassB my_classb


ClassB
void methodB


void ClassB::methodB
{
if (condition)
classB.methodA ();
}

As you can see I'd want to acces to a methodA from metodB.
I can do the work using inheritance, but I would not want access to all public members, only to one of them.
I have see also the friend keyword, but I dont know how to write the correct code.

I'm sure that this is easy to do, but I dont find the way.
Any help will be appreciated.

mvuori
28th June 2011, 22:15
If the methodA could and is designed to be used in that way (which would me no reference or dependence to the members of class A), it should be made either 1) a function or 2) a static method of a third utility class.

Santosh Reddy
29th June 2011, 03:25
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();
}

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();
}

tonnot
29th June 2011, 07:04
Thanks.
ClassB(ClassA * parent); can be the solution.