views:

29

answers:

2

Hi,

I have 3 function in my class B. These three function have to access member function of other class A.

I did this by creating object of class A in class B constructor and tried to access that object in functions of class B. But its showing error.

How can i assess the same object in these three functions. Where i have to create object of class A

B::B()
{ 
  A a;
 }
B:: function()
{
 a.fun(); //fun belongs to class A
}
B:: function1()
{
 a.fun1(); //fun1 belongs to class A
}

I am getting error, How can i implement the same where i can access object a in both function.

+1  A: 

You need to make a a member variable of class B like this:

class B
{
private:
    A a;

// ...
}

That will make it available to all the member functions of B.

(Making it private isn't necessary - the decision to make it private, protected or public depends on whether you want to make it available only within B, within B and B's derived classes, or everywhere.)

RichieHindle
+3  A: 

You should add A as a member of your B class, and not as a local variable of the B constructor. Try this:

class B
{
public:
  B();
  void function1();

private:
  // This is your member, and you can access it from all of B's methods.
  A m_a;
};
Asaf