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:
- I do not understand what the author mean by commenting in Line 1 and Line 2
- Why can’t we do in Line 2?
Well, “larger” is not the key here. The real problem is “is a” relationship.
Any object of
class Bis also of typeclass A(class Bis alsoclass Adue to inheritance), so the first line is okay (the pointer toclass Acan just as well point to an object ofclass B), but the inverse is not true (class Ais notclass Band might even have no idea ofclass Bexistence), so the second line won’t compile.