I’m a CS student and right now we’re learning about inheritance. For our assignments, the teacher gives us a main.cpp file and a class header. We’re expected to create a .cpp implementation of the header without altering the given files. I’ve done most of it, but here’s what I can’t implement:
// File: employee.h
class Employee : public Person
{
private:
static Company company;
public:
static Company GetCompany();
static void SetCompany(const Company& company);
}
It’s the [static void SetCompany] that I’m unable to work with. Normally in the implementation I’d just do
// File: employee.cpp
void Employee::SetCompany(const Company& company) { this->company = company; }
but I get the error “‘this’ may only be used inside a nonstatic member function”. I’m not really sure how else I’m supposed to assign the variable, and it was never addressed in class. Any help would be appreciated. Just note that this is pretty much the format I’m expected to keep, so hopefully any advice won’t stray too much. Anyway, thanks in advance and let me know if anything needs to be clarified… or if I’m just being blind and/or stupid about this.
To access a static field, use
Employee::company, as you cant usethisbecause it is meant to refer to an instance of a class.Your setter will become
But if you try to simply replace your setter, your compiler will throw an error, saying that it doesn’t know
Employee::company. Because it is not instantiate. You need, in your .cpp file, as you would do with a function to declare your field with