What's the use of final keyword in C++11 virtual functions

2 Questions:

1. As I understand, virtual functions are used to implement polymorphism, i.e., to allow derived classes to implement these functions in a different manner. Why would anyone first make a function virtual and then add the final keyword to disallow derived classes to overload it?

2. What is the difference between function overloading and function over-riding? Is there any?

I have tried to google but I am still confused about the above two questions.
Final is to disallow any further inheritance of a particular class or ability to override a function from a derived class. The derived class below the class that used the keyword final can still use the function, just not able to override it. I think it's more of an aesthetic thing and I could be horribly wrong.

Overloading is when you have functions of the same name and are only distinguishable by the number and type of their parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;

void f(int) { cout << "f(int)" << endl; }
void f(double) { cout << "f(double)" << endl; }

void f2(int) { cout << "f2(int)" << endl; }
void f2(int) { cout << "f2(int)" << endl; }

int main()
{
     int x = 0;

     f(x);
     f2(x); //Call is ambiguous, which f2()? 
}


Overriding is the act of a derived class redefining a virtual function that it has inherited from the base class (ie. you want the derived class to use that particular function differently from the base, so you override the definition to suit the need).
Last edited on
thanks Olysold, now I understand.
Topic archived. No new replies allowed.