-2

so I have two classes, let's say class A and class B. In class B's constructor I create an object of type A(private). In class A I have a member function that displays the content of A, void displayA().

Now i run int main(), I create an object of type B(ideally also object of type A stored in B). My question is how do i use the method in A through B?

I tried objB.displayA(), but that obviously didn't work. Do I need to create a member function in B that calls member function in A? Or is there a more elegant solution

jabk
  • 1,388
  • 4
  • 25
  • 43

3 Answers3

2

class B must have a member variable of type class A. For example:

class B
{
public:
    A a;
    int x;
};

Then you can call it like this:

B objB;
objB.a.displayA();
M.M
  • 138,810
  • 21
  • 208
  • 365
  • didn't know about that, thanks :) But what if the `object a` is private? do i need a getter? – jabk Sep 30 '14 at 09:05
  • Yes. Instead of a pure `getter` (they're often not a great idea) consider having B have a function that calls `a.displayA`. If you put in getters etc. for every function of `a` then you may as well make `a` public. – M.M Sep 30 '14 at 09:17
1

You either need to pass objB the instance of class A that you are changing, and then inside the function that you pass it, call obA.displayA();, or you could create objA as a class variable of objB, and then call objA.displayA(); in any of the functions of B.

Yann
  • 978
  • 2
  • 12
  • 31
1

first, do you no public and private? and ,you in your class B,is it have variable which type is class A; like this

#include <iostream>
class A
{
    public:
        void displayA() {
            std::cout << "call a" << std::endl;
        }   
};

class B
{
    public:
        B():a(){}
        A a;
};
int main(int argc, const char *argv[])
{
    B b;
    b.a.displayA();
    return 0;
}

and than thd class B also can be:

`class B
 {
  public:
      B():a(){}
      A a;
      void call() {
          this -> a.displayA();
      }
  };`

and than call the call() which in class B

ipaomian
  • 319
  • 2
  • 12
  • they are private, sorry – jabk Sep 30 '14 at 09:07
  • you means the variable of a is private?and the code above the secend class B can call the displayA(),0.0 – ipaomian Sep 30 '14 at 09:11
  • object a is private. Only constructors and member functions are public. Should i then add a getter for object a? – jabk Sep 30 '14 at 09:16
  • yes ,it can get the private var a,you had better to read [this](http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance),and [this](http://www.parashift.com/c++-faq/access-rules.html)it can be resolve you problem,:) – ipaomian Sep 30 '14 at 09:20