Abstract Class Example in C++


The program defines a base class Base with a non-pure virtual function fun1 and a pure virtual function fun2. The class Derived inherits from Base and provides an implementation for the pure virtual function fun2.

In main, a pointer of type Base is created and assigned a Derived object. The virtual function fun2 is called using the pointer, which is a virtual function call. Since fun2 is a virtual function, the implementation of the fun2 in the Derived class is called at runtime, even though the pointer is of type Base. This is an example of runtime polymorphism.

Source Code

#include<iostream>
//Class having pure virtual function then this class is called as Abstract Class.
using namespace std;
class Base
{
public:
    void fun1(){
    cout<<"Base Fun1:";
    }
    virtual void fun2()=0;
};
class Derived : public Base
{
public:
    void fun2(){
     cout<<"Derived Fun2:";
    }
};
int main()
{
    Base *p=new Derived();
    p->fun2();
    return 0;
}
To download raw file Click Here

Output

Derived Fun2:

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples