C++/scope

Advertisement


Question
Hi,

How are you? Thanks for taking questions. In my *.h file I have this class

class LargeFile {
int x;  
public:
void mergeFiles();
};

Why cannot I in my mergeFile() do this:

void mergeFiles()
{
x=5;
}

The compiler says that x was not defined in this scope. But why? The mergeFiles() is a member of class LargeFile, so why cannot I use its variables. Is it because I didn't specify the instance?

I'm actually trying to achieve this: define variables within a class so that all members of that class could directly and simply  use those variables. I don't want the class to do anything fancy. I don't want to give everything a global scope. How to do it properly? Thanks so much! Andres

Answer
That's probably because compiler is simply taking the function as an outside function which can be used in any class. If the function belongs to this particular class only, you need to define it within the class, not outside it. Things will get right by doing this:

class LargeFile {
int x;  
public:
void mergeFiles()
{
x=5;
}
};

And it does satisfy your requirement of defining functions which can use the variables defined in the class. Try this and tell me what happens. Hope I helped.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tehreem

Expertise

I can answer questions related to C++ coding and programming techniques.

Experience

I am a C++ programmer.

Organizations
University of Engineering & Technology Lahore

Publications
http://recurseit.blogspot.com

Education/Credentials
I am doing BSCS.

©2016 About.com. All rights reserved.