Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about Types Conformity in C++?

Tags:

c++

types

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:

  1. I do not understand what the author mean by commenting in Line 1 and Line 2
  2. Why can't we do in Line 2?
like image 404
ipkiss Avatar asked Jul 07 '11 09:07

ipkiss


1 Answers

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.

like image 58
sharptooth Avatar answered Sep 28 '22 11:09

sharptooth