c++functionclassinheritancepolymorphism

Inherited Function Using Child Function


I was looking to have a base class and multiple child classes each with a separate implementations of one function used in many shared functions. This would be similar to this

class A {
    public:
    int a() {
        return 6;
    }
    int b() {
        return a() - 2;
    }
};

class B: public A {
    public:
    int a() {
        return 10;
    }
};

int main() {
    B x;
    std::cout << x.b() << std::endl;
}

How would I get x.b() to be 8 instead of 4?


Solution

  • You need to make your function virtual, so that a() always refers to the implementation of a() in the object's real class:

    class A {
        public:
        virtual int a() {         //<<<<<<<<--------
            return 6;
        }
        int b() {
            return a() - 2;
        }
        virtual ~A() = default;  
    };
    

    In you version with a non-virtual function, the body of b() calls the only a() it knows, which is the A::a().

    As a good practice, and to avoid nasty errors, when you define a virtual function indicate in the derived classes that you override the virtual function:

    class B: public A {
        public:
        int a() override {
            return 10;
        }
    };
    

    Another good practice is also to foresee a virtual destructor in the base class.