1

I've got a parent class, child class and inside this child class I've defined some struct. Within this struct I'd like to call parent method. Is it possible?

class Parent
{
public:
    int foo(int x);
}

class Child : public Parent
{
public:
    struct ChildStruct {
        int x;

        int bar(int y) {
            return GET_CLASS_CHILD->foo(this->x + y);
        }
    };
}

Is something like this possible in C++? Then how to achieve it?

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
Honza
  • 939
  • 2
  • 11
  • 28

1 Answers1

5

You have to pass to ChildStruct a reference or a pointer to the owner class instance:

class Child : public Parent
{
public:
    struct ChildStruct {
        int x;
        Child& owner;

        ChildStruct(Child& owner_) : owner(owner_) {}

        int bar(int y) {
            return owner.foo(this->x + y);
        }
    };
};

That said, it looks like what you really need is a lambda function.

Anton Savin
  • 40,838
  • 8
  • 54
  • 90