1

Having some trouble understanding variable scope within a class structure.

I want to create a few variables in the class constructor and then have them available to the functions within that class. I thought that just defining them within the constructor would work, but my compiler (g++) gives me an error: 'foo' was not declared in this scope.

Can someone shed some light on this trivial problem?

Here is some dummy code to illustrate what I'm trying to do.

myClass.h
using namespace std;
class myClass{

public:
    myClass(){
        std::vector<int> foo;
        foo.resize(10,0);
    };

    void myFunc();
}

myClass.cpp
void myClass::myFunc(){
    std::cout << foo[1] << end;
    // etc...
}
JoeFish
  • 3,009
  • 1
  • 18
  • 23
Noah
  • 567
  • 8
  • 19
  • 7
    Time for a [good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)! – Kerrek SB Dec 19 '11 at 20:40

1 Answers1

5

Variables declared in a constructor go out of scope at the end of the constructor body. This is no different to other functions. If you want variables that are accessible to all member functions of a class, you should make them member variables.

You do this by declaring them in the class body. E.g.

class myClass {
public:
    myClass() {
        foo.resize(10,0);
    }

    void myFunc(); // now has access to foo

private:
    std::vector<int> foo;
};
CB Bailey
  • 755,051
  • 104
  • 632
  • 656