static_cast<Derived>(base)

Why does the following code fails to compile?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class Base{
};

class Derived:public Base{
};

int main() {
    
    Base base;
    static_cast<Derived>(base);

    return 0;
}
Last edited on
Because there is no valid conversion from Base to Derived.

For this to work you would have to declare a Derived constructor taking a Base as argument
Derived::Derived(const Base&) or declare a conversion operator Base::operator Derived().
Topic archived. No new replies allowed.