Hind Forsum Hind Forsum - 1 year ago 60
C++ Question

Why does C++ support for a pure virtual function with an implementation?

I did a simple test today:

struct C{virtual void f()=0;};
void C::f(){printf("weird\n");}

The program is OK, but is weird to me, when we use
it means the function body should be defined in the inherited classes, but it seems I can still give it implementation function.

I tried both GCC and VC, both OK. So it seems to me this should be part of C++ standard.

But why this is not a syntax error?

A reason I could think of is like C# having both 'interface' and 'abstract' keywords, interface can't have an implementation, while abstract could have some implementations.

Is this the case for my confusion, that C++ should support such a kind of weird syntax?

Answer Source

C++ Supports pure virtual functions with an implementation so class designers can force derived classes to override the function to add specific details , but still provide a useful default implementation that they can use as a common base.

Classic example:

class PersonBase
    string name;
    PersonBase(string nameIn) : name(nameIn) {} 

    virtual void printDetails() = 0
        std::cout << "Person name " << name << endl;

class Student : public PersonBase
    int studentId;
    Student(string nameIn, int idIn) : PersonBase(nameIn), studentId(idIn) {  }
    virtual void printDetails()
        PersonBase::printDetails(); // call base class function to prevent duplication
        std::cout << "StudentID " << studentId << endl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download