Reputation: 3
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;
}
Upvotes: 0
Views: 55
Reputation: 409166
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.
That will leave the Student::name
member default constructed and empty, but the Student::age
variable will be uninitialized, and have an indeterminate value, and using such values (even printing them) is undefined behavior.
You have two solutions:
Use this
to 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.
Upvotes: 3