I've been doing some coursework for the programming module of my Physics degree but I've been having some trouble. I had to make a class called Person and a subclass of that called Employee such that: Person.hpp:
#ifndef PERSON_HPP_
#define PERSON_HPP_
class Person {
public:
Person(const std::string & name="Anonymous"): name(name) {;}
~Person() {;}
std::string getname(){
return name;
}
void setname(std::string newname) {
name = newname;
}
void Print();
private:
std::string name;
};
#endif /* PERSON_HPP_ */
Person.cpp:
void Person::Print(){
std::string name = Person::getname;
std::cout << name << std::endl;
}
Employee.hpp:
#ifndef EMPLOYEE_HPP_
#define EMPLOYEE_HPP_
class Employee: public Person {
public:
Employee(const std::string & name, const std::string & job) : name(name), job(job){;}
~Employee() {;}
std::string getjob(){
return job;
}
void setjob(std::string newjob) {
job = newjob;
}
void Print() const;
private:
std::string job;
};
#endif /* EMPLOYEE_HPP_ */
Employee.cpp:
void Employee::Print(){
Person::Print();
std::string job = Employee::getjob;
std::cout << job << std::endl;
}
main.cpp:
#include <iostream>
#include <string>
#include <vector>
#include "Person.hpp"
#include "Person.cpp"
#include "Employee.hpp"
#include "Employee.cpp"
#include "Friend.hpp"
#include "Friend.cpp"
int main() {
return 0;
}
The error is in my employee.cpp. When building this error shows: ../Employee.cpp:10:6: error: use of undeclared identifier 'Employee'
I realise that I have probably made a very basic mistake however it is frustrating for me that I cannot see it.
Any help would be great! Thanks in advance, Sean Cooper
N.B. The purpose of employee.cpp is to print the name of the employee along with its associated job.
Your include
's should look like this:
Person.cpp:
#include <iostream>
#include <string>
#include "Person.hpp"
Employee.cpp:
#include <iostream>
#include <string>
#include "Employee.hpp"
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Person.hpp"
#include "Employee.hpp"
#include "Friend.hpp"
That is, each .cpp
(implementation) includes the respective .hpp
(interface) along with additional headers needed (like <string>
). Your main.cpp
includes all needed headers but no other .cpp
file. The compiler will parse all .cpp
files individually and the linker will link the results into an executable. As a rule of thumb, never include a .cpp
anywhere.
The specific error is when the compiler sees
void Employee::Print()
and doesn't know what Employee
is. Including Employee.hpp
fixes this by bringing in Employee
's definition.