Principle of least privilege and the const keyword

1.9k Views Asked by At

Classes are about inheritance and composition. Is using the const keyword related to the principle of least privilege?

I understand inheritance and composition and I understand them but what about principle of least privilege? Can anyone explain it to me and how to remedy my code to contains principle of least privilege?

class A {
  int i;
public:
  A(int ii) : i(ii) {}
  ~A() {}
  void f() const {}
};

class B {
  int i;
public:
  B(int ii) : i(ii) {}
  ~B() {}
  void f() const {}
};

class C : public B {
  A a;
public:
  C(int ii) : B(ii), a(ii) {}
  ~C() {} // Calls ~A() and ~B()
  void f() const {  // Redefinition
    a.f();
    B::f();
  }
};

int main() {
  C c(47);
} ///:~
1

There are 1 best solutions below

4
On

1st of all you need to know that the best practice is to explicitly declare destructors virtual in order to guarantee that destructors are called recrusively inside a class inheritance tree. For this particular instance things will work, but if you will delete the class through a base pointer you will end up with destructors not being called (for example B* ptr = new C(47); delete ptr; you will end up with C's destructor not being called).

Regarding the least privilege principle , the const keyword states to the compiler that no change of the class members will be done during the execution of the f() function.

In other words, inside f() , the implicit this parameter will be constant. You will not be able to change a or B::i .

Const identifiers are very helpful for compilers in order to make read-only optimizations over the code.

If you want to link your code to the least privilege principle you can state it as following

"Whenever you will override this function, you will only have read privilege inside the class".