I have the following code which return "YXX".
I would like to know why the second print displays an 'X' whereas the key-word virtual
is used in the class X. So the line tab[0] = y1
will be set tab[0] as an Y object and displays 'Y' due to the virtual method isn't it ?
#include <iostream>
class X {
public: virtual void f() const { std::cout << "X"; }
};
class Y : public X {
void f() const { std::cout << "Y"; }
};
void print(const X &x) { x.f(); }
int main() {
X tab[2];
Y y1;
tab[0] = y1;
print(y1);
print(tab[0]);
print(tab[1]);
std::cout << std::endl;
}