Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
May 5, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Virtual function is abstract

We are getting an error message that says a function from within a class C cannot allocate instance of type C because one of the virtual functions (the one we wrote) is abstract. How can we make it non-abstract?

Before changing an abstract class to a concrete class, you first must understand why the creator of that class made it abstract in the first place. In general, this is a decision that is made during the object-oriented design process. When we speak of abstract in object-oriented terms, it more or less means the same thing as it does in philosophical terms. Something abstract is conceptual; therefore it is intangible and can be realized only when applied to some thing tangible or concrete.

A classic example of an abstract class is Shape. The Shape may contain member functions to draw a circle, square or triangle, but it means nothing unless it can be applied to something tangible; therefore, the C++ compiler will prohibit any instatiation of objects of type Shape. In order to use the Shape class, you must derive a new class from it that implements the member functions (or methods) defined in the abstract class, thus making the derived class concrete. For example, you may derive a Table, House, and Boat class from the Shape abstract class. Provided you implement the functions in the base class that make it abstract, all your derived classes will be concrete classes. Then, you will be able to instantiate objects of those types. Hence you can have a square table, house, or boat.

Finally, what makes a class abstract in C++ is that at least one member function is declared as pure virtual. Pure virtual functions are virtual functions that are initialized to zero, and contain no implementation. Below is a code example:

// Abstract base class Shape
class Shape{

// pure virtual functions
	virtual void Round( ) =3D 0;
	virtual void Square( ) =3D 0;
	virtual void Triangle( ) =3D 0;
To use an abstract class, you must derive a new class from it, and override all pure virtual functions by providing implementation. See code extract below:
// Concrete class Table inherits from abstract class shape
class Table : public Shape{

// Functions implemented from abstract class shape.  Implementation for these functions will usually be
// located in a methods file (.cpp file extension).
	void Round( );
	void Square( );
	void Triangle( );
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date