In c++ public inheritance, private members can only be accessed through the base class interface. If I cast a derived class into a base class, can I access its base class private members

  c++, question

图片描述And my code is wrong, why?

///////////////// .h
 #ifndef HI_H_INCLUDED
 #define HI_H_INCLUDED
 #include <iostream>
 using namespace std;
 class Worker
 {
 string name;
 
 public:
 Worker(string na):name(na){}
 private:
 void data()
 {
 cout<<"worker"<<endl;
 }
 
 };
 class Waiter:virtual public Worker
 {
 
 public:
 Waiter(string na1):Worker(na1){}
 
 
 void show()
 {
 ((Worker &)*this).data();  ///are forced to be converted to the base class, why can't we call the private function data ()
 data();
 }
 private:
 void data()
 {
 cout<<"waiter"<<endl;
 }
 };
 
 
 #endif // HI_H_INCLUDED
 
 ////////////  .cpp
 #include <iostream>
 #include "hi.h"
 #include<stdlib.h>
 
 using namespace std;
 
 
 int main()
 {
 Worker a("lin");
 Waiter b("liu");
 
 b.show();
 system("pause");
 }

This is certainly not the case.

The purpose of declaring a member private is not to allow you to use it in subclasses, if it can be used after mandatory type conversion like the topic owner.privateWhy does this access specifier leave onlypublicAndprotectedNo, that’s good.

If you want to overload the function of the parent class, you can modify two lines:

class Worker
 {
 string name;
 
 public:
 Worker(string na):name(na){}
 //private:
 protected:  // <-- 1
 void data()
 {
 cout<<"worker"<<endl;
 }
 
 };
 class Waiter:virtual public Worker
 {
 
 public:
 Waiter(string na1):Worker(na1){}
 
 
 void show()
 {
 //((Worker &)*this).data();  ///are forced to be converted to the base class, why can't we call the private function data ()
 Worker::data();  //<-2 calls the method of the same name of the parent class
 data();  //<-3 subclass methods are called here
 }
 private:
 void data()
 {
 cout<<"waiter"<<endl;
 }
 };