-1

I don't really know how to phrase it so here's an example

class Example() {
    public:
        Example() {
            int variable;
        }

        void Function() {
            // How do you modify variable from here?
        }
}
Vellu013
  • 17
  • 3
  • Take construction out of the question and you still can’t do that – Taekahn Jun 28 '22 at 15:24
  • 2
    You cannot. `variable` ceases to be once you return from `Example()`. Are you looking for member variables, perhaps? – Botje Jun 28 '22 at 15:24
  • You can refer to a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) for a better understanding of what is happening here. In particular, `variable` is local to the constructor and cannot be used once it goes out of scope. These things are explained in (m)any of the beginner level books linked above. – Jason Jun 28 '22 at 15:26

1 Answers1

3

variable is local to the constructor Example::Example. This means that it cannot be used after it goes out of scope at the closing brace } of the same ctor.

You can instead make variable to be a data member as shown below:

//-----------v------------->removed () from here
class Example {
    public:
//-----------------vvvvvvvv------->use member initializer list to initialize variable
        Example(): variable(0) {
            
        }

        void Function() {
           //use variable as you want
           variable++;   
        }
    private:
        int variable; // variable is a data member now
};

Demo

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Note: In modern C++ `int vairable{0};` would be preferable and then you don't even need a constructor and had default and aggregate initialization. – Goswin von Brederlow Jun 28 '22 at 16:13
  • @GoswinvonBrederlow Yes, i prefer in-class initializers over initializing things in member initializer list but in this example i was trying to show something different so i didn't bother using them. In particular, i was focussing on showing OP basic usage of data member. Ofcourse using in-class initilazer and mem initializer list are equivalent. – Jason Jun 28 '22 at 16:28