C ++ how to call a parent class method from an contained class?

I am trying to make a call to a method of the Parent class from the contained object, but you are out of luck with the following code. What is the standard way to do this?

I searched around, and this seems to work for inherited objects, but not for contained objects. Is it right to call a parent class? Or is it called the owner class?

class Parent{
private:
  Child mychild;

public:
  void doSomething();
}

class Child{
public:
  void doOtherThing();
}

void Child::doOtherThing(){
  Parent::doSomething();
}
+3
source share
3 answers

And the containing object does not have special access to the class that contains it, and does not know at all that it is contained. You need to pass a link or pointer to the containing class somehow - for example:

class Child{
public:
  void doOtherThing( Parent & p );
};

void Child::doOtherThing( Parent & p ){
   p.doSomething();
}
+11
source

. 'this' (, ), .

+1

If the child needs to interact with the parent, he will need a link to this object; currently the child has no concept of owner.

0
source

Source: https://habr.com/ru/post/1707568/


All Articles