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.