1

I'm wondering how polymorphism works with objects instead of pointers. I wrote the following example:

This code:

#include <iostream>
#include <vector>

class Base {
public:
    virtual void ToString() {
        std::cout << "Base" << std::endl;
    };
};

class DerivedA : public Base {
public:
    void ToString() final {
        std::cout << "DerivedA" << std::endl;
    }
};

class DerivedB : public Base {
public:
    void ToString() final {
        std::cout << "DerivedB" << std::endl;
    }
};


int main(int argc, char **argv) {
    std::vector<Base> v;
    v.push_back(DerivedA());
    v.push_back(DerivedB());

    v[0].ToString();
    v[1].ToString();
    return 0;
}

Show this output:

Base

Base

While:

int main(int argc, char **argv) {
    std::vector<Base*> v;
    v.push_back(new DerivedA());
    v.push_back(new DerivedB());

    v[0]->ToString();
    v[1]->ToString();
    return 0;
}

Shows this:

DerivedA

DerivedB

Why in the first example is calling the base method while the second one calls the derived ones?

nachovall
  • 485
  • 1
  • 5
  • 18

0 Answers0