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
> 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.


The mergeFiles() defined above is not a member of LargeFile ; it is a free function at glogal scope.

To define the member, LargeFile::mergeFiles() outside the class, use the scope resolution operator and specify that a member functio n is being defined.

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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.