I am reading some C++ text and got the following code:
class A { };
class B : public A { };
void main() {
A* p1 = new B; // B may be larger than A :OK [Line 1]
B* p2 = new A; // B may be larger than A :Not OK [Line 2]
}
I have 2 questions:
Well, "larger" is not the key here. The real problem is "is a" relationship.
Any object of class B
is also of type class A
(class B
is also class A
due to inheritance), so the first line is okay (the pointer to class A
can just as well point to an object of class B
), but the inverse is not true (class A
is not class B
and might even have no idea of class B
existence), so the second line won't compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With