I have a question regarding composition and inheritance in C++:
I have a base class 'A'
and a derived class 'B'
( 'B'
inherits members from 'A'
), is it possible use 'B'
as a member of 'A'
by composition?
As to "A has B member, B derived from A": Practically, you cannot declare such a thing. If class A has a member of type B, then B needs to be declared before A. If B uses A as a base, A must be declared before B.
As to composition, if you wanted to do such a thing, you could have to use indirection (pointer, smart-pointer, etc).
class B;
class A {
B *b;
};
class B : public A {
};
One might argue that (in C++) using pointers is not composition; however, in Java, all Objects are "pointers", so composition is:
class A {
B b;
}
class B extends A {
}
However you may embed a B*
field. Hence a const B&
should be possible too, and behave like a B
. (Mind I am now a sandbox java programmer.)
class B;
class A {
B& b;
};
BTW you might not even embed an A in an A.
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.