sp497
sp497

Reputation: 2493

Avoiding Defining a pure virtual function in c++ in immediate derived class?

Do we have to compulsorily define a pure virtual function in c++ in the immediate derived class ? Or can we just avoid it so that we can define it only in concrete classes ? How is this achieved ?

Upvotes: 2

Views: 1197

Answers (3)

DGomez
DGomez

Reputation: 1480

If there's some virtual pure method not implemented then the derived class is abstract. You must implement the method in some derived class if you want to instantiate it.

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

There's absolutely no requirement to ever define any pure virtual functions in the class until you begin to create actual objects of that class.

Abstract classes are intended to serve as bases for other classes. The abstract class hierarchy can be arbitrarily deep, meaning that you are not required to define pure virtual methods in the immediate descendant.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258558

No one forces you to implement pure virtual functions, so you don't have to. Your class will just be abstract. In a derived class, just leave the declaration out or re-declare it as virtual pure.

struct Base
{
   virtual void foo() = 0;
};

//this is OK, X is abstract
struct X : Base
{
};

//this is also OK, redundant, and Y is abstract
struct Y : Base
{
   virtual void foo() = 0;
};

Upvotes: 4

Related Questions