3

I have this simple code where two inner classes are depending on each other. I can't call object's functionB() inside of functionC() although as you can see I have created a pointer to an object of ClassB and even instantiated the object yet I still get the error that I need to call the function from an object. I was wondering what exactly am I doing wrong here?

#include <iostream>
class ClassA
{
public:
    ClassA() { object = new ClassB(); };
    ~ClassA();
    void functionA() {  };
private:
    class ClassB
    {
    public:
        void functionB() { std::cout << "Function B"; };
    };
    class ClassC
    {
    public:
        void functionC() {
            std::cout << "Fuction C";
            object->functionB();
        }; //Error here
    };
    ClassB* object;
    ClassC* object1;
};
zwya
  • 33
  • 1
  • 4

2 Answers2

5

C++ simply does not capture its "parent" instance, as e.g. Java does. In the nested ClassB and ClassC you need an explicit back-reference to ClassA:

class ClassA {
public:
    ClassA() : object(new ClassB(*this)) {}
    ~ClassA() { delete this->object; }
private:
    class ClassB {
        classA &parent;
    public:
        ClassB(classA &parent) : parent(parent) {}
    };
    ClassB *object;
};

But why do you allocate ClassB in here dynamically? This is easier to read and understand and less error prone:

class ClassA {
public:
    ClassA() : object(*this) {}
    ~ClassA() {}
private:
    class ClassB {
        classA &parent;
    public:
        ClassB(classA &parent) : parent(parent) {}
    };
    ClassB object;
};
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • 1
    Thank you very much. That fixed it. That's what I get for starting with java I guess. – zwya Apr 20 '16 at 16:40
  • Hehe, Java does a lot implict magic behind the scenes. C++ tends to be more explicit. What is better is a matter of taste I guess. – Kijewski Apr 20 '16 at 16:45
  • I had it first without the pointers and then when I got the error, I decided to change to it pointers thinking it would work. – zwya Apr 20 '16 at 16:51
3

I would say, the error text is misleading. But in essence it means that there is no way to access parent object from child object, unless parent object is specifically captured in child's member.

The code has a big problem with the incorrect management of pointers (see rule of 5), but since I take this is for illustration only, I won't focus on it.

SergeyA
  • 61,605
  • 5
  • 78
  • 137