Q:

virtual function outputting weird values

I have 2 classes : ShapeTwoD & Square . Square is derived from ShapeTwoD.
class ShapeTwoD
 { 
   public:virtual int get_x()
          { return x;}

          void set_x(int x)
          {x = x; }

   private:
        int x;
 };

class Square:public ShapeTwoD
{    
    public:
          virtual int get_x()
          { return x+5; }

    private:
           int x;

};

In my main programme
int main()
{
 Square* s = new Square;

s->set_x(2);

cout<<s->get_x()  //output : 1381978708 when i am expecting 2
    <<endl;

ShapeTwoD shape[100];

shape[0] = *s;

cout<<shape->get_x(); //output always changes when i am expecting 2

}

The console output i am getting is very weird.
The first output is 1381978708 though i am expecting it to be 2 . 
The second output always changes though i am also expecting it to be 7
I am trying to use virtual functions to resolve to the most derived class method , 
can someone explain to me what is happening ???

A:

Take a look at the comments in the code:
class ShapeTwoD
{ 
public:
    virtual int get_x()
    {
        return x; // outputs ShapeTwoD::x
    }

    void set_x(int x)
    {
        // x = x;   // sets x to x
        this->x = x // sets ShapeTwoD::x
    }

   private:
        int x;
 };

class Square:public ShapeTwoD
{    
public:
    virtual int get_x()
    {
        return x + 5; // Outputs Square::x
    }

private:
    int x;
};

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

    s->set_x(2);

    cout<<s->get_x()  //output : 1381978708 when i am expecting 2
        <<endl;       // because Square::x is uninitialized

    ShapeTwoD shape[100];

    shape[0] = *s; // slices Square to ShapeTwoD

    cout<<shape->get_x(); //output always changes when i am expecting 2
                          // look at the comments to the set_x function
}

So, because x is declared as private in the ShapeTwoD, Square can't get access to it. You have to do:

Make x protected in ShapeTwoD
Remove x from Square
Change x = x in set_x to this->x = x (or rename member variable, say, to _x)

