2

How does C++/the compiler know in the code below when to execute the right piece of code? And how is this stored (behind the scenes)? My vector contains Base* but there must be some extra information somewhere, right?

The compiling code which is the same as this:

class Base {
    public:
        Base()=default;   
        virtual void DerivedOrBase() { std::cout << "Base\n"; }
};

class Derived : public Base {
    public:
        Derived()=default;   
        void DerivedOrBase() override { std::cout << "Derived\n"; }
};

int main()
{
    std::vector<Base*> myVector;
    myVector.push_back(new Base());
    myVector.push_back(new Base());
    myVector.push_back(new Base());
    myVector.push_back(new Derived());
    
    for(auto p : myVector) p->DerivedOrBase();

    return 0;
}
dejoma
  • 394
  • 1
  • 6
  • 18

0 Answers0