Search code examples
c++classvariablesconstructorscope

Using variables from a class's constructor in one of its member functions?


I'm learning C++ and I want to know if there is a way you can use variables defined in a class's constructor in a member function. I've tried looking online and in my textbook but I can't find a definitive answer. For example:

class Item {
public:
   Item(std::string str) {
      std::string text = str;
      int pos = -1;
   }
   void increment() {
      // how would I reference pos here?
      pos++;
   }
};

Thanks in advance!


Solution

  • I want to know if there is a way you can use variables defined in a class's constructor in a member function.

    No, you can't. Variables defined in the constructor goes out of scope at the end of the constructor.

    The normal way is to initialize member variables in the constructor. These can then be accessed in the member functions:

    class Item {
    public:
        Item(std::string str) : // colon starts the member initializer list
            text(std::move(str)),
            pos{-1} 
        {
            // empty constructor body
        }
    
        void increment() {
            pos++;         // now you can access `pos`
        }
    
    private:
        // member variables
        std::string text;
        int pos;
    };