Relationship between abstract class and concrete class
Usage
- Forces a concrete class to implement its own behavior by inheriting a pure virtual function
Explain
Pure virtual function is a virtual function which has only prototype, but no definition. Instead of function body, it has "= 0" in prototype.
Abstract class is a class having pure virtual functions. Because a pure virtual function has no implementation, abstract class cannot be an instance. If someone does, compiler gives an error.
Instead of abstract class, concrete class inherits abstract class and implements its behavior by overriding pure virtual functions. If the pure virtual function is not implemented(=overridden) in concrete class, a compiler also gives an error. Code 1 shows how to use a pure virtual function and abstract and concrete classes.
// 01_C_PureVirtualFunction.cpp
#include <iostream>
using namespace std;
// Abstract class
class BaseClass
{
public:
virtual void foo() = 0; // Pure virtual function
};
// Concrete class
class DerivedClass : public BaseClass
{
public:
void foo() {}
};
int main()
{
// BaseClass b; // Abstract class cannot be an instance
DerivedClass d;
d.foo();
}
// Compile: clang++ -std=c++14
// -o 01_C_PureVirtualFunction 01_C_PureVirtualFunction.cpp
Foo
Abstract class defines interface, and helps to adapt LSP. Several concrete classes inherit an abstract class and override functions to have its own behavior. So, by using pointer of abstract class, all concrete class instances can be controlled.
Summary
- Abstract class has more than one pure virtual function.
virtual void draw() = 0;
- A pure virtual function should be overridden in a concrete classes, and their instances can be controlled by the pointer of abstract class.
COMMENTS