Odai Mohammed
Odai Mohammed

Reputation: 319

Calling class functions through a pointer to the class

Suppose we have the following class:

    class Cell
    {
    private:
        int x;
        Cell *next;
    public:
        Cell(int a)
        {
              x = a;
        }
        int getX()
        {
              return x;
        }
        Cell *getNext()
        {
              return next;
        }

     };

as well as the fallowing class:

    class Snake
    {
    private:
        Cell *tail;
    public:
        Snake()
        {
            Cell newCell(10);
            tail = &newCell;
        }
        Cell *getTail()
        {
            return tail;
        }
    };

and this is our main function:

      int main()
      {
           Snake newSnake;
           int a = newSnake.getTail()->getX();
           cout << a << endl;
           return 0;
       }

when I execute my code I get the output:

      -858993460     

when the output is expected to be:

       10

and I can't seem to figuer out what the problem is, any ideas?

Upvotes: 0

Views: 56

Answers (2)

Humam Helfawi
Humam Helfawi

Reputation: 20311

 tail = &newCell; 

this line will cause undefined behaviour. after it goes out of scope newCell is destroyed and tail still pointing there where could be anything (correct value, 0, random value or....)

To solve your problem:

First, I believe the whole design is broken and need to be reviewed. However, I will correct the mistake with less possible changes without touching the design.

change this:

   Snake()
    {
        Cell newCell(10);
        tail = &newCell;
    }

to:

   Snake()
    {
        Cell newCell(10);
        tail = new Cell(10);;
    }

And add this:

   ~Snake()
    {
        delete tail;
    }

Upvotes: 1

Greg M
Greg M

Reputation: 954

Yes, this would be the correct way. When you type

ptr->getX()

its the same thing as

(*(ptr)).getX()

You can always look at the reference for the -> operator too.

Upvotes: 0

Related Questions