0
// pointers to base class
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
};

class Rectangle: public Polygon {
  public:
    int area()
      { return width*height; }
};

class Triangle: public Polygon {
  public:
    int area()
      { return width*height/2; }
};

int main () {
  Rectangle rect;
  Triangle trgl;
  //Polygon * ppoly1 = &rect;
  //Polygon * ppoly2 = &trgl;
  //ppoly1->set_values (4,5);
  //ppoly2->set_values (4,5);
    Polygon  ppoly1 = rect;
    Polygon  ppoly2 = trgl;
    ppoly1.set_values (4,5);
    ppoly2.set_values (4,5);

  cout << rect.area() << '\n';
  cout << trgl.area() << '\n';
  return 0;
}

I know that commented lines( when pointer of Polygon is used to call function, its fine). Why do we need to take a pointer , why cannot we just use normal variable of type Polygon. I tried compiling, it compiles fine, but does not give the correct result. Why is it so ?.

2 Answers2

4
  • You are slicing your objects when you assign a Rectangle/Triangle to a Polygon. See What is the slicing problem in C++?

  • Then you call set_values on (sliced) copies, so when you compute the area of the originals polygons, no values are actually set.

  • Also your base class Rectangle should define a virtual destructor, and int area() should probably be a const pure virtual method of Polygon

Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88
0

Because when you do

Polygon  ppoly1 = rect;

you are creating another ppoly1 object by copying values in the rect object. So when you modify values of ppoly1 actually you are not affecting the ones in rect, kind of when you make a photocopy of a document and scribble on the copy you are not damaging the original document. A pointer (or a reference) instead refers to the same object as before: think of the & operator as getting the position of the object. If you copy a pointer you are copying not the object itself but only its position, which is still the position of the original object. Think as if you write your home address to a stranger on a paper sheet: if he robs the house whose address is written in the paper sheet, your same house will be robbed.

pqnet
  • 6,070
  • 1
  • 30
  • 51