Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and Set Methods in C++ OOP

In my computer science class I have an enum value in a header file and I'm having troubles with the get and set functions. I'm quite new to C++. This is part of my header file:

enum class SchoolType {
    Elementary = 1,
    Secondary = 2
};

class School : public Institution
{
    public:
        // There are a couple more values here

    SchoolType GetSchoolType();
    void SetSchoolType(SchoolType typeSchool);
};

And this is part of my .cpp file:

SchoolType GetTypeSchool()
{
    return this->_typeSchool;
}
void SetTypeSchool(SchoolType typeSchool)
{

}

But 'this' brings up an error and says that 'this' may only be used inside a nonstatic member function. How can I get that function to work? My computers teacher told me that that is how I should code the get function but I still don't understand, is there something that I'm doing wrong in the header?

like image 629
Lilia O. Avatar asked May 17 '26 20:05

Lilia O.


1 Answers

For the .cpp file, you should have:

SchoolType School::GetSchoolType() {
    return this->_typeSchool;
}
void School::SetSchoolType(SchoolType typeSchool) {
    // Insert code here...
}

Basically, in C++ you need to specify what class the function is part of (in this case, School) when defining the member functions, or else the compiler doesn't see it as being part of any class. You also need to keep your method names consistent (GetSchoolType vs GetTypeSchool).

like image 83
forkrul Avatar answered May 20 '26 10:05

forkrul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!