1

How is it possible to override a private pure virtual function from the base class in the private section of a derived class? Like this:

class Person 
{
private:
    virtual int age() = 0;
};

class Baby : public Person
{
public:
    void print_age() {
        int a = age();
        std::cout << a << std::endl;
    }
private:
    int age() override {
        return 5;
    }
};

int main()
{
    Baby b;
    b.print_age();
    return 0;
}

It doesn't seem to make a lot of sence but it compiles and runs fine. Would it be best practice to make the private age() function protected instead?

comp1201
  • 407
  • 3
  • 13
  • 1
    Since the child is not accessing the parent's `age` function, the access rules are not being violated. – ChrisMM Jan 20 '23 at 23:26
  • This pattern makes perfect sense and there is no reason why it shouldn't work. – n. m. could be an AI Jan 20 '23 at 23:30
  • 2
    Even more fun is inheritance doesn't give a crap about access. A `public` base method can be overridden with a `private` method in a derived class and the correct derived method will still be called by an outsider invoking the method on a base reference. – user4581301 Jan 20 '23 at 23:33
  • 1
    Overriding of functions has nothing to do with their access. It has to do with their signature (name, argument types, return type, exception specification). So a derived class can override any virtual function it inherits from a base class, by declaring a function with the same signature. Access is only relevant when *calling* the function - so a derived class cannot *call* a private member of the base class. – Peter Jan 21 '23 at 00:01
  • 1
    Does this answer your question? [What is the point of a private pure virtual function?](https://stackoverflow.com/questions/3970279/what-is-the-point-of-a-private-pure-virtual-function) *Or is that a different question? It was the top hit when searching for `[c++] private virtual function` so maybe you already saw it?* – JaMiT Jan 21 '23 at 04:30

0 Answers0