Search code examples
c++encapsulation

C++ protect getters/setters using final


Let's say I have a class that requires an encapsulated variable for conditional protection.

class person {

private:
    int height_;

public:
    explicit person(int height) {
        this->height_ = height;
    }

    int get_height() const noexcept {
        return height_;
    }

    void set_height(int height) {
        if (height < 0)
            throw std::invalid_argument("Height cannot be negative");
        this->height_ = height;
    }
};

I realize I can just make height an unsigned int but it's an example of many possible problems.

Should my set_height be marked as virtual ... final to protect it against derived overriding?
Or should I just assume that under normal circumstances that won't happen?

As a side note does this increase compile time or have some negative connotation?


Solution

  • Only virtual functions can be overriden by a subclass. As it is in your code a subclass wouldn't be able to override those functions anyways.

    If you needed them to be virtual for some reason then yes, the final keyword would prevent overriding.