Doubt in virtual function

Hi all,

I was browsing through a code and found one thing which sort of confused me.

There is a base class in which a function was defined as

virtual void myfunc(int param1, int param2) = 0;

Can anyone explain the significance of assigning value 0 to this function??

This would explain it better than I would :D

http://www.cplusplus.com/forum/beginner/40226/
It's pure virtual function (or abstract function) that has no body at all! A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.
To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0. so, by doing equal to zero we are giving definition of that virtual function.
To be correct - a pure virtual function can have a body.
You just have to seperately define the body of the function sperately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
struct MyX
 {
     virtual void MyX_func() = 0; //make struct MyX an abstract class
 };
 
//have to seperately define a body for
//the function if you want to.
 void MyX::MyX_func()
 {
     
 }
 
 struct MyX_D :MyX   //a derived class
 {
     void MyX_func() override
     {
         
         MyX::MyX_func();
         
     }
 };

int main()
{

    MyX *pm = new MyX_D;  
    
    pm->MyX_func();
}
Last edited on
Thanks all for the reply.

One more question...

In the above example, I have given two arguments to the function myfunc. So, when I define the function, can i have different number of arguments to this function?
No, not unless you overload it or make it a variadic function.
Topic archived. No new replies allowed.