user2827286
user2827286

Reputation: 77

variable not declared in this scope

I'm making a program for class, and for some reason it is giving me this error when it is declared in the class definition.

error: in function 'void setMessageBuffer(std::string)'
error: 'message' was not declared in this scope.

class apple
{
     private:
         string message, message2;

     public:
         void setMessageBuffer(string);
};

void apple::setMessageBuffer(string messagebuff)
{
     message = messagebuff;
}

I've done other parts of the program like that and they work fine, but for some reason this part doesn't seem to want to compile.

Upvotes: 2

Views: 3919

Answers (3)

Aaron McDaid
Aaron McDaid

Reputation: 27133

You forgot to put apple:: in front of the method name. Your error message tells me this!

error: in function 'void setMessageBuffer(std::string)'
error: 'message' was not declared in this scope.

Contrast that with:

template.cpp: In member function ‘void apple::setMessageBuffer(std::string)’:
template.cpp:14:7: error: ‘another variable’ was not declared in this scope

(Apologies if I'm wrong here, maybe it's just how my compiler is behaving, g++-4.6)

Upvotes: 3

CS Pei
CS Pei

Reputation: 11047

I think there is something wrong in other parts of your code, for example, did you include string ? and using namespace std;?

The following code can be compiled by GCC without any problem

#include <string>
using namespace std;
class apple
{
    private:
        string message, message2;

    public:
        void setMessageBuffer(string);
};

void apple::setMessageBuffer(string messagebuff)
{
    message = messagebuff;
}

int main()
{
}

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The error message and the code don't agree: the code compiled to produce the error message lacked apple:: in front of setMessageBuffer(): without the function being a member function, it can't access apple's members. The code as posted compiles assuming it is preceded by the two lines

#include <string>
using namespace std;

(or, in my opinion preferable, without the second of these two lines and all uses of string being prefixed by std::).

Upvotes: 2

Related Questions