ClassA *ptrA = &objB; // Question1
Why this assignment is valid?
Because that's how polymorphic inheritance works. A ClassB
is a ClassA
; so a reference/pointer to ClassB
can convert to a reference/pointer to ClassA
.
ptrA = (ClassA*)&objB;
That's doing the same thing, but making the cast explicit. This is much more dangerous though - the evil C-style cast will allow any pointer conversion, whether or not it's valid, while the original implicit conversion will only allow safe conversions (as the derived-to-base pointer conversion is).
ptrA = new classB;
That creates a dynamic object, giving you a pointer to that; the original sets the pointer to point to an existing object. Don't use new
unless you really need it.
ClassA objA = *ptrA // Question2
This is sometimes known as slicing. If the base class is copyable (as it presumably is here), then the base sub-object can be copied to make a new object of that type. Technically, *ptrA
is converted to a reference to ClassA
(since such a conversion is allowed, just as the previous pointer conversion is); then that reference is used to copy-initialise objA
.
Slicing can cause confusion; but it's not an issue if you only use abstract base classes, since they can't be instantiated directly.