Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple levels of private and public inheritance - unusual access

#include<iostream>
using namespace std;
class uvw;
class abc{
   private:
      int privateMember;
   protected:
    int protMember;
   public:
    int publicMember;
};

class def : private abc{
    public:
       void dummy_fn();
};

class uvw: public def{

};

void def::dummy_fn()
{
   abc x;
   def y;
   uvw z;
   cout << z.protMember << endl; // This can be accessed and doesn't give a compile-error
}

From what I understand, after def inherits privately from abc, protMember and publicMember become private in def. So, now when uvw inherits from def, it shouldn't have any data members. But we can weirdly access z.protMember from dummy_fn() , where as z shouldn't have a variable protMember in the first place. Am I going wrong anywhere?

like image 460
Ankesh Anand Avatar asked Nov 08 '13 08:11

Ankesh Anand


1 Answers

If you were trying to access it from a free function, it wouldn't work. It does work in this case because dummy_fn() is a member function of def, so it has access to all the private things inside def. Since z is-a def, it has access to the private def members inside the z instance too.

Or at least that's my guess. It's a strange case.

like image 82
Tristan Brindle Avatar answered Nov 16 '22 02:11

Tristan Brindle