Reputation: 1
Very simple example of c++ inheritance :
#include <iostream>
using namespace std;
class A{
public :
virtual void print(A a){
cout<<"a"<<endl;
}
};
class B : public A {
public :
virtual void print(A a){
cout<<"a2"<<endl;
}
virtual void print(B b){
cout<<"b"<<endl;
}
};
int main(){
B b;
A &a = b;
a.print(b);
return 0;
}
Why does this output a2?
I would have expected this to be effectively the same as :
b.print(b)
thanks!
Upvotes: 0
Views: 80
Reputation: 308140
Because your reference is a type A
, only the A
methods will be considered when deciding what to call. Since print(A)
was virtual, it will actually call the method from B
that matches the signature from A
.
If this is confusing, consider if you had added a method foo
to B
. What would happen if you tried to call a.foo()
? It would fail, because objects of type A
don't have a foo
method.
Upvotes: 2