Private members

Private members are class members that are hidden from the outside world. The private members implement the OOP concept of data hiding. The private member of a class can be used only by the member functions of the class in which it is declared. Private members cannot be inherited by other classes.

Private members in inveritance

private class member and inveritance

Private inveritance example

#include <iostream>
using namespace std;

class person
{
private :
  char name[20];
  
public :
   char * GetName() {
     return name;
     }
}; 
class student : public person
{
public :
   char * GetName() {
     return name;
     }
};

int main (int argc, char *argv[])
{
  student s;
  s.GetName();
  return 0;
}

Private inveritance compilation

$g++ private.cpp
private.cpp:18:13: error: 'name' is a private member of 'person'
     return name;
            ^
private.cpp:7:8: note: declared private here
  char name[20];
       ^
1 error generated.

Protected members

Protected members are the members that can only be used by the member functions and friends of the class in which it is declared. The protected members cannot be accessed by non member functions. Protected members can be inherited by other classes.

Protected members in inveritance

protected class member and inveritance

Protected inveritance example

#include <iostream>
using namespace std;

class person
{
protected :
  char name[20];
  
public :
   char * GetName() {
     return name;
     }
}; 
class student : public person
{
public :
   char * GetName() {
     return name;
     }
};

int main (int argc, char *argv[])
{
  student s;
  s.GetName();
  return 0;
}

Protected inveritance compilation

$g++ protected.cpp
compiles successfully!!

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

#