noname
noname

Reputation: 209

C++ preventing method overriding

Is there any way in C++ by which we can declare virtual method un-overridable just like final methods in Java.

I know by making default constructor private of class I can make class final but what about just virtual method ?

Thanks

Upvotes: 0

Views: 148

Answers (4)

Dúthomhas
Dúthomhas

Reputation: 10123

How to make a final class in C++ versions before C++11: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Final_Class

Upvotes: 0

SergeyA
SergeyA

Reputation: 62613

Despite the fact that C++11 and later allows method to be declared final, I dare say it is not a good thing to do. Do not seal down your class! Users of it might have inventive scenarios, and they might need to tweak it a bit. Why deprive them of this option?

If you look into standard library implementation (one of the best sources of really good programming in terms of both efficiency and style) you will see that members are never final, nor are the classess themselves.

Upvotes: 0

Ceros
Ceros

Reputation: 490

If you declare your method virtual like so:

virtual myMethod();

Then they can be overriden. Remove virtual to make them "un-overidable"

Since C++11, you can also use final with virtual like so:

virtual myMethod() final;

Final keyword

Upvotes: 2

Axel13fr
Axel13fr

Reputation: 11

Starting from C++ 11, there is as well a final keyword which can be used both on classes and methods.

It's to my knowledge not possible to do this with prior versions.

See https://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final

Upvotes: 1

Related Questions