How to properly override base class function in C++?

91 Views Asked by At

I have the following two structures, child inherits from base:

struct Base{
    double S1(int x){
        return x*x;
    }
    double S2(int x){
        return 2*x;
    }
    double S(int x){
        return S1(x) + S2(x);
    }
};


struct Child: Base{
    double S1(int x){
        return 0.0;
    }
    double S2(int x){
        return 0.0;
    }
};

S(int x) uses S1(int x) and S2(int x) to produce its result. I want to override S1 and S2 in the child, which seems to work. The following outputs:

Child child;
Base base;
std::cout<<child.S(2.0)<<std::endl;  //<-- 8   not OK, still base S
std::cout<<child.S1(2.0)<<std::endl; //<-- 0   OK, child S1
std::cout<<base.S1(2.0)<<std::endl;  //<-- 4   OK, base S1
std::cout<<base.S(2.0)<<std::endl;   //<-- 8   OK, base S

8 0 4 8 which shows that S1 was indeed overriden. However, child.S appears to call the base structure's S which, in turn uses the base's functions S1 and S2. How can I make the child's S (which is not explicitly defined here as it is inherited) use the overriden S1 and S2?

1

There are 1 best solutions below

6
navaneeth mohan On BEST ANSWER

Just make S1 and S2 virtual

struct Base{
    virtual double S1(int x){
        return x*x;
    }
    virtual double S2(int x){
        return 2*x;
    }
    double S(int x){
        return S1(x) + S2(x);
    }
};


struct Child: Base{
    double S1(int x){
        return 0.0;
    }
    double S2(int x){
        return 0.0;
    }
};