Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
–
is incorrect. Within the body of the constructor you are assigning parameters to themselves. It is because the parameters hide data members with the same name within the body of the constructor.
At least you should write
Employee(string company, string name, int age) {
this->name = name;
this->company = company;
this->age = age;
But it would be even better to use a mem-initializer list like
Employee(const std::string &company, const std::string &name, int age)
: name( name ), company( company ), age( age )
And in main you may write
Employee emp1("bww","susmit",24);
instead of
Employee emp1 = Employee("bww","susmit",24);
As for the function Introduce
then it is better to declare and define it the following way
std::ostream & Introduce( std::ostream &os = std::cout ) const
os << "my age is- " << age << std::endl;
return os;
Also there is no great sense to declare these data members
string name;
string company;
int age=0;
as having a public access. You could declare them as having private access.
Also as your class does not have the default constructor then this member initialization within the class definition
int age=0;
is redundant.
Your constructor just assigns the arguments given to the constructor to themselves:
Employee(string company, string name, int age) {
// ^
// |
name = name; // -------------+ both left and right name refer to the argument
company = company;
age = age;
You could solve it by using a different name for the constructor arguments (or by being explicit using this->member = ...
) or by using the member initializer-list:
Employee(string company, string name, int age) : // colon starts the member init-list
name(name), // The first name refers to the member varible (this->name)
company(company), // and the second refers to the constructor argument
age(age) //
// constructor body can now be empty
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.