Home arrow C++ arrow Page 3 - Polymorphism in C++

Polymorphism in C++

If you are new to the world of object-oriented programming, then your first thought after reading the title of this article is "what the heck could ever transform in code?" The answer is not so trivial that I can explain it in just a sentence, but join me throughout this article and you will get the idea.

Author Info:
By: Gabor Bernat
Rating: 4 stars4 stars4 stars4 stars4 stars / 18
June 16, 2009
  1. · Polymorphism in C++
  2. · Pointers
  3. · Downcasting
  4. · The Virtual Keyword

print this article

Polymorphism in C++ - Downcasting
(Page 3 of 4 )

The problem remains: how we can access, from a base pointer pointing to a derived object, the derived object's functions? One solution is downcasting. You use the dynamic_cast keyword.

The method is simple. This safe casting method will try to cast the input pointer into the specified type of pointer. If this is possible (there exists an is a relationship between them), it will return a correct pointer; otherwise, it will return NULL. Now we will cast out the base pointer into a derived type. Append the following lines after the earlier ones.


inTo.str(""); //clean the stream


CarContainer* carP = NULL;

carP = dynamic_cast<CarContainer*>(baseP);

if (baseP)



cout << inTo.str() << endl;



cout << "The base pointer does not points to a CarContainer Object" <<endl;



The new result allows us to do what we wanted to accomplish.






Car Type: Lamborghini Murcielago

Car Value : 313000



Press any key to continue . . .


This will produce a function call for the base, but this is far from polymorphism, and we would need to try to test for each existing derived class from the base. When you have a hundred derived classes, you dont want to try this, and besides, this will lead to a switch-like logic in programming, making the code less readable and maintainable in the future when the hierarchy is expanded.

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials