CPP Polymorphism and Virtual Methods

What is Polymorphism in C++?

  • Poly means many, and morph means form: A polymorphic function is many-formed.
  • Polymorphism works only with pointers or references.
  • Building polymorphism is :
    • the capability to bind specific derived class objects to base class pointers at runtime.
    • the fundament to this is Use of virtual methods in derived classes.
  • It is important to understand the differences between:
    Class A Class is a specification for a specific type of objects (class example: Person, Car, Animal, ...). They are also referred as complex types.
    Example:
    class Person {
            // here comes the class specification
    };
    Object An Object is an occurrence that is created with a Class specification.
    Example:
     Person * pObama = new Person();

    The "new Person();" creates an object of the Person Class and returns a pointer reference to that object.
    Reference A Reference tells us that it has an relation to an object created with a Class of the same type as the Reference or an object created with a Class that is a subclass of the Reference.
    Example:
     Person * pObama = new Employee(45, 65, 50000);

    In this case: pObama is a Person Reference that holds a pointer to an Employee Object, which is created by a drived Class, Employee, of the Person Class.
  • With Polymorphism we want to execute methods for the created object of a Class even the Reference is of the same Class or a base Class of that Class.
    Example:
    shape.getArea() length * width, if shape is a reference to a Rectangle object.
    shape.getArea() radius * radius *PI, if shape is a reference to a Circle object.
    To achieve this kind of Polymorphism we need virtual methods.

What is Virtual Methods?

  • In Java is Polymorphism by default built-in, but in C++ we can build the control of the Polymorphism as we want.
  • To achieve the polymorphic functionality we make overridden methods virtual.
  • A method is virtual if when we write the virtual keyword in front of the method.
  • When a method in a class is made virtual all overridden methods in the subclasses are also virtual.
  • It is not necessary to write virtual in front of a virtual methods in the derived class, but a good practice to do that.
  • Note that the virtual function magic operates only on pointers and references.
    Polymorphism and virtual methods example:
    #include <iostream>
    
    class Person {
    public:
      Person (int age, int weight){
        this->age = age;
        this->weight = weight;
      }
      // this method is made virtual
      virtual void showInfo() {
        std::cout << "I am " << age << " years old " ;
        std::cout << "and weighs " << weight << " kilo.\n\n" ;
      }
      int getAge() { return age; }
      int getWeight() { return weight; }
    protected:
      int age;
      int weight;
    };
    
    class Employee : public Person {
    public:
      Employee (int age, int weight, int salary): Person(age,weight){
        this->salary = salary;
      }
      // The base has made this method virtual
      void showInfo() {
        std::cout << "I am " << age << " years old " ;
        std::cout << "and weighs " << weight << " kilo " ;
        std::cout << "and earns " << salary << " dollar.\n\n" ;
      }
      int getSalary() { return salary; }
    private:
      int salary;
    };
    int main()
    {
      Employee Rune(35, 95, 40000);
      Person & Bengt=Rune;
      // As the showInfo method is virtual 
      // the Employee showInfo() will be executed
      // as Bengt is a reference to an object of Employee
      Bengt.showInfo();
    
      Person * pRicard = new Person(40, 70);
      pRicard->showInfo();
    
      delete pRicard;
      Person * pObama = new Employee(45, 65, 50000);
      // As the showInfo method is virtual 
      // the Employee showInfo() will be executed
      // as pObama is a pointer reference to an object of Employee
      pObama->showInfo();
      delete pObama;
    
      return 0;
    }
    When we run this application the result will be:
    I am 35 years old and weighs 95 kilo and earns 40000 dollar.
    
    I am 40 years old and weighs 70 kilo.
    
    I am 45 years old and weighs 65 kilo and earns 50000 dollar.

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.