Search code examples
c++oopinheritancecomposite

C++ Inheritance & composition used together


I have class A, having methods that update properties of B. So, I need inheritance.

class B{
public:
int x;
};

class A : public B{
public:
void update(int y){
x = y;
}
};

I also want to reach function "update" through class B, so I also need composition.

class B{
public:
A a;
int x;
};

class A : public B{
public:
void update(int y){
x = y;
}
};

I want my structure as such, so that I want to track properties of objects-type Bs this way:

...
B.a.update(5);
int n = B.x;

However, I cannot use composition before declaring class A, and cannot use inheritance before declaring class B. What should I do to resolve this infinite loop ?


Solution

  • I am not sure what exactly you are trying to achieve here, but if I'm guessing correctly, what you might need is a virtual function:

    class B{
    public:
    int B;
    virtual void update(int x){
        B = x;
    }
    };
    
    class A : public B{
    public:
    virtual void update(int x){
        // Here goes code specific to B-class.
        B::update(x);
        // or here ;)
    }
    };
    

    btw, you probably don't want int B field in a public: section; if you modify it's value from update method, you probably don't want others to try to modify it directly.