Search code examples
c++staticmethod-resolution-order

Using a static member from a derived class instead of the base class


As above, I'm trying to create a static variable name called increment_rate that has a default value of 1.05 for all Employee class.

However, the Developer class (derived from Employee class) enjoys a default increment_rate of 1.10 instead (yay to programmers).

In the Employee class, I have a public method called apply_incr(). Whenever I call it, standard Employees (such as the base class Employee, or other sub-classes such as Clerk or Janitor) only enjoys a standard increment_rate of 1.05, while sub-class Developer should automatically enjoy 1.10.

In python, the method resolution order will automatically choose the derived-class's increment_rate by default IF both the base class and the derived class has the variable increment_rate. However in C++, how would I implement such a similar functionality such that it will automatically apply 1.10 for developers, while everyone else only get 1.05?

Because all Clerk or all Janitor or all Employee has the same rate of 1.05, that's why I chose to use a static member that is used class wide, instead of a normal member that is unique to each instances of the class.

Thanks!


Solution

  • I'm not sure why there is a need for a static variable.. Assuming the apply_incr() is not static, you could very well have it like this:

    class Employee {
    
    public:
        virtual double getIncrementRate() const { return 1.05; }
    }
    
    class Developer : Employee {
    
    public:
        virtual double getIncrementRate() const override { return 1.10; }
    }