Following up a similar question in previous post about downcasting and type safety , I wonder if the following example creates undefined behavior.
An instance of Base class has been created. No dynamic binding take place.
However, in the Base::interface function the instance of the Base class is casted to an instance of the Derived class .
Is this safe? If yes , why ?
Please find the piece of code below.
#include <iostream>
template <typename Derived>
struct Base{
void interface(){
static_cast<Derived*>(this)->implementation();
}
};
struct Derived1: Base<Derived1>{
void implementation(){
std::cout << "Implementation Derived1" << std::endl;
}
};
int main(){
std::cout << std::endl;
Base<Derived1> d1;
d1.interface();
std::cout << std::endl;
}