Pure Virtual Function and Abstract Class

on

Pure virtual functions are virtual function that does not have implementation. It contains only declaration part.
i.e.

Class Test
{
	public :
		virtual void funct() = 0 ;	
};

A pure virtual function is one with the expression =0 added to the declaration.
The equal sign with zero tells compiler that virtual function will be pue and if you try to instantiate object of class base, the compiler will give an error.

-cannot declare variable ‘t1’ to be of abstract type ‘Test’|
-because the following virtual functions are pure within ‘Test’:|
– virtual void Test::funct()|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

Abstract Class

Abstract Class contains at least one pure virtual function. It used to provide an interface for its sub classes. Such class exists only to act as a parent/Super class of Derived/sub class that ill be used to instantiate objects.

#include<iostream>
using namespace std;

class Test
{
    public:
        virtual void funct()=0;
};
class TestChild: public Test
{

public:
    void funct()
    {
        cout<<"Derived Class - Override Virtual Method";
    }

};
int main()
{
    TestChild t1;
    t1.funct();

}

Once you’ve placed a pure virtual function in the base class, you must override it in all the derived classes where you want to instantiate objects.

Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class.
Example

int main()
{
    Test *t;
    TestChild t1;
    t = &t1;
    t->funct();

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s