0
class Base
{
  public:
     Base(){}
     virtual void f() {};
}

class Derived : public Base
{
   public:
      Derived() {}
      virtual void f() {}
}

int main()
{
   Base *obj = new Derived();
   obj->f();

   return 0;
}

Well, this type of behaviour is called upcasting or downcasting?

What is upcasting and downcasting?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

3

This is upcasting.

Upcasting is basically “widening” or casting up the tree, (parents), while downcasting is “narrowing” or specialization, casting down the tree (children)

Or you can say upcasting is derived -> base type. Downcasting is base -> derived type.

For example

Animal * a = new Dog();

is upcasting,

whereas

(Dog *) a 

is downcasting (since a was defined as Animal *)

srv236
  • 509
  • 3
  • 5
  • In C++, usually downcasting is done like `dynamic_cast(a)` to take advantage of the run time type information to ensure the downcast is legitimate. – Eljay Aug 29 '20 at 11:56