user1756835
user1756835

Reputation: 51

Pure virtual function definition outside derived class

I have abstract base class and derived class in header file. Is it possible to have definition of pure virtual function outside the derived class?

For example:

//file .h
class Baseclass
{
public:
    virtual int vfunc() = o;
   //assume Ctor and Dctor
};
class Derivedclass : public Baseclass
{
public:
    int vfunc();
    //assume Ctor and Dctor
};

Now in the cpp file:

#include <file.h>
int Derivedclass :: vfunc()
{
    // Body of the function
}

Is the above method correct/possible?

Upvotes: 4

Views: 1799

Answers (3)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

Is it possible to have definition of pure virtual function outside the derived class?

The function is not pure virtual in the derived class, it's only pure virtual in the base class.

The derived class overrides the function and does not have a pure-specifier (the =0 bit after the function declarator) so DerivedClass::vfunc() is not pure virtual, and therefore must have a definition somewhere if it's used in the program. Defining it in a separate file from the header is perfectly normal.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308111

This is not only possible, it's standard practice. The only time you have to worry about putting function definitions into the header is with templates.

Upvotes: 3

Coding Mash
Coding Mash

Reputation: 3346

Yes it is possible. You can define them outside your class, if that is what at all you want to ask.

Upvotes: 1

Related Questions