can pure virtual function have a body? | SoloLearn: Learn to code for FREE!


can pure virtual function have a body?


8/16/2016 6:17:33 PM

Shubham Taneja

5 Answers

New Answer


They certainly can. Calls for a pure virtual function can be made statically. class P { public: virtual void func() = 0; }; void P::func() { //body for pure virtual function } class S : P { public: void func(); }; void S::func() { P::func(); //static call to pure virtual function } int main() { S s; s.func(); //static call via object }


@Cohen: What compiler compiles this program? If a compiler does, I would say it's not ISO C++ conformant. Basic problem is that non static functions take a hidden first parameter that has to be of the type of the class the method is defined in and that's the object you refer to by the "this" keyword. In other words: apart from very likely being a compiler problem, calling a non-static method from a static method is a bad practice. Try to use a class P with fields and access them in the virtual method...


Apologies, ignore my answer then. Still a beginner myself and questions like this help me research new things, hence why I like to lurk around these forums😁 I have fixed the original answer I made so that it actually works, but I don't know whether it's any good at all. Sorry again.



this program should not work, you can not create object of abstract class P. I guess you were trying to create object of derived class S instead.