Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 virtualfinal to protect it against derived overriding?
Or should I just assume that under normal circumstances that won’t happen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading