Hello,
Have a class Hero. Sometimes I need a deep copy (when all members are copied by value) of this class as a kind of some derived class:
class Hero
{
public:
// members, w/o getters/setters
public:
// Constructors
Hero();
Hero(...)
~Hero();
inline SuperHero* asSuperHero() {
// Here should be retured SuperHero instance initialized with all members of Hero class
}
};
class SuperHero : public Hero
{
private:
// Shouldn't be instantianed manually
SuperHero();
public:
// This class-only specific method
void helpAround();
};
The more obvious way is to implement SuperHero constructor which takes all members and do theirs copy manually (because there is no copy constructor in C++ for derived classes): SuperHero(member1, member2, ...) (kind of this). But when I change amount of Hero members, I alway will should change theirs copy in SuperHero constructors.
To avoid this I would implement asSuperHero() in the following way:
inline SuperHero* asSuperHero() {
return static_cast<SuperHero *>(this);
}
Here I there is no need to copy all members etc. Is this way C++ correct, design-corrent and C++ safe?
Thanks,