Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever "moral" to override a nonvirtual function? [closed]

I have used the following C++ rule of thumb for a long time:

If a class overrides a function in its base class, the function should be declared virtual in the base.

I think I have come across an exception from this rule. To judge whether this is justified, or points at a flaw in my design, I am asking this question. I would like to get examples or better rules.


Edit: I tried describing my use case here, and I have understood that I don't really need inheritance!

I wanted to ask a general question though. Thanks for the answers!

like image 536
anatolyg Avatar asked Mar 13 '11 13:03

anatolyg


People also ask

Can I override a non-virtual function?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

Can you override private virtual methods C++?

C++ has access control, but not visibility control. This means that private functions are visible but not accessible. A private virtual function can be overridden by derived classes, but can only be called from within the base class.

Can we call a virtual function from a constructor?

You can call a virtual function in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, “base before derived”.

How slow are virtual functions Really?

Virtual functions are slow when you have a cache miss looking them up. As we'll see through benchmarks, they can be very slow. They can also be very fast when used carefully — to the point where it's impossible to measure the overhead.


1 Answers

You can not override a non-virtual function. Only thing you can do is to hide the base class implementation. But this doesn't provide you the polymorphic behavior that virtual function provide.

like image 179
Asha Avatar answered Oct 20 '22 22:10

Asha