glonk
glonk

Reputation: 1

C++ Private Memeber Variable Inaccessible to Memeber Function

I am working on recreating pong, and while moving drawPaddle function from the main Game class to the Paddle class I ran into an issue where the function cannot read the member variables (even though they are in the same class). The class is in a header file and the function definitions are in a cpp file. The variables in question are height, width, xPos, and yPos.

Paddle class

#include "Graphics.h"

class Paddle
{
public:
    void setX(int z)
    {
        xPos = z;
    }
    int getX()
    {
        return xPos;
    }
    void setY(int z)
    {
        yPos = z;
    }
    int getY()
    {
        return yPos;
    }
    int getWidth() {
        return width;
    }
    void setHeight(int z)
    {
        height = z;
    }
    int getHeight()
    {
        return height;
    }
    void setPlayer(bool z)
    {
        player = z;
    }
    bool getPlayer()
    {
        return player;
    }

private:
    //functions
    void drawPaddle(Graphics& gfx);
    void updatePaddle(Graphics& gfx);

    //variables
    int xPos;
    int yPos = Graphics::ScreenHeight / 2 - Paddle::height / 2;
    bool player;
    static constexpr int width = 20;
    int height = 100;
};

drawPaddle function

#include "Paddle.h"
#include "Graphics.h"

void drawPaddle(Graphics gfx)
{
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < Paddle::height; j++)
        {
            gfx.PutPixel(p.getX() + i, p.getY() + j, Colors::White);
        }
    }
}

As you can see I've tried accessing it with the raw variable (tells me the variable is undefined), through the class (tells me the variable is inaccessible), and using the getter for it (failed because it must be in reference to a specific instance). Anyone have any idea what I am doing wrong? Thanks.

Upvotes: 0

Views: 123

Answers (1)

rsjaffe
rsjaffe

Reputation: 5730

In the definition, you didn't indicate that drawPaddle was a member of Paddle, so it was treating that definition as a definition of a free function, not a member function. Free functions wouldn't have access to the private members.

It should start with void Paddle::drawPaddle(Graphics gfx)

Upvotes: 2

Related Questions