Search code examples
c++virtual

Providing a definition for a pure-virtual function


I'm a Java programmer and was confused about the fact of providing the definition for pure-virtual functions. In Java I'm used to think about abstract methods as methods we'll provide the definitions in a base class. But the following code is perfectly valid:

#include <iostream>

struct A
{
    virtual ~A() = 0;
};

A::~A(){ std::cout << "~A()" << std::endl; }

struct B : A
{
    ~B(){ std::cout << "~B()" << std::endl; }
};

A *a = new B;

int main()
{
    delete a;
}

But if we try to do something like that:

#include <iostream>

struct A
{
   virtual ~A() = 0;
   virtual void foo() = 0;
};

void A::foo(){ }
A::~A(){ std::cout << "~A()" << std::endl; }

struct B : A
{
    ~B(){ std::cout << "~B()" << std::endl; }
};

A *a = new B;

    
int main()
{
    delete a;
}

The compiler's going to complain about providing no definition for pure virtual functions. Why can we define the pure-virtual destructor in a namespace scope, but can't do that for usual member function.

Is that rather an exception than a rule?


Solution

  • You are allowed to define any pure virtual member function. However, even though you define A::foo, it is still pure, so A and B are still abstract classes and may not be instantiated. That will be the cause of any errors your compiler may emit.