In this specific case1, the compiler (at least in theory) can determine which function is called in each case, and generate code to simply call the two functions directly (and when I've tested it, most compilers will optimize code like this exactly that way).
A more typical case for polymorphism would involve some sort of user input, so the function to be called can't be determined statically. For example, using your Base and Derived classes, consider something like:
int main(int argc, char **argv) {
Base b;
Derived d;
Base *arr[] = {&b, &d};
int i = atoi(argv[1]) != 0;
arr[i]->foo();
return 0;
}
In this case, the compiler can't determine the correct function to call statically -- depending on what you pass on the command line when you run it, it might use either the Base or the Derived version of foo().
You also seem to have a kind-of intermediate case you started to try to include in your code, but never really completed -- you initialize ptr to point at your Base object and then your Derived object, but you never invoke a function via ptr, only directly on the objects themselves. If you did invoke the functions via the pointer, it would be harder to optimize than when working only directly with concrete objects. Fewer compilers will determine the type statically in this case, but at least some still can/will.
1Well, almost this specific case anyway. As it stands right now, the code won't compile, because you've defined a class named base (lower-case 'b') and tried to instantiate a class named Base (upper-case 'B'). Also, your "Derived" class isn't actually derived from Base, as you presumably intended. Once those are fixed though...
Derivedclass as a child class ofbase? I don't see the inheritance...ptr->foo();somewhere?Derived::foo()is private !!!