inheritance - C++: Declaring pointer to base and derived classes -
i found confused 1 basic question in c++
class base {  };  class derived : public base {  }  base *ptr = new derived();    what mean? ptr pointing base class or derived class? @ line, how many memory allocated ptr? based on size of derived or base?
what's difference between , follows:
base *ptr = new base(); derived *ptr = new derived();   is there case this?
derived *ptr = new base();   thanks!
to understand type system of c++, important understand difference between static types , dynamic types.  in example, defined types base , derived , variable ptr has static type of base *.
now when call new derived(), pointer static , dynamic type of derived *.  since derived subtype of base can implicitly converted static type of base * , assigned ptr static types match.  dynamic type remains derived * however, important if call virtual function of base via ptr, calling virtual functions based on dynamic type of object, not static type.
Comments
Post a Comment