jeudi 10 août 2017

C++ polymorphism in simple example

I have this set of classes.

class Animal {
public:
    Animal(uint32_t attr1, uint32_t attr2);

    virtual uint32_t get_attr1() const;
    virtual uint32_t get_attr2() const;

private:
    uint32_t attr1;
    uint32_t attr2;
};

class Dog: public Animal {
public:
    Dog(uint32_t attr1, uint32_t attr2, uint32_t attr3);
    uint32_t get_attr3() const;

private:
    uint32_t attr3;
};

class Cat: public Animal {
public:
    Cat(uint32_t attr1, uint32_t attr2, uint32_t attr4);
    uint32_t get_attr4() const;

private:
    uint32_t attr4;
};

Now I want to have

vector<Animal*> animals;

and few functions that are declared as follows:

void f(Dog* dog);
void f(Cat* cat);

and this code:

for (auto animal: animals) {
    f(animal);
}

how to make polymorphism out of this code? It looks like animal is not treated like cat or dog.

Aucun commentaire:

Enregistrer un commentaire