1

I found the following thing :-

Public mode in inheritance: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. Private members of the base class will never get inherited in sub class.

But on running the following program the derived class is accessing the private data members of the base class, HOW AND WHY

The program is as follows :-

#include<iostream>
using namespace std ;

class Student
{
  private  :  long int sapId ;
              char name[20] ;

  public   : void getStudent()
             {
               cout << "Enter The Sap Id :- " ;
               cin >> sapId ;
               cout << "Enter The Name of The Student :- " ;
               cin >> name ;
             }

             void putStudent()
             {
               cout << "SAP ID :- " << sapId << endl ;
               cout << "Name :- " << name << endl ;
             }
} ;

class CSE : public Student
{
  protected : char section ;
              int rollNo ;

  public    : void getCSE()
              {
                cout << "Enter Section :- " ;
                cin >> section ;
                cout << "Enter Roll Number :- " ;
                cin >> rollNo ;
              }

              void putCSE()
              {
                cout << "Section :- " << section << endl ;
                cout << "Roll Number :- " << rollNo << endl ;
              }
} ;

main()
{
  CSE obj ;
  obj.getStudent() ;
  obj.getCSE() ;
  cout << endl ;
  obj.putStudent() ;
  obj.putCSE() ;
  return 0 ;
}
slothfulwave612
  • 1,349
  • 9
  • 22
  • No, it is not accessing private members of a base class. All the base class member functions it's accessing are inside a public scope. – Ron Mar 24 '18 at 19:39
  • *"Private members of the base class will never get inherited in sub class."* Not true. They are inherited, but invisible from the derived class. – HolyBlackCat Mar 24 '18 at 19:39

1 Answers1

2

I found the following thing :-

Public mode in inheritance: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. Private members of the base class will never get inherited in sub class.

The thing is wrong. It's as simple as that.

Private members get inherited just like everything else, as you've discovered.

Put down the quoted book and choose another.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055