Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,693 questions

57,001 answers

573 users

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 287 views
1 answer 282 views
1 answer 308 views
1 answer 247 views
1 answer 223 views
...