Reputation: 243
Can I convert compatible non-pointer objects without actually defining a cast operator? So if B inherits from A:
A a;
B b;
Will (A)b
compile if I donot provide my own cast operator?
Edit: It does seem to compile. Is it because there is a default conversion cast operator or the compiler recognizes the compatibility and uses the default copying constructor or assignment operator in assignments for example?
Upvotes: 1
Views: 531
Reputation: 76266
Yes, it does compile (http://ideone.com/CXbeh0)
By default A
is copyable. The copy constructor has signature A::A(A const &)
. Since instance of B
is implicitly convertible to A const &
, the cast will be resolved using A
's copy constructor.
The conversion to reference applies to the (also implicitly generated) copy assignment operator too, so a = b
again compiles using A &A::operator=(A const &)
.
Keep in mind, that the new object is of type A, not B, so it does not contain any additional information the original instance of B did. That is rarely what you want.
On a side-note, it is recommended in C++ to forget that C-style cast exists and use the more specific cast types of C++:
static_cast
, for compatible types only.dynamic_cast
for upcasting pointers/references with run-time
check.const_cast
to only handle const.reinterpret_cast
if you really need to play pointer tricks, but beware of aliasing rules.Upvotes: 3
Reputation: 98358
By no user-defined constructors or operators are defined, then:
(A)b
will be implemented as if:
A(b) //Calls A copy-constructor: A::A(const A&)
That is, it will create a temporary of A copy-constructing from the argument.
This is called object splicing and it is usually a bad idea, because you are copying some fields of B, but not others. YMMV.
Upvotes: 0