Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use virtual function instead of regular? [duplicate]

In c++, the virtual function in base class can be overridden in derived class. and a member function where the specific implementation will depend on the type of the object it is called upon, at run-time.

Since virtual function has to be implemented(except for pure virtual) Can I use regular function in base class and redefine it in derived class? if yes. What's the point of using virtual function?

Thanks

like image 429
Jay Avatar asked Jun 29 '26 09:06

Jay


1 Answers

You can redefine it but it won't work in a polymorphic way.

so if I have a

class base
{
   int foo(){ return 3; }
};

class Der : public base
{
  int foo() {return 5;}
};

and then have a function that takes a base

void dostuff(base &b)
{
   b.foo(); // This will call base.foo and return 3 no matter what
}

and I call it like this

Der D; 
dostuff(D); 

Now if I change the base to

class base
{
   virtual int foo(){ return 3; }
};

void dostuff(base &b)
{
   b.foo(); // This will call the most derived version of foo 
            //which in this case will return 5
}

so the real answer is if you want to write common code that will call the correct function from the base it needs to be virtual.

like image 86
rerun Avatar answered Jun 30 '26 23:06

rerun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!