0

I've created a BaseClass and two subclasses: SubOne and SubTwo. After that I created a collection called MyCollection which stores the instances in a vector.

Both the base class, and the subclasses have the method getString. Base class returns with base, and the subclasses with sub1 and sub2.

I don't get any warning or error during the compilation. But for some reason, if I try to iterate over the vector, the subclasses return "base"

#include <iostream>
#include <vector>

class BaseClass {

    public:

        BaseClass() {}

        std::string getString() {
            return "base";
        }

};

class SubOne : public BaseClass {

    public:

        SubOne() : BaseClass() {}

        std::string getString() {
            return "sub1";
        }

};

class SubTwo : public BaseClass {

    public:

        SubTwo() : BaseClass() {}

        std::string getString() {
            return "sub2";
        }

};

class MyCollection {

    private:

        std::vector<BaseClass> instances;

    public:

        MyCollection() {}


        void add(BaseClass & ins) {
            instances.push_back(ins);
        }

        std::string printString() {

            for(std::vector<BaseClass>::iterator it = instances.begin() ; it != instances.end(); ++it) {
                std::cout << it->getString() << std::endl;
            }

        }

};

int main() {

    MyCollection *coll = new MyCollection();

    SubOne* s1 = new SubOne();
    SubTwo* s2 = new SubTwo();

    coll->add(*s1);
    coll->add(*s2);

    coll->printString();

    return 0;

}
Iter Ator
  • 8,226
  • 20
  • 73
  • 164

1 Answers1

1

You forgot to use keyword virtual. Also translate to pointers (credit goes to Captain Giraffe).

See code below:

#include <iostream>
#include <vector>

class BaseClass {

public:

    BaseClass() {}

    virtual std::string getString() { // BINGO _!_!_!_!
        return "base";
    }

};

class SubOne : public BaseClass {

public:

    SubOne() : BaseClass() {}

    std::string getString() {
        return "sub1";
    }

};

class SubTwo : public BaseClass {

public:

    SubTwo() : BaseClass() {}

    std::string getString() {
        return "sub2";
    }

};

class MyCollection {

private:

    std::vector<BaseClass*> instances;

public:

    MyCollection() {}


    void add(BaseClass* ins) {
        instances.push_back(ins);
    }

    std::string printString() {

        for(std::vector<BaseClass*>::iterator it = instances.begin() ; it != instances.end(); ++it) {
            std::cout << (*it)->getString() << std::endl;
        }

    }

};

int main() {

MyCollection *coll = new MyCollection();

SubOne* s1 = new SubOne();
SubTwo* s2 = new SubTwo();

coll->add(s1);
coll->add(s2);

coll->printString();

return 0;

}
Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20