Darlyn
Darlyn

Reputation: 4938

map of derived classes

I have a base class

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 , const Person & b){
        a[name] = b
   }
protected:
    string name;
    int age;
    map<string , Person > a;
};

That contains map of object type Person. I want to push various derived classes into that map e.g

Derived class

class Kid : public Person{
public:
    Kid(string name, int age):Person(name,age){};
    virtual void getInfo( ){
        cout << "Kid " << name << " " << age;
    }
};

I want add method of Person class to bahave such as

Person one("John",25);
one.add("Suzie",15);

Which fails. I know i can remake the code using pointers e.g

map<string , Person*> a   
void add( string name , Person *b){
      a[name] = b;
}
Person one("John",25);
one.add(new Kid("Suzie",15))

But is there a way how to achieve it without using pointers?

Upvotes: 1

Views: 404

Answers (2)

pcodex
pcodex

Reputation: 1940

your original design ends up recursing infinitely. You need a polymorphic map, but do you need it to be a member of the class??

Take a look at this question Can a c++ class include itself as an attribute?

Upvotes: 0

Jack
Jack

Reputation: 133577

No, you can't obtain polymorphism without using references or pointers.

The issue is easily understood by thinking that a non pointer object requires to store the whole class data (including the vtable).

This means that a map<string, person> will store somewhere person instances in a sizeof(person) slot.

But a sizeof(person) can't contain enough data to store additional information of subclasses of person. This leads to object slicing.

Upvotes: 3

Related Questions