3

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

Jay
  • 117
  • 2
  • 2
  • 6

2 Answers2

1

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.

rerun
  • 25,014
  • 6
  • 48
  • 78
1

Actually, Virtual function is base of object oriented language. In java, all functions are virtual function. But in c++, virtual function is slower than regular function. So if there is no need to function override, you should use regular function instead of virtual function.

tele
  • 11
  • 2