1

I faced a confusing behavior. I can't understand why this code behave like this.

#include <iostream>
#include <cstdlib>

struct A {
    virtual void test() = 0;
};

struct B : public A {
    void test() override { std::cout << "B" << std::endl; }
};

struct C : public A {
    void test() override { std::cout << "C" << std::endl; }
};

int main()
{
    A* b = new B();
    A* c = new C();


    A* t = b;
    t->test();

    t = c;
    t->test();
}

It will work to put out this.

B
C

But, this code work like this.

#include <iostream>
#include <cstdlib>

struct A {
    virtual void test() = 0;
};

struct B : public A {
    void test() override { std::cout << "B" << std::endl; }
};

struct C : public A {
    void test() override { std::cout << "C" << std::endl; }
};

int main()
{
    A* b = new B();
    A* c = new C();


    A& t = *b;
    t.test();

    t = *c;
    t.test();
}
B
B

I expected to return this code will put out the first code. But not. I can't understand why the second code doesn't put out like the first code. Would you mind letting me know the reason of this behavior?

shikugawa
  • 37
  • 2
  • 1
    `t = *c;` this does not reassign the reference, it assigns the value of the object pointed at by `c` to the object referred to. References are not re-assignable in any circumstances. –  May 05 '20 at 14:51
  • Yep, you can't reassign references. You're overwriting the base-class subobject of `*b` with a copy of the base-class subobject of `*c`. I'm not sure I've ever seen that much object slicing in a single statement! – Useless May 05 '20 at 14:53
  • `t = *c;` is basically `*b = *c;`. – François Andrieux May 05 '20 at 14:55

0 Answers0