1

Say the class B inherits from class A and class A contains a virtual function

virtual public foo() {cout<<"I'm A"<< endl';}

while B contains

public foo() {cout<<"I'm B" << endl';}

Why is it that

A* x = new B;

will let x use the function foo() where it prints out "I'm B", but

A x = B;

would give me the other function?

Marks
  • 33
  • 2
  • Which of the two seems strange to you? – Beta Mar 23 '15 at 02:48
  • 5
    `A x = B;` won't compile. Anyway, read about [object slicing](http://en.wikipedia.org/wiki/Object_slicing) – Igor Tandetnik Mar 23 '15 at 02:48
  • 1
    That is just the mechanism for runtime polymorphism provided by C++. See [this](http://stackoverflow.com/questions/5854581/polymorphism-in-c) answer for a detailed explanation. – Pradhan Mar 23 '15 at 02:52

0 Answers0