Zavior
Zavior

Reputation: 6462

function parameters, polymorphism

I have the following piece of code. I was wondering if there was a way to modify foo(A a) so that calling it would have the result as in the commented code below, but without overloading.

class A { 
  public: virtual void print() { std::cout << "A\n"; } };
class B : public A {
  public: virtual void print() { std:cout << "B\n"; }
};

void foo( A a ) { a.print(); } // How to modify this, so it chooses to use B's print()?
// void foo( B a ) { a.print(); } // now, this would work! 

int main( void ) { 
  A a; 
  foo( a ); // prints A
  B b;
  foo(b);  // prints A, but I want it to print B
}

Is this possible at all? If not, why?

Upvotes: 0

Views: 823

Answers (1)

Cat Plus Plus
Cat Plus Plus

Reputation: 129954

You must take the argument via reference (or pointer, but you don't need pointers here), otherwise the object gets sliced.

void foo(A& a) { a.print(); }

Upvotes: 5

Related Questions