Abstract Base Classes and Concrete Classes
Abstract Base Classes and Concrete Classes
Concrete Classes
Abstract classes
All classes can be designated as either abstract or
concrete.
Concrete is the default.
This means that the class can have (direct) instances.
In contrast, abstract means that a class cannot have its
own (direct) instances.
A class that contains a pure virtual function is known
as an abstract class.
Abstract class
Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void
get(); )
You cannot instantiate an abstract class.
An abstract class may contain abstract methods.
You need to inherit an abstract class to use it.
If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
// Abstract class
class Shape
{
protected:
float dimension;
public:
void getDimension()
{
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0; };
// Derived class
class Square : public Shape
{
public:
float calculateArea()
{
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape
{
public:
float calculateArea()
{
return 3.14 * dimension * dimension; }
};
int main()
{
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() <<
endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() <<
endl; return 0;
}
pure virtual function
A pure virtual function doesn't have the function body and it
must end with = 0.
For example,
class Shape
{ public:
// creating a pure virtual function virtual void calculateArea()
= 0;
};
Note:
The = 0 syntax doesn't mean we are assigning 0 to the
function. It's just the way we define pure virtual functions.
Concreate class
class Base
{
public:
void show() { cout<<" In Base \n"; }
};
return 0;
}