Is casting a class to a subclass of itself without additional data fields well defined?
For example if I wanted to hide certain internal only methods from an end user like in the following.
#include <string>
#include <iostream>
// public.hpp
class Talker {
public:
Talker(std::string text) {
this->text = text;
}
virtual void talk() {
std::cout << this->text << std::endl;
}
protected:
std::string text;
};
// private.cpp
class InnerTalker : public Talker {
public:
void setText(std::string text) {
this->text = text;
}
};
int main(int argc, char **argv) {
Talker t("Hello World!");
t.talk();
InnerTalker *ht = reinterpret_cast<InnerTalker *>(&t);
ht->setText("Farewell World!");
t.talk();
return 0;
}
I have compiled this example and it works as I expect. Printing:
Hello World!
Farewell World!
However that does not make it well defined behavior.
Thank you in advance for any information you can provide.
From cppreference:
Performing a class member access that designates a non-static data member or a non-static member function on a glvalue that does not actually designate an object of the appropriate type - such as one obtained through a reinterpret_cast - results in undefined behavior:
You can perform the reinterpret_cast
, but doing nearly anything that uses the resulting pointer will result in UB.