0

What is the syntax for calling a method in an owning object from an owned object in c++?

Parent class:

class Parent
{
private:
    Child child;

public:
    Parent()
    {
        addChild(child);
    }

    void MethodToBeCalled(int someArgument)
    {

    }
};

Child class:

class Child
{
private:
    void myVoid()
    {
        //Call parent method somehow
    }

public:
    Child()
    {

    }
};

I tried to make my question as simple and generic as possible (to be of benefit to as many as possible). Let me know if I can make it even clearer.

Thank you!

distractedhamster
  • 689
  • 2
  • 8
  • 22

3 Answers3

3

Here's a example. I had to modify your code a bit to get it compile:

class Component {};

class Parent;

class Child   : public Component
{
private:
    inline void myVoid();
    Parent &parent_ref;

public:
    Child(Parent &pr) : parent_ref{pr} {}
};

class Parent   : public Component {
private:
    Child child;

public:
    Parent() : child{*this}
    {
        // addChildComponent(child);
    }

    void MethodToBeCalled(int someArgument)
    {

    }
};

inline void Child::myVoid()
{
    parent_ref.MethodToBeCalled(1);
}
kec
  • 2,099
  • 11
  • 17
2

If you are sure that your Child object is a member subobject of Parent class (as in your example), you can use the container_of trick (see Understanding container_of macro in the Linux kernel)

class Child
{
private:
    void myVoid();
};

class Parent
{
public:
    Child child;

    void MethodToBeCalled(int someArgument)
    {
    }
};

void Child::myVoid()
{
    container_of(this, Parent, child)->MethodToBeCalled(42);
}

Obviously, tricks like this immediately restrict the usability of your Child class to always being a member of Parent class (at least when you intend to call myVoid() method on it).

A much better idea would be to just pass a reference to parent object to child object.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

In your case, you can't, because Child and Parent have nothing in common except that they both inherit Component. Child has to have a Parent object in order to call MethodToBeCalled().

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • I've heard that it should be possible by sending a reference to the parent in the childs constructor. But I don't understand what that syntax would look like? – distractedhamster Mar 26 '16 at 16:57
  • 1
    Create a `Parent` object in your class, then you can add an argument to the construtor `Child(Parent& parent)`. Then you can set the parent object from your class to that parent (`this->parent = parent;` for example). After you can call `MethodToBeCalled()` like this `parent.MethodToBeCalled(0);` – Rakete1111 Mar 26 '16 at 17:00
  • Thank you! This comment is the closest to what ended up working for me. – distractedhamster Mar 26 '16 at 20:02