Access Specifiers + Inheritance

Jun 13, 2011 at 12:59pm
Hi.

Regarding inheritance: if you have a Base class A, and class B: public A

You inherit all members of class A, however you can only use the ones declared as public or protected? But you also inherit the private members? What is that for if you can't use them?

Thx,
xcrypt
Last edited on Jun 13, 2011 at 12:59pm
Jun 13, 2011 at 1:27pm
you can call functions declared in A on a B object, these functions may use private members of A.
Last edited on Jun 13, 2011 at 1:30pm
Jun 13, 2011 at 2:04pm
closed account (yUq2Nwbp)
if you could use private members, then in order to get access to private members of base class you only should write class that derives from your base class and the idea of member functions and friend functions would be mindless.....

also when you write class B:public A then you inherit interface of class A...interface of class A is its public part.......

i recommend you to read Stroustroup 3-rd edition book chapter 12....it is about inheritance of classes....
Last edited on Jun 13, 2011 at 2:07pm
Jun 14, 2011 at 3:02am
quirkyusername wrote:
you can call functions declared in A on a B object, these functions may use private members of A.
Example:
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>

namespace mySpace {
   class A {
      int a;

    public:
      A(int x = 0) : a(x) {}

      int getA() const { return a; }
   };

   class B : public A {
      int b;

    public:
      B(int x = 0, int y = 0) : A(x), b(y) {}

      int getB() const { return b; }
   };
}

using namespace std;
using namespace mySpace;

int main() {
   A a(3);
   B b(-1, 10);
   cout << a.getA() << " is " << sizeof(a) << " bytes\n"
        << b.getA() << ',' << b.getB() << " is " << sizeof(b) << " bytes\n";
   return 0;
}
3 is 4 bytes
-1,10 is 8 bytes
Topic archived. No new replies allowed.