#include <iostream>
using namespace std;
class Employee
{
/*These are attributes of a Employee class*/
public:
string Name;
string Company;
int Age;
/*This is a method of class*/
void IntroduceYourself()
{
cout<<"Name - "<< Name << endl;
cout<<"Company - "<< Company << endl;
cout<<"Age - "<< Age << endl;
}
/*This is user-defined constructor of class*/
Employee (string name, string company, int age)
{
Name = name;
Company = company;
Age = age;
}
};
int main ()
{
/*Creating 1st instance of Employee class*/
Employee employee1 = ("Danish", "Amazon" , 22);
employee1.IntroduceYourself();
/*Creating 2nd instance of Employee class*/
Employee employee2 = ("Aqib", "Accountancy" , 23);
employee2.IntroduceYourself();
}
Asked
Active
Viewed 452 times
0

Stack Danny
- 7,754
- 2
- 26
- 55
1 Answers
0
The problem is that when writing ("Danish", "Amazon" , 22)
you're using the built in comma operator whcih will evaluate the fist two operands and then discard them and the final result of the expression ("Danish", "Amazon" , 22)
will be an int
prvalue. But since there is no converting constructor in your class that takes an int
, that final resulting int
cannot be used to create employee1
. Similarly, for employee2
also.
The correct way to create the instances would be as shown below:
int main ()
{
//-----------------------v-----------------------v---->use braces instead of parenthesis
Employee employee1 = {"Danish", "Amazon" , 22};
employee1.IntroduceYourself();
//-----------------------v--------------------------v---->use braces instead of parenthesis
Employee employee2 = {"Aqib", "Accountancy" , 23};
employee2.IntroduceYourself();
}
Method 2
Use direct initialization.
int main ()
{
//use direct initialization syntax
Employee employee1("Danish", "Amazon" , 22);
employee1.IntroduceYourself();
//use direct initialization
Employee employee2("Aqib", "Accountancy" , 23);
employee2.IntroduceYourself();
}

Jason
- 36,170
- 5
- 26
- 60