Home > Back-end >  any reason not to use 'protected' in this situation (cpp, c , oop)
any reason not to use 'protected' in this situation (cpp, c , oop)

Time:12-28

#include <iostream>

using namespace std;

class R {
protected:
    int a;
public:
    int read(void) {
        return a;
    }
};

class RW : public R {
public:
    void write(int _a) {
        a = _a;
    }
};

int main(void) {
    int a;
    R *r = (R *)&a;
    RW *rw = (RW *)&a;

    rw->write(1);
    cout << dec << r->read() << endl;
    cout << dec << rw->read() << endl;

    return 0;
}

I want to make a class that can only read (class R) and a class can read and write (class RW). Is there any reason I should not do this in oop? and also any reason not to use the 'protected' here? Please help me, thanks for any replies!

P.S. I don't want to define duplicated 'private int a;' on both classes, because the offset of 'int a in class RW' and size of 'class RW' is not the same to the 'class R' anymore.

CodePudding user response:

any reason not to use the 'protected' here?

protected member variables are sometimes discouraged in favor of protected member functions that accesses private member variables - and you don't need duplicate as if you make it private in R. You could add a protected member function to write to it instead.

class R {
public:
    int read() const { // not `void` and add `const`
        return a;
    }

protected:
    void write(int A) {
        a = A;
    }

private:
    int a;
};

class RW : public R {
public:
    void write(int A) {
        R::write(A);
    }
};

Without any added validation in R::write, the above basically does the same as your code, but a is private.

Your original version is not wrong though. As can be seen here: Should you ever use protected member variables? there's no definite "no, you should never use protected member variables".

One may argue that if they are only protected, one can just inherit the class and treat them as public and if changing such member variables doesn't require any validation of any sort, they could be made public to start with. One would have to look at it from case to case.

  • Related