Abstract Base Class in C++
Object Oriented Programming in C++ – Part 9
Forward: In this article I explain the operation of the abstract base class.
By: Chrysanthus Date Published: 23 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
An Abstract Base Class
An abstract base class is a class with what is known as a pure virtual function. A pure virtual function is a function (method) that does not have an implementation (that is, it does not have a definition; in other words it does not have a function body in curly braces). Well, you need to know how to produce this virtual function. The typing has a declaration that is preceded by the keyword, virtual; to the declaration is assigned the value zero. The following code illustrates the description of an abstract class that has a pure virtual function.
#include <iostream>
using namespace std;
class MyClass
{
public:
virtual int mthd() = 0;
};
int main()
{
return 0;
}
The class has just one function; it is the virtual function. Note the way it has been typed. It begins with the word, virtual; a null address has been assigned to the declaration within the class description. Any class with a pure virtual function is called an abstract base class. In future, you can inherit other classes from this class and in the inherited (derived) classes, you will give the method its implementation.
In the following code the base class is an abstract base class.
#include <iostream>
using namespace std;
class Calculator
{
public:
int num1;
int num2;
int add()
{
int sum = num1 + num2;
return sum;
}
virtual int mthd() = 0;
};
class ChildCalculator: public Calculator
{
public:
int fixedVal;
int square(int answer)
{
int finalVal = answer * answer + fixedVal;
return finalVal;
}
int mthd()
{
cout<<"I have been implemented in the derived class.";
}
};
int main()
{
ChildCalculator myChildObj;
myChildObj.mthd();
return 0;
}
Note: you cannot instantiate a class from a base abstract class, because it has one or more functions that are virtual. You can instantiate an object from the corresponding derived class, where the virtual functions (methods) have been implemented.
That is what I have for Abstract Base Classes. Let us stop here and continue in the next part of the series.
Chrys
Related Courses
C++ CourseRelational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem