C++: Pure Virtual functions

C++ Pure Virtual functions are used to create an abstract classes or interfaces. Pure Virtual functions have no function definition; just the function will be declared and the definition left to the derived classes.

In C++, like Java, there is no interface keyword to create an interface. To create an interface in C++, the option is use Pure Virtual Functions.

Any class that has one or more pure virtual functions, is called an abstract class or an interface class. C++ doesn’t allow to create objects or instances for an abstract class.

Then how to access members in an abstract class? The solution is:

  • Create a derived class from an abstract class
  • Define all the pure virtual functions in derived class
  • Create an object of derived class to access members of an abstract class

C++ abstract classes may be partially defined. That means, you can have some implemented functions and one ore more pure virtual functions inside the class. Once all class’s members are completely defined, C++ allows to create an instance.

Here is the syntax to declare a Pure Virtual Function:

virtual function-return-type Function-Name(arguments) = 0;

Pure Virtual Functions must be declared as virtual with virtual keyword and it should be assigned to “0”; means no definition to the function.

For eg: Here we are going to create an abstract class MyInterface with a Pure Virtual Function Display. Display function is simply display the message.

Note: This program was compiled and tested using “Microsoft Visual Studio 2012”

Step (1). Define an abstract class MyInterface with Display Pure Virtual Function.

class MyInterface
{
public:
	virtual void Display(_TCHAR* message) = 0;
};

Step (2). Create a derived class from MyInterface and implement its Pure Virtual Function Display.

class SimpleClass : public MyInterface
{
public:
	void Display(_TCHAR* message)
	{
		_tprintf(message);
	}
};

Step (3). Create an instance of derived class and call the method Display.

int _tmain(int argc, _TCHAR* argv[])
{
	SimpleClass obj;

	obj.Display(L"Hello, World!");

	return 0;
}

Once you run the application, you will see “Hello, World!” message on the screen.

**

Leave a Reply