class Parent{
public:
~Parent() = 0;
virtualbool isChild1() const = 0;
void changeChild();
private:
}
class Child1 : public Parent{
public:
~Child1(){};
bool isChild1(){returntrue;}
private:
// some int
}
class Child2 : public Parent{
public:
~Child2(){};
bool isChild1(){returnfalse;}
private:
// some other int
}
Let me assume I have a vector of <Parent*> what's the right way to implement changeChild so that i can mutate from Child2 to Child1 (or viceversa)?
1 2 3 4 5 6 7 8
std::vector<Parent*> v{};
// initalize v with appropriate Childs;
for (int i = 0;i<v.size();++i){
if (v[i]->isChild1()){
v[i].changeChild()
}
}
// ideally now all the vector elements are pointers to Child2
What I'd like to do is something like
1 2 3 4 5 6 7 8
void Parent::changeChild(){
if(this->isChild1()){
// create a new pointer to a Child2 and point this to it
}else{
// create a new pointer to a Child1 and point this to it
}
//somehow destroy the original this.
}
I have problems as in the function definition I cannot point "this" to something else.
Is there any workaround for this kind of operation? Thanks.
I have merely a faint recollection that something like this might apply:
1 2 3 4 5 6 7 8 9 10
std::vector<Parent*> v{};
// initalize v with appropriate Childs;
for ( auto & p : v ) {
if ( auto c1 = dynamic_cast<Child1*>( p ) ) {
Child2* c2 = new Child2 // initialize *c2 or copy appropriate bits from *c1
delete p;
p = c2;
}
}
which is cool, I managed to understand your answer and use a less elegant version for my problem, check for memory leaking and be happy.
Agan on topic, I am trying to overload the >> operator for the Parent class, so that I'll be able, for example, to read data from file.
I defined in the Parent.hpp file the function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
std::istream& operator>>(std::istream& is, Parent* var){
bool isChild1;
is>>isChild1;
if(isChild1){
//define Child1 vars
is >> vars;
if(!is)return is;
Child1 *pippo = new Child1(vars);
var = pippo;
return is
}else{
//define Child2 vars
is >> vars;
if(!is)return is;
Child2 *pippo = new Child2(vars);
var = pippo;
return is;
}
}
The compiler does not complain, but I am not confident this bit of code is safe. Is there a better way to define an >> operator to read either Child1 or Child2 dynamically from file?
Thanks in advance.