How to use public inheritance with private and protected base class members in C++

1 Answer

0 votes
#include <iostream>
  
class Base {
   private:
    int pri_vate = 1;
  
   protected:
    int prote_cted = 2;
  
   public:
    int pub_lic = 3;
  
    int getPrivate() {
        return pri_vate;
    }
};
  
class PublicDerived : public Base {
   public:
    int getProtectedt() {
        return prote_cted; 
    }
    /*
    int getPrivate_PublicDerived() {
        return pri_vate; // error: ‘int Base::pri_vate’ is private within this context
    }*/
};
  
int main() {
    PublicDerived o;
      
    //std::cout << "Private = " << o.pri_vate << "\n"; // error: ‘int Base::pri_vate’ is private within this context   
    std::cout << "Private = " << o.getPrivate() << "\n";
    std::cout << "Protected = " << o.getProtectedt() << "\n";
    // std::cout << "Private = " << o.prote_cted << "\n"; //  error: ‘int Base::prote_cted’ is protected within this context
    std::cout << "Public = " << o.pub_lic << "\n";
      
    return 0;
}
  
  
  
/*
run:
  
Private = 1
Protected = 2
Public = 3
  
*/

 



answered Jan 14, 2021 by avibootz
edited Jan 14, 2021 by avibootz

Related questions

1 answer 194 views
1 answer 189 views
1 answer 208 views
1 answer 172 views
1 answer 141 views
...