Things You'll Need:
- C++ development environment software
-
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.
-
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().
-
Step 3
Compose a generic function that takes in objects of type "Shape." The function can call Shape::Draw().
-
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
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.