I know that abstract base classes are those which have a pure virtual function and objects of abstract base class cannot be created.
So , why should we create a class which cannot define its object?
I know that abstract base classes are those which have a pure virtual function and objects of abstract base class cannot be created.
So , why should we create a class which cannot define its object?
We want them to provide interface descriptions, and force deriving classes to implement these interfaces.
struct IRender;
struct IShape {
virtual void Draw(IRender& render) = 0;
virtual ~IShape() {}
};
struct IRender {
virtual void RenderShape(IShape& shape) = 0;
virtual ~IRender() {}
};
At this point we don't want to know about the concrete implementations.
It's a contract of sorts used between developers to say "This is the type of functionality we want to implement", and leaves the implementation up to the developers if the classes they want to design are to inherit the base class.
Simple example:
#include <iostream>
using namespace std;
class Animal
{
public:
Animal() {}
virtual void sound() = 0;
};
/* Dog class is derived from base class Animal */
class Dog : public Animal
{
public:
Dog() {}
void sound()
{
cout << "woof!" << endl;
}
};
Here, Dog
is an Animal
, and must implement it's own sound. The base class Animal
's sound() function implies that Animals make sounds, and that any class that inherits from Animal
should implement a sound function. From this, you could make a Cat
class that outputs a meow from its sound class, as well as a Bear
class that outputs a roar, etc.
In addition to a pure virtual class which serves as an interface, you can also have a class with a combination of pure virtual functions and functions with definitions. This is useful for a polymorphic base class which needs defined behavior from the subclasses but can't implement it.
Take a basic inheritance example:
class Animal { virtual void Eat() = 0; };// pure virtual base class
class Dog : Animal { ... };// tangible, real class
Implementing Dog::Eat is straight-forward. But how would you implement "Animal::Eat"? There is no generic implementation of "Eat"; you need a specific type of animal to know how to implement such an action.
A abstract class doesn't have any object but it can have a pointer which can hold address of derived class object.using this we can perform operations on derived classes
class Base {
public:
virtual void method1();
}
class Derived:public Base {
// 1. List item
void method1() {
cout<<"in derived 1"<<endl;
}
}
int main() {
Base *ptr;
Derived d;
ptr=&d;
ptr->method1();
}