Home > Mobile >  Classes not giving required output in c
Classes not giving required output in c

Time:09-28

I have created a class name Employee and inside that I have declared a function and two variable(name ,age) . After creating a variable x I am not getting the name insted getting empty name and age =0

CODE:

#include<iostream>
using namespace std;

class Employee{
public:
    string name;
    int age;
    void print(){
     cout<<"Name:"<<name<<endl;
     cout<<"Age:"<<age<<endl;
    }
    
    Employee(string name,int age){
        name = name;
        age=age;
    }
    

};
int main(){

    Employee x=Employee("chang",33);
    x.print();
     return 0;
}

Expected:
name:Chang
age :33

OutPut:
name:
age :0

Can Someone tell me what is the reason behind it.

CodePudding user response:

Employee(string name, int age) {
    name = name;
    age = age;
}

you are not modifying the class members, but the parameters instead.

You have three ways to solve this problem:

  • use this-> to precisely target the right variables.

    Employee(string name, int age) {
       this->name = name;
       this->age = age;
    }
    
  • use an initialisation list:

    Employee(string name, int age) : name(name), age(age) {
    
    }
    
  • don't use any constructor, but use brace initialization instead:

    int main() {
        Employee x = Employee{ "chang", 33 };
        x.print();
    }
    

I would personally use option three with the braces, as it's the most efficient to write.


read here why you shouldn't be using namespace std;

  • Related