I've trying to find some information towards casting class values within their hierarchy, but I have only been able to find useful information about casting pointers to classes.
So here we go:
#include <map>
#include <string>
#include <iostream>
class Base {
protected:
std::map<std::string, std::string> properties;
};
class Sub: public Base {
public:
std::string &first_name() {
return properties["first_name"];
}
std::string &last_name() {
return properties["last_name"];
}
};
Base factory() {
Sub sub;
sub.first_name() = "John";
sub.last_name() = "Doe";
return sub;
}
int main() {
Base base(factory());
Sub sub(static_cast<const Sub &>(base));
std::cout << "First name: " << sub.first_name() << std::endl;
std::cout << "Last name: " << sub.last_name() << std::endl;
return 0;
}
Is the behaviour of the program above problematic or is it well-defined? I am basically dealing with subclasses of a base class, where only the base class has attributes. All subclasses only have functions. Is it an issue if the objects are freely converted from their base to the sub and back?