0

I know that C++ allows for the parameters of a constructor to have the same names as the class attributes, but my attributes only initialize when the parameters have different names.

Code:

#include <iostream>
using namespace std;

class Test{
    int age;
    string name;

    public:
        Test(string name, int age){
            name=name;
            age=age;
        }
        
        void introduce(){
            cout << "My name is " << name << ". I am " << age << " years old." << endl;
        }
};

int main(){
    Test bob("Bob", 53);
    bob.introduce();
}

Produces the output:

My name is . I am 6422476 years old.

But if I change the parameter names to some aliases like this:

Test(string nm, int ag){
    name=nm;
    age=ag;
}

Then the output is:

My name is Bob. I am 53 years old.

What went wrong here? Thanks for the help.

Alan N
  • 21
  • 6
  • 1
    Something else to chew on: What if I told you that `name=name;` isn't initialization, but instead an assignment? – user4581301 Aug 16 '21 at 21:41
  • This is a good example of why you should give members different names than parameters. One coding style is to prefix members with "m_". Another coding style is to append member names with"_". This coding style makes your code easier to read and reduces confusion between parameters and members. – Thomas Matthews Aug 16 '21 at 21:53
  • 1
    You could also use an initialization list: `Test(const std::string& name, int age) : name(name), age(age) { }` I still prefer using different names or employing a naming convention. – Thomas Matthews Aug 16 '21 at 21:55
  • @ThomasMatthews Still a bit confused as to why this doesn't work, considering everywhere else on SO says it's allowed. Regardless, I appreciate the feedback. Definitely a good practice to name them differently. – Alan N Aug 17 '21 at 04:00
  • @AlanN: There are a whole bunch of stuff that is allowed in the C++, but it doesn't mean that it makes a good, readable, program. For example: [The International Obfuscated C Code Contest](https://www.ioccc.org/) – Thomas Matthews Aug 17 '21 at 14:20

0 Answers0