简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM