Search code examples
c++derived-classvirtual-functions

C++ derivative class with virtual function


I have a problem with some task. I need to write an derived class in which I need to be sure, that vector FVect cointains only characters <'a'; 'z'>.

class Something {
private:
   char FVect[3];

protected:
   virtual void setValue(int _idx, char _val) { FVect[_idx] = _val; }

public:
   Something() {};
};

I don't know exactly how to write a method in derived class (without making changes in class Something) since FVect is private.

Thanks for help.


Solution

  • With your current setup, the only thing you can do is implement setValue() in the class derived from Something and raise an exception if _val is outside the valid values, otherwise calling the base class method if it is valid:

    class Derived : public Something {
        ...
        void setValue(int _idx, char _val) {
            if ((_val < 'a') || (_val > 'z')) throw std::invalid_argument( "invalid character" );
            Something::setValue(_idx, _val);
        }
        ...
    };