0

I have this code snippet. I come from a Java background. I don't understand why the BubbleSort class sort method can access a private method in its base class and override it? This code snippet compiles and there is no error. in BubbleSort class, I am overriding the sortData method but the sortData method is private in the base class so practically Bubblesort class shouldn't be able to see it, let alone let me override the method.

#include <iostream>
class Sort{
public:
    virtual void processData() final {
        readData();
        sortData();
        writeData();
    }
private:
    virtual void readData(){}
    virtual void sortData()= 0;
    virtual void writeData(){}
};

class BubbleSort: public Sort{
private:
    void sortData() override {
        std::cout << "sortData" << std::endl;
    }
};
int main(){
    std::cout << std::endl;
    Sort* sort = new BubbleSort();
    sort->processData();
    std::cout << std::endl;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
navid
  • 27
  • 5
  • 1
    It's a bit counterintuitive, but `BubbleSort` can _override_ `sortData` without being able to, itself, _call_ `sortData`. This distinction is used for, for instance, in [the non-virtual interface idiom](https://isocpp.org/wiki/faq/strange-inheritance#private-virtuals) – Nathan Pierson May 15 '22 at 21:54
  • 1
    Your `Sort` class lacks a virtual destructor. If you were to actually attempt to rid yourself of the memory leak and did `delete sort;`, you would invoke undefined behavior due to the lack of a virtual destructor in `Sort`. Also, don't attempt to write or understand C++ code using Java as a model. – PaulMcKenzie May 15 '22 at 21:58
  • 1
    `private` doesn’t mean you can’t **see** it from outside. It means you can’t **call** it. Try it. The error message will be that it’s not accessible. In the code in the question the compiler sees the base version of the function and overrides it. – Pete Becker May 15 '22 at 22:04
  • 1
    As to why private virtuals are useful, what if the base class has a set of instructions it needs to perform the virtual functions in a specific order, A(), then B(), and then C(), and it **must** be done in that order. The derived classes implement A(), B(), and C(), but those derived classes cannot call them willy-nilly, only the base class has control over when they're called. Now the base class can call A(), B(), and then C() in that order. – PaulMcKenzie May 15 '22 at 22:05

0 Answers0