eHow launches Android app: Get the best of eHow on the go.

How To

How to Create Interchangeable Objects With Polymorphism

Contributor
By eHow Contributing Writer
(7 Ratings)

In object oriented programming (OOP) a derived class is treated as if it were its base class. This allows programmers to write generic code that is decoupled from type-specific information. Polymorphism, one of the basic features of C++, lets the right code get executed. This happens because of the virtual keyword identifying the member functions of the base class. "Virtual" tells the compiler to perform late binding so that when a function is called at runtime the correct code is executed.

Difficulty: Challenging
Instructions

Things You'll Need:

  • C++ development environment software
  1. Step 1

    Write the base class using your chosen C++ development environment software. This will be the class used to create, or derive, other classes. Give it functionality by defining member functions. Use action words to label the member functions like "Read" and "Check." Label the member functions to the left with the "virtual" keyword.

  2. Step 2

    Code the classes that derived from the base class. If you created "Shape" as being your base class, then "Circle," "Square" and "Triangle" will inherit its member functions. The "virtual" keyword ensures that Circle::Draw() will run the code of Circle and not the code of Shape::Draw().

  3. Step 3

    Compose a generic function that takes in objects of type "Shape." The function can call Shape::Draw().

  4. Step 4

    Use the function in Main(). Because of the polymorphic behaviour by the "virtual" keyword it knows what shape to draw without C++ code like, "if you are a circle execute this code," "if you are a square execute this code" or "if you are a triangle execute this code."

Comments  

davidjames said

Flag This Comment

on 1/7/2009 This article contains errors; calling Circle::Draw() will always call that function no matter how the objects are setup - you don't need the virtual keyword to make this happen. The virtual keyword helps with things like: Circle * myCircle = new Circle(); Shape * myShape = myCircle; myShape->Draw(); (calls Circle::Draw() if Draw was defined as virtual in the Shape class. Also, the code examples cannot be well formatted using the eHow article fomat.

Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

eHow Computers
eHow_eHow Technology and Electronics