I have Base and Derived class Base :
class Person{
public:
Person(string name , int age ){
this -> name = name;
this -> age = age;
}
virtual void getInfo(){
cout << "Person " << name << " " << age;
}
protected:
string name;
int age;
};
Derived:
class Kid : public Person{
public:
Kid(string name, int age):Person(name,age){};
virtual void getInfo( ){
cout << "Kid " << name << " " << age;
}
};
class Adult : public Person{
public:
Adult(string name, int age):Person(name,age){};
virtual void getInfo( ){
cout << "Adult " << name << " " << age;
}
};
When i do something like
map<string ,Person*> m;
Person *one;
Person *three;
Kid two("Mathew",15);
Adult four("JOhn",55);
three = &four;
one = &two;
m["first"] = one;
m["second"] = three;
for( auto &x : m )
x.second-> getInfo();
return 0;
It nicely prints info as it should // "Adult" for adult class and "Kid" for kid class
however when i edit the class and move the map into base class. e.g and create Add
method.
class Person{
public:
Person(string name , int age ){
this -> name = name;
this -> age = age;
}
virtual void getInfo(){
cout << "Person " << name << " " << age;
}
void add( string name , Person a){
Person *one = &a;
m[ name ] = one;
}
void print(){
for( auto &x: m )
x.second -> getInfo()
}
protected:
string name;
int age;
map< string , Person*> m;
};
Person one("John", 25);
one.add("first",Kid("Mathew",15));
one.add("second",Adult("Leo",55));
one.print();
It throws seg fault , why is this happening? Its basicly the same implementation with using of method. What causes the seg fault? Is there a way how to fix it?
// EDIT
I tried using unique_ptr redecaring map as
map< string , unique_ptr<Person>> m;
AddField (string name , Person a ){
m[name] = ( unique_ptr<Person> (a));
return *this;
}
or
properties[name] = unique_ptr<Person> ( new Person( a ));
or
AddField (string name , Person a ){
CData *one = unique_ptr<Person>(new Person(a));
m[name] = one ;
return *this;
}
I am not experienced with unique/share ptr. This threw
‘std::unique_ptr’ to ‘Person*’