I'm a Java programmer and was confued about the fact of providing the defintion for pure-virtual functions. In Java I'm used to think about abstract methods as methods we'll provide the deifinitions 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 complaing about providing no definition for pure virtual functions. Why can we define the pure-virtual destructor in a namesapace scope, but can't do that for usual member function.
Is that rather an exception than a rule?
You are allowed to define any pure virtual member function. However, even though you define
A::foo
, it is still pure, soA
andB
are still abstract classes and may not be instantiated. That will be the cause of any errors your compiler may emit.