The almost useless c++ trick of the day
By Hugo on Wednesday, September 3 2008, 23:37 - C++ - Permalink
When I learn c++, I remember my teacher telling : "A pure virtual method is a method without implementation", well that's not entirelly true... Actually, you can have a method beeing both pure virtual, and implementated. How is that possible ? well i must say that I don't know, since every assertions I ever made concerning how a compiler handles pure virtual methods was using the fact that a pure virtual was a null pointer in the class vtable... since you can have a body in it, it's obviously not null anonyme...
Anyway, implementing a pure virtual method is quite easy :
class A { public : virtual void pureVirtual() = 0 { std::cout << "Me love otters" << std::endl; } };
And this will compile without any problem !
The comportment of an implemented pure virtual method is quite simple, like any other pure virtual method, it prevents your class from beeing implemented. So here you can't have
A* a = new A();
it would print the usual error message : cannot instanciate abstract class. But what you can do, is call the implementation from a inherithed class of A, so here, you could do :
class B : A { public : virtual void pureVirtual() { std::cout << "Not pure virtual anymore" << std::endl; A::pureVirtual(); } }; int main() { B*b = new B(); b->pureVirtual(); }
which would print :
Not pure virtual anymore
Me love otters
And the worst part, is that even if a implemented pure virtual method seems a little bit of a non sense, not only it can be done, but it could be usefull, if you want to provide an interface with a default behavior, or probably many things else :)