tags:

views:

2180

answers:

3

I am trying to make a call to a Parent class method from a contained object, but have no luck with the following code. What is the standard way to do it?

I have searched around and this seems to work for inherited objects, but not for contained objects. Is it right to call it a Parent class even? Or is it called an Owner class?

class Parent{
private:
  Child mychild;

public:
  void doSomething();
}

class Child{
public:
  void doOtherThing();
}

void Child::doOtherThing(){
  Parent::doSomething();
}
+5  A: 

A contained object has no special access to the class that contains it, and in general does not know that it is contained. You need to pass a reference or a pointer to the containing class somehow - for example:

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

void Child::doOtherThing( Parent & p ){
   p.doSomething();
}
anon
A: 

If the child needs to interact with the parent, then it will need a reference to that object; at present, the child has no notion of an owner.

Rob
+1  A: 

The child has no connection to the parent class at all. You'll have to pass 'this' down to the child (probably in the constructors) to make this work.

Promit