Hello!
I have started with C++ and I have a question regarding class casting in c++.
Let's say I have 2 classes and one extends the other:
1 2 3 4 5 6 7 8 9 10
|
class Person {
public:
Person();
Person(const Person& orig);
virtual ~Person();
int getAge();
void setAge(int age);
private:
int age;
};
|
and
1 2 3 4 5 6 7
|
class MyPerson : public Person {
public:
MyPerson();
MyPerson(const MyPerson& orig);
virtual ~MyPerson();
int getAge();
};
|
where funtion
getAge()
is only a call to Person:
1 2 3
|
int MyPerson::getAge(){
return Person::getAge();
}
|
In some part of my code I am doing a static_cast from
Person
to
MyPerson
:
1 2
|
Person p = getFromSomeWhereAPerson();
MyPerson mp = static_cast<MyPerson>(p);
|
I think is not save, because a
Person
must
not be a
MyPerson
instance but in this case,
MyPerson
is only calling its super class
Person
...and compiles and I don't have (at the moment) segmentation faults :)
In order to avoid the static_cast, I have thought in 2 solutions:
1) Copy manually all properties from a
Person
to a
MyPerson
:
1 2 3 4 5 6 7 8 9
|
class MyPerson : public Person {
public:
MyPerson();
MyPerson(const MyPerson& orig);
virtual ~MyPerson();
int getAge();
// Copy state from Person
void loadFromPerson(Person p);
};
|
where
1 2 3
|
int MyPerson::loadFromPerson(Person p){
Person::setAge(p.getAge());
}
|
2) Another idea is to convert
MyPerson
in a wrapper:
1 2 3 4 5 6 7 8 9 10
|
class MyPerson : public Person {
public:
MyPerson();
MyPerson(const MyPerson& orig);
virtual ~MyPerson();
const Person* getDelegate();
int getAge();
private:
Person * _delegate;
};
|
where
getAge()
is a call to its wrapped
Person
:
1 2 3
|
int MyPerson::getAge(){
return _delegate->getAge();
}
|
I don't really know what to do and I think this is a common situation....any suggestion?
Than you in advance!