Warning: Note that this is a dumb question of something that I would probably never solve in this manner. Hence the contradicting title. But since I have actually seen something similar in code I have gone through on a very large system I became intrigued. 🙂
Let’s say we have a simplified class:
class Foo
{
void a();
virtual void b();
}
and then another class
class Bar : public Foo
{
void a();
}
If a general part of the program handles all these classes as the base class of type Foo, how do I in the best manner call the “correct” version of function a within b? Since there is a possibility that the object is of type Bar.
And say you, for legacy reasons, could not change the existing code and make the base class a function virtual etc.
What I did was to make a virtual in the base class and implement b within Bar since I had that option. But let’s, for the sake of argument, say that this was impossible or disallowed. How “wrong” would it be to implement a workaround using something like this.
void b() {
...
Bar* dabar;
if((dabar = dynamic_cast<Bar*>(this)) != NULL) {
dabar->a();
}
else {
a();
}
}
As I said, note that this is when dealing with base classes and wanting to call the function of a child class. Not the other way around.
If there is a possibility to make your function virtual in the base class,
this is the way to go, including the overhead of calling a different company
to change there code, as this is clearly a design flaw.
If you do not have this possibility, for what reason whatsoever,
your code will work, except when you want to derive from Bar.
What do you think will happen, when you have a Bar* and call “a” on that.
Like:
And, of course, dynamic_cast will imply a serious disadvantage on performance.
Write clean code, write what you want to express, do not use tricks!