Abstract Class in C++ with examples

Abstract Class in C++

1. A class containing at least one pure virtual function is called an abstract class in C++.

2. We cannot instantiate abstract class (i.e., object cannot be created of an abstract class).

3. A class whose object cannot be created because of pure virtual function is called an abstract class.

4. We need to create child class of abstract class in order to use methods of abstract class but again we can't use the pure virtual function.

5. We must override pure virtual function of abstract class in its child class to use methods of abstract class.


For Example:- Abstract class example in c++

#include<iostream>
using namespace std;

//making Abstract class
class Person
{
public:
//declaring pure virtual function
virtual void Func() = 0;

void Fun1()
{
//...
}
};

//making child class of Abstract class
class Student: public Person
{
public:
//overriding pure virtual function
void Func()
{
//...
}
};


For Example:- Abstract class example in c++

#include<iostream>
using namespace std;
class Figure
{
public:
// Pure virtual function
virtual int Area() = 0;

// Function for setting breadth.
void setBreadth(int br)
{
breadth = br;
}

// Function to set height.
void setHeight(int ht)
{
height = ht;
}

protected:
int breadth;
int height;
};


// A rectangle is a figure. So, it will inherit figure.
class Rectangle: public Figure
{
public:
//overriding pure virtual function in derived class.
int Area()
{
return (breadth * height);
}
};


// A triangle is also a figure. So, it will also inherit figure.
class Triangle: public Figure
{
public:
// Triangle uses the same Area function but implements it too.
// Overriding pure virtual function in derived class
int Area()
{
return (breadth * height)/2;
}
};


int main()
{
Rectangle R1;
Triangle T1;

R1.setBreadth(6);
R1.setHeight(12);

T1.setBreadth(40);
T1.setHeight(4);

cout << "The area of the rectangle is: " << R1.Area() << endl;
cout << "The area of the triangle is: " << T1.Area() << endl;
}


Why to use Abstract Class in C++?


abstract-class-in-c++-learning-mania


Person class is an abstract class (it is generalized class that can have similar or common features of any person like name, date of birth, address, etc).

Generalization makes it easier for us to maintain the projects (like in future if we want to make another class Salesman, we can simply inherit it from Person class).

Account class is an abstract class which have a pure virtual function named Interest(). Saving and current are child classes of Account class in which pure virtual function is overridden.



<< Previous                                                                                      Next >>
Previous
Next Post »