Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ class does not output correct data?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. 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;
    }
    
  2. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading