***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

Abstract classes

An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.

The purpose of an abstract class is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.

Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.

 

#include <iostream.h>

// Base class

class Shape {

   public:

      // pure virtual function providing interface framework.

      virtual int getArea() = 0;

      void setWidth(int w) {

         width = w;

      }

        void setHeight(int h) {

         height = h;

      }

  

   protected:

      int width;

      int height;

};

 // Derived classes

class Rectangle: public Shape {

   public:

      int getArea() {

         return (width * height);

      }

};

 class Triangle: public Shape {

   public:

      int getArea() {

         return (width * height)/2;

      }

};

 

void main(void) {

   Rectangle Rect;

   Triangle  Tri;

   Rect.setWidth(5);

   Rect.setHeight(7);

     // Print the area of the object.

   cout << "Total Rectangle area: " << Rect.getArea() << endl;

    Tri.setWidth(5);

   Tri.setHeight(7);

     // Print the area of the object.

   cout << "Total Triangle area: " << Tri.getArea() << endl;

}

output:

Total Rectangle area: 35

Total Triangle area: 17

No comments:

Post a Comment