Mahi
Mahi

Reputation: 473

How to access a data member and a member function from a member function of another class?

if i write a class-

class A
{
    int x;
    void show()
    {
       cout<<a;
    }
};

int main()
{
   A a;
   a.show();
   a.x;
}

But If another class B is ther then how the member function of A accessed inside member function of class B-

class B
{
    int y;
    void display()
    {
       cout<<y;
    }
};

Plz reply.

Thanks..

Upvotes: 0

Views: 2277

Answers (2)

beduin
beduin

Reputation: 8273

At first, your example isn't right.

class A
{
    int x; // x is private
    void show() //show is private also
    {
       cout<<a;
    }
};

int main()
{
   A a;
   a.show(); //you can't access private members from outside
   a.x;
}

Considering you question: to access class A members inside another class member function you can:
1. instantiate class A instance inside class B member function
2. make desired class A members static, so you need not to provide class A object to access this members.

class A {
public:
// ...
stativ void do_stuff() {}
};

class B {
//....
void do complicated stuff() {/*...*/ A::do_stuff();}
};

Upvotes: 1

simpatico
simpatico

Reputation: 11107

The same way as in your main.

   class B{
...
  void foo(){
    A a;
    a.show();
  }
}

Interesting reading about inheritance and friendship in C++.

Upvotes: 1

Related Questions