Saturday, 7 July 2018

Pure Virtual Functions or Abstract Class

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration.
1) A class is abstract if it has at least one pure virtual function
/ pure virtual functions make a class abstract
#include
using namespace std;
 
class Test
{
   int x;
public:
    virtual void show() = 0;
    int getX() { return x; }
};
 
int main(void)
{
    Test t;
    return 0;
}
Output:
Compiler Error: cannot declare variable 't' to be of abstract
 type 'Test' because the following virtual functions are pure 
within 'Test': note: 	virtual void Test::show() 
2) We can have pointers and references of abstract class type.
#include
using namespace std;
 
class Base
{
public:
    virtual void show() = 0;
};
 
class Derived: public Base
{
public:
    void show() { cout << "In Derived \n"; }
};
 
int main(void)
{
    Base *bp = new Derived();
    bp->show();

    Derived d;
    d.show(); //In Derived. 
   return 0;
}
Output:
In Derived 
3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
#include
using namespace std;
class Base
{
public:
    virtual void show() = 0;
};
 
class Derived : public Base { };
 
int main(void)
{
  Derived d;
  return 0;
}
Compiler Error: cannot declare variable 'd' to be of abstract type 
'Derived'  because the following virtual functions are pure within
'Derived': virtual void Base::show(
4) An abstract class can have constructors.
For example, the following program compiles and runs fine.
#include
using namespace std;
 
// An abstract class with constructor
class Base
{
protected:
   int x;
public:
  virtual void fun() = 0;
  Base(int i) { x = i; }
};
 
class Derived: public Base
{
    int y;
public:
    Derived(int i, int j):Base(i) { y = j; }
    void fun() { cout << "x = " << x << ", y = " << y; }
};
 
int main(void)
{
    Derived d(4, 5);
    d.fun();
    return 0;
}
Output:
x = 4, y = 5


In C++, an interface can be simulated by making all methods as pure virtual. In Java, there is a separate keyword for interface.
In Java, a class can be made abstract by using abstract keyword. Similarly a function can be made pure virtual or abstract by using abstract keyword.

No comments:

Post a Comment