C++
  Home arrow C++ arrow Page 4 - Polymorphism in C++
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Polymorphism in C++
By: Gabor Bernat
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 7
    2009-06-16

    Table of Contents:
  • Polymorphism in C++
  • Pointers
  • Downcasting
  • The Virtual Keyword

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Polymorphism in C++ - The Virtual Keyword


    (Page 4 of 4 )

    The correct solution is to apply the virtual keyword. The direct effect of this on the pointed function is that, on functions from the base classes, rather than being redefined, it will be overwritten.

    We will declare as virtual our function inside the base class.

     

    virtual bool appendToStream(stringstream& inTo) const;

     

    Once you declare a function virtual, it will remain virtual in all of the derived classes and the classes derived from the derived class; once virtual, always virtual, to sum it up. The real strength in this solution is that, for all functions declared like this in the base class, when we have a base pointer pointing to a derived object, the called function will be declared.

    By just adding the virtual keyword in front of the appendToStream function declaration, the same code entered inside the main function at the end of the Pointers segment of this article will now call the derived objects class function, and produce a very different result:

     

    2

    CarContainer

    Car Type: Lamborghini Murcielago

    Car Value : 313000

     

     

    Press any key to continue . . .

     

    Now we have the general usage. Imagine the same when we have a stream of incoming pointers to derived classes through base class pointers; for instance, a vector of base class pointers. If we decide to add a new class, if we overwrite for the virtual function, we do not need to modify a single character in the vector handling. All of this will be done by the compiler in the background. Here is a fast example:

     

    BananaContainer banana(1, 1, 50);

    CarContainer car(2, "Lamborghini Murcielago", 313000);

    EmptyContainer empty(3);

     

    stringstream inTo;

     

    std::vector<BaseContainer*> allContainer;

    allContainer.push_back(&banana);

    allContainer.push_back(&car);

    allContainer.push_back(&empty);

     

    std::vector<BaseContainer*>::iterator it, end;

    for (it = allContainer.begin(), end = allContainer.end();

    it != end; ++it)

    {

    (*it)->appendToStream(inTo);

    }

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

     

    We can also decide to not overwrite the virtual function, as by default in this scenario the base class's function will be used. This is the case of the EmptyContainer, for which I decided to not write this function, and as follows, only the ID of the container is printed on the screen of your computer. In addition, the following appears on the console:

    1

    BananaContainer

    Price per box: 1

    Number of boxes 50

     

    2

    CarContainer

    Car Type: Lamborghini Murcielago

    Car Value : 313000

     

    3

     

    Press any key to continue . . .

     

    Here, in a downloadable form, is the code for all of this written in Visual Studio 2008. It will work under any C++ compiler as long as you build a new empty console project and add these files to it. Be aware that it already contains some stuff that will be covered in the next article, so if you happen to bump into something that is not covered here, wait a little while. Nevertheless, feel free to try the things I have shown you in this article.

     

     

    Take the time to understand the content I offered to you today. I've just scratched the surface of polymorphism and virtual functions. Feel free to post your comment here on the blog.

    Live with Passion!”


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

     

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek