What is the opposite of c++ `override` / `final` specifier? - c++

In c++11 the override specifier protects from not overriding an intended virtual base function (because the signatures do not match).
The final specifier protects from unintentionally overriding a function in a derived class.
=> Is there a specifier (something like maybe first or no_override) that protects from overriding an unknown base function?
I'd like to get a compiler error when a virtual function was added to a base class with the same signature as an already existing virtual function in a derived class.
EDIT 4: To keep this question simple and answers relevant, here is again the
original pseudo-code
abstract class B : A has private: virtual void fooHasBeenDone() = 0;
class C : B implements private: virtual void fooHasBeenDone() override { react(); }
Now class A gets a new private: virtual void fooHasBeenDone();
But the new A::foo could be something different than the original B::foo.
and a specific example
abstract class B : A has virtual void showPath() = 0; meaing a PainterPath
class C : B implements virtual void showPath() override { mPath.setVisible(); }
Now class A gets a new virtual void showPath(); meaning a file path
Now when A calls showPath(), B shows the painterPath instead of some file path.
Of course this is wrong, and I should then rename B::showPath() to B::showPainterPath() and implement B::showPath() override as well. I'd just like to get informed by the compiler.
Here is a compiling real-world example:
#include <iostream>
#define A_WITH_SHOWPATH
class A
{
#ifdef A_WITH_SHOWPATH
public:
void setPath(std::string const &filepath) {
std::cout << "File path set to '" << filepath << "'. Display it:\n";
showPath();
}
// to be called from outside, supposed to display file path
virtual void showPath() {
std::cout << "Displaying not implemented.\n";
}
#else
// has no showPath() function
#endif
};
class B : public A
{
public:
virtual void showPath() = 0; // to be called from outside
};
class C1 : public B {
public:
virtual void showPath() override {
std::cout << "C1 showing painter path as graphic\n";
}
};
class C2 : public B {
public:
virtual void showPath() override {
std::cout << "C2 showing painter path as widget\n";
}
};
int main() {
B* b1 = new C1();
B* b2 = new C2();
std::cout << "Should say 'C1 showing painter path as graphic':\n";
b1->showPath();
std::cout << "---------------------------\n";
std::cout << "Should say 'C2 showing painter path as widget':\n";
b2->showPath();
std::cout << "---------------------------\n";
#ifdef A_WITH_SHOWPATH
std::cout << "Should give compiler warning\n or say \"File path set to 'Test'. Display it:\"\n and \"Displaying not implemented.\",\n but not \"C1 showing painter path as graphic\":\n";
b1->setPath("Test");
std::cout << "# Calling setPath(\"Test\") on a B pointer now also displays the\n# PainterPath, which is not the intended behavior.\n";
std::cout << "# The setPath() function in B should be marked to never override\n# any function from the base class.\n";
std::cout << "---------------------------\n";
#endif
return 0;
}
Run it and look at the text output.
For reference, an older example with a specific use-case (PainterPath instance):
https://ideone.com/6q0cPD (link may be expired)

The facility of specifiers like first or no_override is not there as such. Probably because it may create confusion. However, it can trivially be achieved by changing the approach.
One should add any new method in the base class with final specifier. This will help to get the compiler error for any matching signatures. Because, it will make the subsequent derived class method signatures automatically as "first" of their kind. Later the final keyword can be removed, as it was intended just for "first hand verification".
Putting & removing final keyword after the newly added base method is analogically similar to compiling binary with debug (g++ -g) option, which helps you to fix bug. In production that debug option is removed for optimization.
From your example:
class A {}; // no method, no worry
class B {
public: virtual void showPath() = 0; // ok
};
...
Now accidentally you are adding similar method in A, that results in error:
class A {
public: virtual void showPath() final; // same signature by chance
// remove the `final` specifier once the signature is negotiated
};
class B {
public: virtual void showPath() = 0; // ERROR
};
So the signatures between new A::showPath() & existing B::showPath() have to be negotiated & then carry on by removing final specifier.

This answer is community wiki because it combines all other answers. Please upvote the specific answer that was helpful to you as well as this one.
No, there is no specifier like first or no_override. (answer)
You should use the override specifier as often as possible.
Qt has a macro Q_DECL_OVERRIDE that expands to override, if available.
If not available, at least mark each overriding function with a comment.
If you do that, there are compiler flags that warn about a missing override:
"Clang now has -Winconsistent-missing-override, and newer GCCs have -Wsuggest-override."
I don't know of a VS2012 flag for this. Feel free to edit.
You can mimic the desired behavior by adding a 'secret' that the base class cannot know. (answer)
This is helpful in very specific use cases, but generally breaks the concept of virtuality (see comments to the other answers).
If you don't own the base class and have a conflict (e.g. compiler warning), you will need to rename your virtual function in all derived classes.
If you own the base class, you can temporarily add a final to any new virtual function. (answer)
After the code compiles without errors, you know that no function of that name and signature exists in any derived class, and you can remove the final again.
... I think I'll start marking first virtual functions as DECL_FIRST. Maybe in the future there will be a compiler-independent way of checking this.

No there is not.
Adding a virtual function to a base class that has the same signature as a virtual function in a child class cannot break any existing functionality unless adding that virtual function turns the base class into a polymorphic type. So in the norm, it's benign, and a purest would argue, adding language features to guard against this would be rather pointless.
(Of course you could mark your new function final just to check that a child class function isn't going to clobber it.)
Your only option is to resort to code analysis tools.
(Note that VS2012 does not implement, or even claim to implement, the C++11 standard, although it does have some of it.)

C++ doesn't seem to provide such means out of the box. But you can mimic it like follows:
template<class Base>
class Derived : public Base
{
private:
struct DontOverride {};
public:
// This function will never override a function from Base
void foo(DontOverride dummy = DontOverride())
{
}
};
If you intend to introduce a new virtual function, then do it like below:
template<class Base>
class Derived : public Base
{
protected:
struct NewVirtualFunction {};
public:
// This function will never override a function from Base
// but can be overriden by subclasses of Derived
virtual void foo(NewVirtualFunction dummy = NewVirtualFunction())
{
}
};

Related

Understanding calling inherited methods from abstract class in C++

I was doing an experiment on inheritance and abstract classes without using pointers (avoiding the use of new when possible), and I came across a behavior that makes sense but I havent found documentation on it on the internet (neither a name for it or example).
I create a class, Abstract that has two methods, one is defined and the other is not. Then, a class Inherited inherits from Abstract and implements this second method.
Heres the classes:
Abstract.hpp:
#ifndef ABSTRACT_HPP
# define ABSTRACT_HPP
#include <iostream>
class Abstract {
public:
Abstract() {};
~Abstract() {};
virtual void DoSomethingAbstract() = 0;
void DoSomethingNormal() {
std::cout << "Inside Abstract::DoSomethingNormal" << std::endl;
DoSomethingAbstract();
}
};
#endif /* ABSTRACT_HPP */
Inherited.hpp :
#ifndef Inherited_HPP
# define Inherited_HPP
#include "Abstract.hpp"
class Inherited : public Abstract {
public:
Inherited() {};
~Inherited() {};
virtual void DoSomethingAbstract() {
std::cout << "Inside Inherited::DoSomethingAbstract" << std::endl;
}
};
#endif /* Inherited_HPP */
The following main works as expected (the only implementation of each function is the one that is called):
#include "Abstract.hpp"
#include "Inherited.hpp"
int main() {
Inherited a;
a.DoSomethingNormal();
return 0;
}
output:
Inside Abstract::DoSomethingNormal
Inside Inherited::DoSomethingAbstract
Mostly I'd like to know if this is a UB and I'm just getting lucky, an unfrequent way of checking runtime polymorphism (which should not since there are no pointers to abstract classes here), or a perfectly defined behaviour somewhere in the standard.
PS: I am compiling with g++ 9.4.0, with flags `-std=c++98 -Wno-c++0x-compat.
Your example seems simple -- and for the most part, it is. But it leads to some important concepts. First, what you can do is a google on c++ polymorphism. There are a lot of hits, and the first several didn't seem to be wrong.
Let's look at some of your code:
virtual void DoSomethingAbstract() = 0;
This is referred to as a pure virtual function. It means you won't actually make this method, but you're going to reserve a slot for it (and can call it). It means you can not make instances of this class -- it's abstract. If you try to make one, the compiler will complain. Your subclasses MUST provide implementations or they are also abstract and can't be instantiated.
void DoSomethingNormal() {
std::cout << "Inside Abstract::DoSomethingNormal" << std::endl;
DoSomethingAbstract();
}
This method is NOT virtual. Your subclass can make its own copy of this method, but then you can get weird results. Let's say you do this:
class Inherited: public Abstract {
public:
void DoSomethingNormal() {...}
};
void blah(Abstract &obj) {
obj.DoSomethingNormal();
}
It won't matter whether you pass in an Abstract or an Inherited -- because you didn't declare the method virtual, and because blah() doesn't know what you're passing in but thinks it's an Abstract, you'll get Abstract's version of DoSomethingNormal().
But if you declare the method virtual, you're saying, "Use whichever version corresponds to the class that actually was instantiated."
This is polymorphism at it's most useful, important role.

What are the use cases for a base class pointer pointing to a derived class object

I'm a new to OOP and trying to learn C++ and I came cross polymorphism and using the virtual keyword.
I just don't understand why we might need to do that.
I've checked this site for similar questions but none of them attempts to answer that why?
The main goal is: Separation of concerns.
Let's take an example from my day job. I work on a codebase that does networking. The vast majority of the codebase depends on a class that looks like:
class Transport
{
public:
virtual bool SendMessage(int clientId, string message);
};
Imagine I've got hundred files, and tens of thousand of lines of code, using this class.
Now, my colleague in the low-level team wants to allow our code to use both UDP and TCP for communications. They can simply implement:
class UdpTransport:public Transport
{
public:
bool SendMessage(int clientId, string message) override { /* their code */};
};
class TcpTransport:public Transport
{
public:
bool SendMessage(int clientId, string message) override { /* their code */};
};
This allows me to keep the whole of my code unchanged (using only Transport* or Transport&) and not have to worry about what a UdpTransport or TcpTransport is. It allows one part of the code to work without knowing what another part of the code is doing.
Most introductions of polymorphism start with something like this:
Base* b = new Derived(); // ouch :/
This is very unfortunate in my humble opinion, because it creates the misunderstanding that polymorphism implies manual memory managment via new. The topics are somewhat related. Though my example of polymorphism would start like this:
#include <iostream>
struct base {
virtual void say_hello() { std::cout << "hello base\n"; }
};
struct derived : base {
void say_hello() override { std::cout << "hello derived\n";}
};
void foo(base& b) {
b.say_hello();
}
int main()
{
base b;
derived d;
foo(b);
foo(d);
}
say_hello must be declared virtual to allow derived to override the method. If say_hello was not virtual then derived::say_hello would not override it.
If you remove virtual and override above you can see what happens when the method in the derived class does not override the method in the base class. The call b.say_hello() would then call base::say_hello() no matter if a base or derived is passed to foo because only for virtual methods the method to be called considers the dynamic type of the object.
What are the use cases for a base class pointer pointing to a derived class object
Same as the reference above. foo(base&) can take an object of any type that derives from base and then call its say_hello method. If this wasnt possible you would have to write a foo(derived), foo(derived2), foo(derived3) to call their say_hello method. In a nutshell, polymorphism means to treat different types the same. foo does not need to know what the dynamic type of its paramter is. It only needs to know that it inherites from base.
Many Design Patterns (GOF book) rely on virtual functions. The idea is that you have you work with an object of which you only know it's interface and when you call a function, what is done is based on the object that implements the interface.
One of the design patterns is Command where you have a container in which you can add command implementations and the handler of the container calls the "execute" function without having to worry about what the command actually is. The command implementation contains already the data it needs to run.
A common alternative for virtual functions is a switch case that needs to know all the implementations as an enum so the caller knows what to call exactly or an own implementation of a function-table.
Of course, if you don't see how such thing can improve your program, then it's best not to try and force it in.
Consider the following class architecture and function:
#include <iostream>
#include <string>
class Base
{
public:
std::string hello() const
{
return "Hello Base!";
}
};
class Derived : public Base
{
public:
std::string hello() const
{
return "Hello Derived!";
}
};
void outputHello(const Base& b)
{
std::cout << b.hello() << '\n';
}
We have:
A base class with a hello() method that returns "Hello Base!";
A derived class with a hello() method that returns "Hello Derived!";
A outputHello(const Base&) function that takes a reference to a Base object as its argument and prints out the result of a call to its hello() method.
Now, what do you think the following program will output?
int main()
{
Base b;
outputHello(b);
Derived d;
// Allowed as a reference/pointer to Base can
// reference/point to a Derived object
outputHello(d);
}
You probably guessed the following if you come from Java or a similar object-oriented language:
Hello Base!
Hello Derived!
But it instead it outputs Hello Base! twice. Why? It's actually quite simple. When the compiler gets to the outputHello function body it sees std:cout << b.hello() << '\n'. It thinks: Well, b is of type Base, so I'm gonna issue a call to Base::hello(). And it does exactly that, regardless of the type of the object we actually pass as argument to outputHello.
To solve this problem and get the output we expected, we need RTTI (Runtime Type Information), whose name speaks for itself. This is achieved by marking Base::hello() as virtual:
class Base
{
public:
virtual std::string hello() const
{
return "Hello Base!";
}
};
It is also good practice to mark Derived::hello() as override, though it is not necessary — override functions are automatically virtual.
class Derived : public Base
{
public:
std::string hello() const override
{
return "Hello Derived!";
}
};
We then get our expected output.

Overriding vs Virtual

What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}.
class Parent {
public:
void say() {
std::cout << "1";
}
};
class Child : public Parent {
public:
void say()
{
std::cout << "2";
}
};
int main()
{
Child* a = new Child();
a->say();
return 0;
}
The output is 2.
So again, why would the reserved word virtual be necessary in the header of say() ?
Thanks a bunch.
If the function were virtual, then you could do this and still get the output "2":
Parent* a = new Child();
a->say();
This works because a virtual function uses the actual type whereas a non-virtual function uses the declared type. Read up on polymorphism for a better discussion of why you'd want to do this.
Try it with:
Parent *a = new Child();
Parent *b = new Parent();
a->say();
b->say();
Without virtual, both with print '1'. Add virtual, and the child will act like a Child, even though it's being referred to via a pointer to a Parent.
This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!
Here is an example:
Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent).
Parent* parents[3];
parents[0] = new Child();
parents[1] = new Child2();
parents[2] = new Child3();
for (int i=0; i<3; ++i)
parents[i]->say();
As you can imagine, this is very powerful. It lets you extend the Parent as many times as you want and functions that take a Parent pointer will still work. For this to work as others mention you need to declare the method as virtual.
If you do not use the virtual keyword you are not overriding, but rahter defining an unrelated method in the derived class that will hide the base class method. That is, without the virtual, Base::say and Derived::say are unrelated --besides the name coincidence.
When you use the virtual keyword (required in the base, optional in the derived class), you are telling the compiler that classes that derive from this base will be able to override the method. In that case, Base::say and Derived::say are considered overrides of the same method.
When you use a reference or pointer to a base class to call a virtual method, the compiler will add the appropriate code so that the final overrider is called (the override in the most derived class that defines the method in the hierarchy of the concrete instance in use). Note that if you do not use references/pointer but local variables, the compiler can resolve the call and it does not need to use the virtual dispatch mechanism.
Well I tested it for myself, because there are a lot of things we can think about:
#include <iostream>
using namespace std;
class A
{
public:
virtual void v() { cout << "A virtual" << endl; }
void f() { cout << "A plain" << endl; }
};
class B : public A
{
public:
virtual void v() { cout << "B virtual" << endl; }
void f() { cout << "B plain" << endl; }
};
class C : public B
{
public:
virtual void v() { cout << "C virtual" << endl; }
void f() { cout << "C plain" << endl; }
};
int main()
{
A * a = new C;
a->f();
a->v();
((B*)a)->f();
((B*)a)->v();
}
output:
A plain
C virtual
B plain
C virtual
I think that a good, simple and short answer might look like this (because I think people who can understand more can memorize less thus needing for short and simple explanation):
Virtual methods checks for the DATA of the instance the pointer points to, while classic methods don't thus calling the method correponding to the specified type.
The point of that feature is the following: suppose you have an array of A's. The array can contain B's, C's, (or even derived types.). if you want to sequentially call the same method of all those instances, you would call each one you overloaded.
I find this quite tricky to understand, and obviously any C++ course should explained how this is achieved, because most of the time you are just teached about virtual functions, you use them, but until you understand how the compiler understand them and how the executable will handle the calls, you are in the dark.
The thing about VFtables is that I have never been explained what kind of code it adds, and that's obviously here where C++ requires much more experience than C, and this might be the main reason C++ was labelled as "slow" in its early days: in fact, it's powerful, but just like everything, it's powerful if you know how to use it, or else you just "blow your whole leg off".
When you use the keyword virtual, a virtual function table is created to locate the correct methods in an instance. Then, even if the derived instance is pointed to by a base class pointer, it will still find the correct implementation of the method.
Suppose we have two classes as follows:-
class Fruit {
protected:
int sweetness;
char* colour;
//...
public:
void printSweetness() const {
cout<<"Sweetness : "<<sweetness<<"\n";
return;
}
void printColour() const {
cout<<"Colour : "<<colour<<"\n";
return;
}
virtual void printInfo() const {
printSweetness();
printColour();
return;
}
};
class Apple : public Fruit {
private:
char* genus;
//...
public:
Apple() {
genus = "Malus";
}
void printInfo() const {
Fruit::printInfo();
cout<<"Genus : "<<genus<<"\n";
return;
}
};
And now suppose we have some function like the following...
void f() {
Fruit* fruitList[100];
for(int i = 0; i<100 ; i++) {
fruitList[i]->printInfo();
}
return;
}
In cases like above, we can call the same function and rely on the Dynamic Dispatch Mechanism and the abstraction it provides without knowing what kind of fruits are stored in that array. This simplifies the code to a great deal and increases the readability. And is far far better than using type fields which makes the code ugly!
Whereas in the overridden method, we must know what kind of object we are dealing with or otherwise face the object slicing problem which may lead to unexpected results.
Note - I have written this answer just to explicitly show the benefits.
This is a very important aspect of c++ programming-- almost every interview I've been to, I get asked this question.
What happens if you change your main to:
int main() { Parent* a = new Child(); a->say(); return 0; }
Also, it's worth understanding what a vtable is.

Issues with Partial Class Function Overrides in C++

Is there any issue with partially overriding a set of virtual functions defined by a base class?
My compiler provides the following warning:
overloaded virtual function "MyBaseClass::setValue" is only partially overridden in class "MyDerivedClass".
The classes look like this:
class MyBaseClass
{
public:
virtual void setValue(int);
virtual void setValue(SpecialType*);
}
class MyDerivedClass : public MyBaseClass
{
public:
virtual void setValue(int);
}
The easy way to get rid of this warning is to use different names for the base functions, but I wanted to know if there was any compelling reason to fix this specific warning. I do not believe this violates the C++ standard. My guess is that it's to warn a programmer that they may have forgotten to implement the behavior for all possible input types. In our case, it is intentional to exclude some of the specific types.
Would you discourage suppressing this warning altogether?
The override for setValue(int) hides setValue(SpecialType*) of the base class (see the C++ FAQ Lite), so if you try to call setValue(new SpecialType()) you will get an error.
You can avoid this by adding a using directive to the derived class that "imports" the overloads from the base class:
class MyDerivedClass : public MyBaseClass
{
public:
using MyBaseClass::setValue;
virtual void setValue(int);
};
The warning is correct, it's called "name hiding". A variable of type MyDerivedClass cannot call setValue(SpecialType*).
Now I'm going to blatantly rip off someone else's blog:
Overloading and name hiding in C++
In a phone conversation with Brad last night, he told me about a strange problem he's encountered in his new C++ job. Granted, it's probably no big deal to people with extensive C++ experience, but to those of us who live in managed code worlds, this seemed strange.
In C++, when you have a class with an overloaded method (member function, whatever you want to call it), and you then extend and override that method, you must override all of the overloaded methods.
I understand the case where you have changed a method signature in a child class, thereby invalidating the established interface. In this case, though, it seems counterintuitive, since you're not changing the interface, but selectively overriding. Which is different.
For example:
class FirstClass
{
public:
virtual void MethodA (int);
virtual void MethodA (int, int);
};
void FirstClass::MethodA (int i)
{
std::cout << "ONE!!\n";
}
void FirstClass::MethodA (int i, int j)
{
std::cout << "TWO!!\n";
}
Simple class here with two methods (or one overloaded method). You want to override the two-parameter version, so you continue with the following:
class SecondClass : public FirstClass
{
public:
void MethodA (int);
};
void SecondClass::MethodA (int i)
{
std::cout << "THREE!!\n";
}
Now, when you use an instance of SecondClass, most Java or C# programmers might assume you can call:
int main ()
{
SecondClass a;
a.MethodA (1);
a.MethodA (1, 1);
}
However, the second call won't work, since the two-parameter MethodA is not visible. You can get a pointer and up-cast to FirstClass, but your SecondClass instance doesn't inherit the non-overridden methods directly.
It's clear that the compiler wants to warn you: you created a subclass that behaves differently when giving it an int, but you didn't change it's behavior when giving it a SpecialType*.
Although this might be the intention, it is very very possible that the changed behavior is also needed for the other overloaded virtual functions.
I wish the compiler had warned me harder, the time I ignored it! My overridden method turned out to compile and work well in my scenario, but some other scenario's went really wrong due to the overload not being overridden.
Think twice before you disable that warning!
If you want the original behavior kept, it's easy to just call the parent function:
class MyDerivedClass : public MyBaseClass {
virtual void setValue(int);
// explicit: keep original behavior for SpecialType
virtual void setValue( SpecialType* p ) { MyBaseClass::setValue(p); }
};

Safely override C++ virtual functions

I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would like to add some macro or something that ensures that I didn't accidentally declare a new function, instead of overriding the old one.
Take this example:
class parent {
public:
virtual void handle_event(int something) const {
// boring default code
}
};
class child : public parent {
public:
virtual void handle_event(int something) {
// new exciting code
}
};
int main() {
parent *p = new child();
p->handle_event(1);
}
Here parent::handle_event() is called instead of child::handle_event(), because the child's method misses the const declaration and therefore declares a new method. This could also be a typo in the function name or some minor difference in the parameters types. It can also easily happen if the interface of the base class changes and somewhere some derived class wasn't updated to reflect the change.
Is there some way to avoid this problem, can I somehow tell the compiler or some other tool to check this for me? Any helpful compiler flags (preferably for g++)? How do you avoid these problems?
Since g++ 4.7 it does understand the new C++11 override keyword:
class child : public parent {
public:
// force handle_event to override a existing function in parent
// error out if the function with the correct signature does not exist
void handle_event(int something) override;
};
Something like C#'s override keyword is not part of C++.
In gcc, -Woverloaded-virtual warns against hiding a base class virtual function with a function of the same name but a sufficiently different signature that it doesn't override it. It won't, though, protect you against failing to override a function due to mis-spelling the function name itself.
As far as I know, can't you just make it abstract?
class parent {
public:
virtual void handle_event(int something) const = 0 {
// boring default code
}
};
I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.
In MSVC, you can use the CLR override keyword even if you're not compiling for CLR.
In g++, there's no direct way of enforcing that in all cases; other people have given good answers on how to catch signature differences using -Woverloaded-virtual. In a future version, someone might add syntax like __attribute__ ((override)) or the equivalent using the C++0x syntax.
In MSVC++ you can use keyword override
class child : public parent {
public:
virtual void handle_event(int something) <b>override</b> {
// new exciting code
}
};
override works both for native and CLR code in MSVC++.
Make the function abstract, so that derived classes have no other choice than to override it.
#Ray Your code is invalid.
class parent {
public:
virtual void handle_event(int something) const = 0 {
// boring default code
}
};
Abstract functions cannot have bodies defined inline. It must be modified to become
class parent {
public:
virtual void handle_event(int something) const = 0;
};
void parent::handle_event( int something ) { /* do w/e you want here. */ }
I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.
handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.
EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.
Your compiler may have a warning that it can generate if a base class function becomes hidden. If it does, enable it. That will catch const clashes and differences in parameter lists. Unfortunately this won't uncover a spelling error.
For example, this is warning C4263 in Microsoft Visual C++.
C++11 override keyword when used with the function declaration inside the derived class, it forces the compiler to check that the declared function is actually overriding some base class function. Otherwise, the compiler will throw an error.
Hence you can use override specifier to ensure dynamic polymorphism (function overriding).
class derived: public base{
public:
virtual void func_name(int var_name) override {
// statement
}
};
class MyClass {
public:
MyClass() {}
virtual uint32_t someFunction(bool param = false) {
if (param) {
std::cout << "This is an example virtual function with default code" << std::endl;
}
return 1100; //just for return something
};
then you can override the function as you need
class MyClass2 : public MyClass {
public:
MyClass2();
uint32_t someFunction(bool param) override;
};
uint32_t MyClass2::someFunction(bool verbose) {
std::cout << "This is new implementation for virtual method " << std::endl;
}