Monday, 23 February 2015

Pure virtual function in C++

Welcome to Logically Proven blog.

This post demonstrates "Pure Virtual Function" in C++.

A pure virtual function is a function that must be overridden in a derived class and need not to be defined.
A virtual function is declared to be "pure" using the curious "=0" syntax.

For example:

class Base {
  void f1();  // not virtual
  virtual void f2(); // virtual, not pure
  virtual void f3() = 0; // pure virtual

 Base b; // error: pure virtual f3 not overridden

If a class is having any pure virtual functions, then the class is called "abstract class". Thus Base is an abstract class. So no objects are created directly for the class Base.

class Derived : public Base {
  // no f1: fine
  // no f2: fine, we inherit Base::f2
  void f3();

 Derived d; // ok: Derived::f3 overrides Base::f3

Abstract classes are very useful for defining interfaces. Interface contains only method declarations. The classes which extends interface must contain method implementations. In fact, a class with only pure virtual functions is often called an interface.

If you don't override a pure virtual function in a derived class, that derived class becomes abstract.

class D2 : public Base {
  // no f1: fine
  // no f2: fine, we inherit Base::f2
  // no f3: fine, but D2 is therefore still abstract

 D2 d; // error: pure virtual Base::f3 not overridden

Here D2 doesn't contain method implementation for function f3. So D2 is also an abstract class and no object is created. So in this context, classes Base and D2 are abstract classes.

In the below example class D3 is derived from the class D2 and contain implementation for the function f3. So we can create object successfully for the derived class D3.

class D3 : public D2 {
  // no f1: fine
  // no f2: fine, we inherit D2::f2
  void f3();

 D3 d; // ok: D3::f3 overrides D2::f3

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.


Post a Comment