Reputation: 2457
In my code I have naturally, without thinking about it first, type-casted a derived struct into a base struct in order to call an overloaded function and later realized that it might cause problems in some cases (though I honestly don't know if and which).
My code goes as follows:
struct Base
{
//some variables
}
struct Derived : Base
{
//some more variables
}
bool func(const Base &base1, const Base &base2)
{
//do some stuff and return true or false
}
bool func(const Base &base, const Derived &derived)
{
if(func(base, (Base)derived))
return true;
else
//do some more stuff and return true or false
}
The code compiles and the functions work as intended.
I have found tons of questions on SO and elsewhere about up- and down-casting, but they all involve using pointers instead of directly typecasting to the base class. In this link the person directly typecasts, however, to the derived class not the base. There are no questions I found that actually deal with this problem directly, but I might simply not know what to look for, so please point me in the right direction in that case!
I assume (and have read online) that typecasting involves creating a copy, so (Base)derived
will not simply return a reference to derived
, but using the first function. Are there any other downsides or issues that I might run into?
Upvotes: 1
Views: 3507
Reputation: 1827
Use static_cast<const Base&>(derived)
instead of (Base)derived
. It will forward reference, and correct overload resolution.
Upvotes: 6