Search code examples
c++virtualabstract-classupcasting

What are the disadvantages of "upcasting"?


The purpose of an abstract class is not to let the developers create an object of the base class and then upcast it, AFAIK.

Now, even if the upcasting is not required, and I still use it, does it prove to be "disadvantageous" in some way?

More clarification:
From The Thinking in C++:

Often in a design, you want the base class to present only an interface for its derived classes. That is, you don’t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. This is accomplished by making that class abstract,

By upcasting, I meant: baseClass *obj = new derived ();


Solution

  • Upcasting can be disadvantageous for non polymorphic classes. For example:

    class Fruit { ... };  // doesn't contain any virtual method
    class Apple : public Fruit { ... };
    class Blackberry : public Fruit { ... };
    

    upcast it somewhere,

    Fruit *p = new Apple;  // oops, information gone
    

    Now, you will never know (without any manual mechanism) that if *p is an instance of an Apple or a Blackberry.

    [Note that dynamic_cast<> is not allowed for non-polymorphic classes.]