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();
}
-
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(); }
-
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.
-
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.
0 comments:
Post a Comment