can pure virtual function have a body? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

can pure virtual function have a body?

16th Aug 2016, 6:17 PM
Shubham Taneja
Shubham Taneja - avatar
5 Answers
+ 2
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 }
16th Aug 2016, 7:06 PM
Cohen Creber
Cohen Creber - avatar
+ 1
@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...
17th Aug 2016, 8:35 AM
Stefan
Stefan - avatar
+ 1
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.
17th Aug 2016, 10:58 AM
Cohen Creber
Cohen Creber - avatar
0
thanks
17th Aug 2016, 3:50 AM
Shubham Taneja
Shubham Taneja - avatar
0
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.
17th Aug 2016, 6:25 AM
Amit Gupta
Amit Gupta - avatar