Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual functions and static_cast

Can i safely call virtual functions after using static_cast on polymorphic class in situations like in the following code or is it UB?

#include <iostream>

class Base
{
public:
   virtual void foo() { std::cout << "Base::foo() \n"; }
};

class Derived : public Base
{
public:
   virtual void foo() { std::cout << "Derived::foo() \n"; }
};

int main()
{
   Base* derived = new Derived;
   Derived* _1 = static_cast<Derived*>(derived);
   _1->foo();
}
like image 770
FrozenHeart Avatar asked Mar 06 '26 06:03

FrozenHeart


2 Answers

Yes, you can. Although I don't see the point of doing that in your specific example. Just calling it as

derived->foo();

without any casts would have produced exactly the same effect. I.e. some sort of static_cast in that case would be performed implicitly by the virtual call mechanism.

Note that your static_cast does not in any way suppress the "virtual" nature of the call.

That actually makes me wonder what your question is really about. Why would you even ask about it? What are you trying to do? In your code sample really representative of what you are trying to do?

like image 170
AnT Avatar answered Mar 08 '26 19:03

AnT


If the compiler allows you to static_cast and at run-time the dynamic type of the object is as expected, then yes, you can. The question is why do you want to do that...

like image 33
Paul Michalik Avatar answered Mar 08 '26 20:03

Paul Michalik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!