"not declared in this scope"

I know this is something very simple for someone, but I'm just trying to dip my toes into using classes, and it's not working.

So, I've set up a simple header file and cpp file, but I get the error below, for line 10:

... error: 'score' was not declared in this scope

But I don't understand why, when score is already declared in the header file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//cPlayer.cpp
#include "cPlayer.h"

cPlayer::cPlayer():score(0)
{
//constructor
}

void setScore(int points){
score+=points;  // error
}

int getScore(){
return score;   // error
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//cPlayer.h
#ifndef CPLAYER_H
#define CPLAYER_H

class cPlayer
{
    public:
        cPlayer();
        void setScore(int);
        int getScore();

    protected:

    private:
        int score;
};

#endif // CPLAYER_H 

I guess I must have some fundamental misunderstanding of how the class stuff is supposed to work, but any enlightenment would be appreciated. Thanks!
Last edited on
closed account (SECMoG1T)
in you cpp file you forgot to qualify your functions with the class identifier
cPlayer::
Ohhh yeah. That's working now. Thanks very much! Appreciated.
Hello Cheddar99,

To start with line 9 of the ".cpp" file should look like line 4 cPlayer::setScore(int points) and the same for the function on line 13. These functions are part of the class. As you have written them they are regular function that do not have access to the "private" class variable.

In the future posting an error message like ... error: 'score' was not declared in this scope has no meaning because it does not mention the file it is in or the line number it is for. In this case it is easy to fine, but not all the time. In the future post the complete error message that the compiler put out.

But I don't understand why, when score is already declared in the header file.
"scope may be defined in the class, but you need class member functions to access the "private" variables. In the class the forward declaration ,(or prototype), void setScore(int); does not mean that you can write the function as you have. A ".cpp" file like your "cPlayer.cpp" is where you put the member functions of the class and all member functions should look like your ctor with what follows the "::" being the function name.

A quick note: a regular variable should start with a lower case letter. A variable defined as a constant would be in all capital letters. And a class or a struct should start with a capital letter. Not sure if this is a written rule, but it is the generally accepted way of naming.

I believe that when you add cPlayer:: to the beginning of "setScore" and "getScore" it should clear up the problem.

Hope that helps,

Andy
Thank you too, Andy.
Topic archived. No new replies allowed.