0

Following, there is a Abstract class "Shape" and two derived classes "Rectangle" and "Circle" I am using Base class pointer to an object and initializing it to derived object.

Why the last one also prints "Rectangle"?

#include <iostream>
#include <string>

class Shape {
public:
    virtual void show() = 0;
};

class Rectangle : public Shape {
public:
    void show() {
        std::cout << "Draw Rectangle" << std::endl;
    }
};

class Circle : public Shape {
public:
    void show() {
        std::cout << "Draw Circle" << std::endl;
    }
};

int main() {

    Shape *s = new Rectangle();
    s->show();

    Circle c;
    *s = c;

    s->show();

    return 0;
}

Both prints "Rectangle". Why the last one doesn't print "Circle"

But if I do

Circle *c = new Circle();
s = c;
s->show();

Then it prints "Circle"

  • `*s = c;` slices the `Circle` object -- it assigns just the `Shape` object inherited by the `Circle` over the `Shape` object inherited by the `Rectangle`. (In this case it's a no-op because `Shape` has no data members of its own, so `*s = c;` does *nothing at all*.) If you were expecting to change the type of the `Rectangle` object, you can't do that -- objects can't have their actual type changed. Instead try `delete s; s = &c;`, which will destroy the `Rectangle` object and then make the `s` pointer point at `c` instead of a heap object. – cdhowie Jun 03 '17 at 23:36
  • Thanks, makes sense. – user3375257 Jun 03 '17 at 23:51

0 Answers0