How to use a class with protected variable and protected function in C++

1 Answer

0 votes
#include <iostream>

class Base {
protected:
   int  x;
   void pfunction() { std::cout << "Access to pfunction() OK\n"; }
public:
   void setx( int i ) { x = i; }
   void Display() { std::cout << x << "\n"; }

} cb;

class Derived : public Base {
public:
   void f() { pfunction(); }
} dc;

int main() {
   // cb.x;         // error: ‘int Base::x’ is protected within this context
   cb.setx(298);  
   cb.Display();
   
   dc.setx(3);  
   dc.Display();
   
   // cb.pfunction(); //  error: ‘void Base::pfunction()’ is protected within this context
   dc.f();     
   
   return 0;
}


/*
run:

298
3
Access to pfunction() OK

*/

 



answered Jan 13, 2021 by avibootz

Related questions

1 answer 200 views
1 answer 189 views
1 answer 163 views
1 answer 254 views
...