See the code beblow, I have a question about crtp:
foo_aa.name_is illegal becausefoo_aais not an object ofclass AA(it is an object ofclass Foo<AA>), it doesn't have a class member calledname_. I can understand that.- But I don't understand why
foo_aa.Name()is legal, because I never define any object ofclass AA, there is no such variable(name_) in memory, how does theNamefunction assess variablename_?. - More specifically, I know the cast is made in function
Name. But I don't understand why the cast is valid, bacause there is only oneFoo<AA>object and it is just a base class object, how can it be converted to a derived class?
namespace static_poly {
template<typename T>
class Foo {
public:
std::string Name() {
return static_cast<T*>(this)->GetName();
}
};
class AA : public Foo<AA> {
public:
std::string GetName() { name_ = "AA"; return name_; }
std::string name_;
};
void Test() {
Foo<AA> foo_aa;
foo_aa.Name(); // legal
foo_aa.name_ = "hello"; // illagel
}
} // static_poly
According to Base to derived conversion, I know a base class object can be converted to a derived class object, but the behavior is undefined, why crtp is ok?