Downcasting in C++;

Hi,

When we study Object-Oriented Programming languages, more specifically C++, we commonly see that a pointer for a derived class can safely be casted to its base class. This called upcasting. (‘Up’ due to the class hierarchy, we are climbing up this hierarchy).

Usually, a derived class may have new methods that are not present in the base class. And, sometimes we need to access such methods from a base class pointer. This is called downcasting. (‘Down’ because we are going down in the class hierarchy). Well, How can we do that? In C++, this done by using dynamic_cast keyword.

More definitions on (Up/Down)casting:

Upcasting Definition: Upcasting is converting a derived-class reference or pointer to a base-class. In other words, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, without an explicit type cast. This is a result of the is-a relationship between the base and derived classes.

Downcasting Definition: The opposite process, converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting. Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn’t apply to the base class.

Quick example (originally defined here):

class Parent {
public:
  void sleep() {
  }
};

class Child: public Parent {
private:
  std::string classes[10];
public:
  void gotoSchool(){}
};

int main( ) 
{ 
  Parent *pParent = new Parent;
  Parent *pChild = new Child;
    
  Child *p1 = (Child *) pParent; 
  Parent *p2 = (Child *) pChild; 
  return 0; 
}

So, we can make use of the function gotoSchool() by doing:

Child *p = dynamic_cast<Child *>(pParent);

That’s all,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s