The first .h file is named as "Employee.h"
#include<iostream>
class Employee
{
public:
int total=0;
std::string Name,Id,Address;
void dummy();
};
The first .cpp file is named as EMployee.cpp
#include "Employee.h"
void Employee::dummy()
{
std::cout<<"Rohith"<<std::endl;
}
And the main file is named as main.cpp
#include "Employee.h"
int main()
{
std::cout<<total<<std::endl;
Employee obj;
obj.dummy();
}
When executing the above cpp files i am getting an error like this
g++ Employee.cpp main.cpp
main.cpp: In function ‘int main()’:
main.cpp:5:13: error: ‘total’ was not declared in this scope
std::cout<<total<<std::endl;
^~~~~
main.cpp:5:13: note: suggested alternative: ‘strtol’
std::cout<<total<<std::endl;
^~~~~
strtol
Can you help me in this? how can i resolve the above problem.
>Solution :
According to Employee.h, you intend dummy to be a non-static method of class Employee.
In this case you should do the following changes:
- In Employee.cpp, change the definition of
dummyto:
void Employee::dummy()
{
std::cout<<"Rohith"<<std::endl;
}
Without qualifying the name dummy with Employee::, you are defining a new free function called dummy, rather than the method of Employee.
- When invoking the
dummymethod you need an object of classEmployee, e.g.:
Employee emp;
emp.dummy();