No compilation error but the output is this:
g++ class.cpp && ./a.out
is -1003073000 years old.
It does not output the string and int as it supposed to be.
I don’t know what is wrong, I would really appreciate if someone point out my mistake, thanks!.
Here is the code:
#include<iostream>
class Student{
private:
std::string name;
int age;
public:
Student(std::string name, int age){
name = name;
age = age;
}
void setName(std::string name){
name = name;
}
std::string getName(){
return name;
}
void setAge(int age){
age = age;
}
int getAge(){
return age;
}
};
int main(){
Student student1 = Student("Clayton",20);
std::cout<<student1.getName();<<" is "<< student1.getAge()<<" years old."<<std::endl;
}
>Solution :
In the constructor
Student(std::string name, int age){
name = name;
age = age;
}
The names name and age are the argument variables of those names. Which means you assign the variables to themselves.
You have two solutions:
-
Use
thisto explicitly reference the current object and use its member variables:Student(std::string name, int age){ this->name = name; this->age = age; } -
Or use a member initializer list to initialize (rather than assign to) the member variables:
Student(std::string name, int age) : name(name), age(age) { // Empty }For this the language knows the difference between the member and argument variables.
I highly recommend the second alternative.