1
#include <iostream>
using namespace std;

class ShapeTwoD
 { 
   public:
      virtual int get_x(int);




   protected:
    int x;
 };


class Square:public ShapeTwoD
{    
    public:
      void set_x(int,int);

      int get_x(int);





       private:
        int x_coordinate[3];
        int y_coordinate[3];


};

int main()
 {
    Square* s = new Square;

s->set_x(0,20);

cout<<s->get_x(0)
    <<endl;




    ShapeTwoD shape[100];

    shape[0] = *s;

cout<<shape->get_x(0); //outputs 100 , it doesn't resolve to 
                           //  most derived function and output 20 also


 }

void Square::set_x(int verticenum,int value)
{
  x_coordinate[verticenum] = value;

}


int Square::get_x(int verticenum)
{
  return this->x_coordinate[verticenum];

}

 int ShapeTwoD::get_x(int verticenum)
 {
   return 100;

 }

shape[0] has been initialised to Square . When i call shape->get_x , i cant understand why shape->get_x does not resolve to the most derived class instead it resolves to the base class method of shape->get_x . I have already made the get_x method virtual in my base class .

Can someone explain to me why and how to resolve this issue??

Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • You've got an array of `ShapeTwoD`'s, not an array of `Square`s. Look up "object slicing". – jrok Oct 20 '13 at 11:59
  • 1
    possible duplicate of [What is the slicing problem in C++?](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) – jrok Oct 20 '13 at 12:00

1 Answers1

8

In these lines:

ShapeTwoD shape[100];
shape[0] = *s;

you have "slicing". Your shape array contains ShapeTwoDs and you assign from *s to the first ShapeTwoD. This does not change the type of shape[0], so it is not an object of type Square. Polymorphism could only work when you use pointers:

ShapeTwoD* shape[100]; // now you have 100 (uninitialized) pointers
shape[0] = s;

cout << shape[0]->get_x(0);
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180