Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism in C++: Calling an overridden method

Tags:

First, I'm Java coder and want to understand polymorphism in c++. I wrote the example for learning purposes:

#include<iostream>

using namespace std;

class A
{
public:
    virtual void foo(){ std::cout << "foo" << std::endl; }
};

class B : public A
{
public:
    void foo(){ std::cout << "overriden foo" << std::endl; }
};

A c = B(); 

int main(){ c.foo(); } //prints foo, not overriden foo

I expected that overriden foo would be printed, but it wasn't. Why? We overrode the method foo in the class B and I thought that the decision which method should be called is being making from the runtime type of the object which in my case is B, but not a static type (A in my case).

Live example is there