-1

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.

Manishyadav
  • 1,361
  • 1
  • 8
  • 26
  • You are assigning vars to themselves `name = name; age=age;`. Try `this->name = name; this->age=age;` – 273K Sep 28 '22 at 05:41
  • Or try using a [member initializer list](https://stackoverflow.com/questions/47157938/explanation-of-c-class-constructor-syntax) instead of performing a default initialization followed by an assignment. – Nathan Pierson Sep 28 '22 at 05:44

1 Answers1

3
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;

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
  • 1
    I know it's obvious but the fourth option is to choose different names for the parameters. Might not occur to a newbie. – john Sep 28 '22 at 06:16