Chain initialization without temporary pointers
An object of class A
is constructed fr开发者_Python百科om an object of class B
, which is inherited by class C
. How can I create an A
object without temporary pointers to the B
object?
B *my_b = new C();
A *my_a = new A( *my_b );
// but *my_b is only used here
Update: The constructor of A
takes a B
as the argument, not a C
.
If you don't need to retain the object of type B
and class A
constructor copies the object and doesn't instead store a reference to it:
A* my_a = new A( B() );
otherwise you can't do anything much better than what you're doing already.
Don't use new
unless you have a reason to.
A my_a = A( B() );
Or if there is a reason to new
my_a:
A * my_a = new A( B() );
精彩评论