Class B
has some group of methods trait1
. Class B1
and C1
has similar group of methods trait2
. trait2
is derived from trait1
.
How can I implement this? I was going to move all of these trait
s methods out from the main hierarchy into some separate one. Then derive B
, B1
and C1
from appropriate trait. But then I realized that there would be a problem with inheriting B1
from B
because B1
would have trait1
too.
Now I think I can have some field of type, say, TraitBase
, and initiate it with appropriate ctor of type either trait1
or trait2
. But I don't like the idea that I should have a field so my class has some special behaviour. May be there is another solution? Thank you.
UPDATE
I mean class B
has some feature, which is derived in B1
. C1
should have the feature, which class B1
has.
class B
{
virtual foo1();
virtual foo2();
virtual trait_method1(); //implementation 1
virtual trait_method2(); //implementation 1
};
class B1 : public B
{
virtual foo1();
virtual foo2();
virtual trait_method1(); //implementation 2
virtual trait_method2(); //implementation 2
};
class C1 : public C
{
virtual bar1();
virtual bar2();
trait_method1(); //implementation 2
trait_method2(); //implementation 2
};
Your problem may be solved by virtually inheriting from trait1:
class trait2 : virtual public trait1{} class B : public A, virtual public trait1{} class B1 : public B, public trait2{} class C1 : public C, public trait2{}
However, this design only makes sense if class trait1 is stateless. If not, consider different designs, maybe Bridge pattern.
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.