1

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;
}
NH.
  • 2,240
  • 2
  • 23
  • 37
Lodec
  • 87
  • 1
  • 8

1 Answers1

2

tab is an array of X objects, so when you assign the Y object to an element of tab it slices off the Y portions and you are left with just the X part.

Now, if you changed it to:

X * tab[2];
tab[0] = new X;
tab[1] = new Y;
print(*tab[0]);
print(*tab[1]);

It would not do any slicing and it would print XY

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23