Based on the is-a relationship between derived and base classes, implicit casting from derived class to base class is always possible for public inheritance (not possible for protected or private inheritance).
class Base {}; class Derived: public Base {}; Derived d; Base b = d;
Without use of keywords, we may have 3 ways to convert unrelated class types.
- Corresponding constructor
- Overload assignment operator
- Overload type casting operator
Here is a sample code I wrote for testing. Note that the "=" sign in declaration is not assignment operator. Initialization, assignment, and explicit casting are all legal for Approaches 1 and 3, but only implicit casting by assignment is legal for Approach 2 with overloaded operator "=".
Related Posts:
Type Casting in C++
static_cast, dynamic_cast, and reinterpret_cast
Assignment between Class Objects
No comments:
Post a Comment