0

I'm trying to make a simple person class with a name, location, sex, and age with a constructor and a method for printing the info out. I'm getting the following warning:

Warning C26495 Variable 'person::age' is uninitialized. Always initialize a member variable (type.6

It looks like I have it initialized. Also, when I run the code nothing prints because nothing is saved in my object. Here is the code:

#include<iostream>
using namespace std;

class person {//class (public: makes it usable within program)
public:
    string name;
    string location;
    string sex;
    int age;

    person(string name, string location, string sex, int age) {//constructor
        name = name;
        location = location;
        sex = sex;
        age = 0;
    }
    void printinfo() {
        cout << "name: " << name << endl;
        cout << "location: " << location << endl;
        cout << "sex: " << sex << endl;
        cout << "age: " << age << endl;

    }
};

int main()
{
    person person1 ("James", "NYC", "Male", 0);
    person1.printinfo();

    system("pause>0");
}

1 Answer 1

3

Your function arguments shadow the class members. You will want to name them differently.

For example:

class person {
  public:
    string name_;
    string location_;
    string sex_;
    int age_;

    person(string name, string location, string sex, int age) {
        name_ = name;
        location_ = location;
        sex_ = sex;
        age_ = 0;
    }
};

Or, use this->name to refer to the class member variable.

Sign up to request clarification or add additional context in comments.

4 Comments

It would be better to use a constructor member initializer list. In your solution, string members will be first default-initialized and then assigned-to, which might require more work at the machine code level than a single initialization.
@DanielLangr: Sure. But that also is just more information to overload the asker with.
Or, instead of renaming the class members, prefixing them with "this->" should do the trick.
@Spray'n'Pray: Already have that in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.