Inheritance privacy

Hey everybody I want to ask a question about inheritance .

From the child classes could I access a protected data member in the parent class without using a member function or even friend function ?
if so , please Tell me How?.

Thanks.
only write the identifier of that variable and do whatever what you want with it, like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<conio.h>
using namespace std;

class Parrent{
      protected:
                int aaa;
};

class Child : public Parrent{
      public:
             Child(int Naaa){
                     aaa=Naaa;
                     cout<<aaa;
                     }
};

int main(){
    Child object(50);
    getch();
}

Look I want to do something like that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<conio.h>
using namespace std;

class Parrent{
      protected:
                int aaa;
};

class Child : public Parrent{
      public:
             Child(Parrent x){
				 aaa=x.aaa; // here is the error 
                     cout<<aaa;
                     }

};


here is the error
c:\users\f.b.m\desktop\c++\try\try\ddd.cpp(13): error C2248: 'Parrent::aaa' : cannot access protected member declared in class 'Parrent'
1>          c:\users\f.b.m\desktop\c++\try\try\ddd.cpp(7) : see declaration of 'Parrent::aaa'
1>          c:\users\f.b.m\desktop\c++\try\try\ddd.cpp(5) : see declaration of 'Parrent'
Yes. Public inheritance means that I can access protected members in my own base class.

In your code, you are trying to access a protected member of someone else's base class (namely, x's).

Or if you want to access a protected member in someone else's, of the same type as the base class..

There's something called friends, they let you have access to candy, slobber on candy (change), even though it does not belong to you. It belongs to a mother, not yours.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Parent{
   protected:
   friend class Child;  //I like friends :)
   int aaa;
};

class Child : public Parent{
      public:
   Child(Parent x){
      aaa = x.aaa;
      cout << aaa << " I have friends";
   }
};
Last edited on

For Turbine Thanks for you replies, but you didn't read my topic very will .

Thanks for you too jsmith.
Topic archived. No new replies allowed.