RedFox
RedFox

Reputation: 85

Class return value bug

Hello guys i have a logical problem...i had to do a kinda fo labyrinth and it work but then im trying to do it with classes...so here it is.

i have a function outside of main called void playeraction();

cout<<"\nAction : ";
cin>>action;

int prevX=posX;
int prevY=posY;
unsigned char space = {32};

switch (action)
{
    case 'a':
        if(grid[posX][posY-1]!='#')
        {
            posY--;
            grid[prevX][prevY]=space;
            system("cls");
            break;
        }

when its like this the character moves without any problem now when i try to implimenet classes it doesnt

    case 's':

        if(grid[posX+1][posY]!='#')
        {
            Dragon obj;
            obj.moveSouth(posX);
            grid[prevX][prevY]=space;
            system("cls");
            break;
        }

in dragon cpp

int Dragon::moveSouth(int posX)
{
    return posX++;
}

any ideas why it doesn't return the posX++??

Upvotes: 1

Views: 105

Answers (3)

Yuan
Yuan

Reputation: 1157

In your code, there are some bugs.

First, for 'posX++', posX is increased after using its value. You should use ++posX to make it be increased before using.

Second, in the function, the memory of its arguments is on stack. They are temporary, not origin memory of the variables.

You can use reference for this code.

void Dragon::moveSouth(int & posX){

    posX++;

}

Upvotes: 1

Syntactic Fructose
Syntactic Fructose

Reputation: 20076

your function does not modify any sort of internal or external variable, it simply returns a value that is never caught. There are a number of solutions to this,

  • Create internal class variables to keep track of position, only calling a function to modify the position on the map.

class dragon
{
    //...
    void moveDragon(int num, int num2);
    private:
        int posX;
        int posY;
}

void dragon::moveDragon(int num, int num2)
{
    posX -= num;
    posY -= num2;
}
  • Have the function return the same value subtracted for the function

posX = obj.MoveSouth(posX); //new posX now holds the value

Upvotes: 0

Dan
Dan

Reputation: 1486

Because you are not assigning the returned value to any variable. Try this:

int newSouth = obj.moveSouth(posX);

This will assign to newSouth the new posX value.

EDIT: You have to also modify your moveSouth function, as Mats Petersson mentions in the first comment.

int Dragon::moveSouth(int posX){

 int newX = posX++;
 return newX;

}

However, if rather than returing a new value you wanted to increase the original posX, just use a reference to posX, as mentioned by Yuan in the other answer.

Upvotes: 0

Related Questions