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

2
  • 1
    You can hide a non-virtual function. That's generally a bad thing. Commented Oct 18, 2013 at 3:15
  • 1
    Are you sure its not given in your book ? Commented Oct 18, 2013 at 3:15

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.