a simple question

How does a derived class's member function get access to the protected data of the base class? I tried like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream.h>
#include <conio.h>
#include <vcl.h>
#pragma hdrstop
  class First{
  public:
  First (int b){a=b;}
 protected:
 int a;
  };

  class Second:public First
  {
  public:
  Second (int b):First(b)
  {}
  int getA(First f)
  {
    return f.a;
  }
  };
//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
   First f(5);
   Second s(5);
cout << s.getA(f);
getch();
        return 0;
}


and i failed. But tutorials say derived classes may access protected members of the base ones. Or maybe i've been confused? Explain it anyone please
But tutorials say derived classes may access protected members of the base ones.


To my knowledge that means that the Derived classes also have the members of the Base classes implicitly declared. It doesn't mean that an object of a Derived class can access the private or protected members of an object of its Base class. If you want that, look up friend functions and friend classes:

http://www.cplusplus.com/doc/tutorial/inheritance/

Edit: wrote a lie by mistake, corrected it.
Last edited on
closed account (DSLq5Di1)
1
2
3
4
int getA()
{
    return a; // First::a
}
Line 19 fails because you cannot access a protected member of another class. The paramter of the function is another type (not Second) so you cannot access it's protected or private members.

Internally you can access a.
Topic archived. No new replies allowed.