-1

Hi I'm new to c++ and I would like to know why the following code is not working as expected:

#include <iostream>

using namespace std;

class Person
{
public:
    int age;

    Person(){
       int age = 20; 
    }
};

int main()
{
   Person p;
   cout << p.age << endl;
}

I'm expecting to cout 20, but the program returns 0. I thought that the constructor would change age to 20 after the object is created. I tried searching for answers but the search results don't seem to answer my question.

Marc0_H
  • 29
  • 3
  • `age` in the constructor is a local variable to that function, and not the class member. just use `age = 20`. – tromgy Nov 22 '21 at 17:22
  • Omit the `int`8n th constructor body. – πάντα ῥεῖ Nov 22 '21 at 17:22
  • Voted to re-open. This question _may_ be a duplicate (e.g., of https://stackoverflow.com/q/64432081/801894), but it most definitely _is_ reproducible, and it was not caused by a typo. The OP did not understand [_shadowing_](https://en.wikipedia.org/wiki/Variable_shadowing). – Solomon Slow Nov 22 '21 at 22:15

2 Answers2

2

You are creating a local variable age with value 20 and doing nothing else with it. Your constructor needs to look like this:

Person() : age{20} {}

Then it will actually initialize the instance field as expected.

(Otherwise age = 20; in the constructor body (without the int declaration that hides the field name) would have worked as well. But in general it is good practice to always initialize fields in an initializer list rather than in the constructor body. (The most obvious benefit being that the fields can be const, but there are also other benefits, such as a well-defined and enforced and easy-to-read order of initialization.))

(Also, using namespace std; is an antipattern; please don’t do that.)

Andrej Podzimek
  • 2,409
  • 9
  • 12
1
#include <iostream>

using namespace std;

class Person
{
public:
    int age;

    Person(){
      // int age = 20; // the mistake was here
       age = 20; // that's correct
    }
};

int main()
{
   Person p;
   cout << p.age << endl;
}