CPP Polymophism and Abstract Class

What is an Abstract Class in C++?

  • C++ supports the creation of abstract classes by providing the pure virtual method(s).
  • To declare a pure virtual method you must set the virtual keyword in front of the method (as for all virtual methods) and then set the function equals to zero (0) with a semicolon at the end.
    virtual void showMe() = 0;
  • It is illegal to instantiate an object of any class that is an abstract class.
  • It is illegal to instantiate an object of any class that inherits from an abstract class and doesn't implements all of the pure virtual functions.
    Abstract Class example:
    #include <iostream>
    
    class Person {
    public:
      Person (int age, int weight){
        this->age = age;
        this->weight = weight;
      }
      // We makes the showInfo() pure virtual
      // which brings the Person class to be abstract
      // and then we cannot create an object of this class
      virtual void showInfo() =0;
      int getAge() const { return age; }
      int getWeight() const { 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 ShowInfo() must be implemented if we 
      // want to create objects of this Class
      void showInfo() {
        std::cout << "I am an Employee " << age << " years old " ;
        std::cout << "and weighs " << weight << " kilo " ;
        std::cout << "and earns " << salary << " dollar.\n" ;
      }
      int getSalary() const { return salary; }
    private:
      int salary;
    };
    int main() {
      // Even we cannot create a object of the person Class 
      // the Person Class can hold a reference to
      // an object of a drived class that implements the pure virtual function(s).
      Person * pObama = new Employee(45, 65, 50000);
      pObama->showInfo();
      std::cout << "\n" ;
      return 0;
    }
    When we run this application, the result will be:
    I am an Employee 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.