Tuesday, November 12, 2013

Access to Base Class in C++

When a base class is inherited as private, all public and protected members of that class become private members of the derived class. However, in certain circumstances, you may want to restore one or more inherited members to their original access specification.

For example, you might want to grant certain public members of the base class public status in the derived class even though the base class is inherited as private. An access declaration takes this general form:

base-class::member;

The access declaration is put under the appropriate access heading in the derived class declaration. Notice that no type declaration is required (or, indeed, allowed) in an access declaration. To see how an access declaration works, let's begin with this short fragment:

class base {
public:
int j; // public in base
};
// Inherit base as private.
class derived: private base {
public:
// here is access declaration
base::j; // make j public again
..
};


The following program illustrates the access declaration; notice how it uses access
declarations to restore j, seti(), and geti() to public status.
#include <iostream>
using namespace std;
class base {
int i; // private to base
public:
int j, k;
void seti(int x) { i = x; }
int geti() { return i; }
};
// Inherit base as private.

class derived: private base {
public:
base::j; // make j public again - but not k
base::seti; // make seti() public
base::geti; // make geti() public
// base::i; // illegal, you cannot elevate access
int a; // public
};
int main()
{
derived ob;
//ob.i = 10; // illegal because i is private in derived
ob.j = 20; // legal because j is made public in derived
//ob.k = 30; // illegal because k is private in derived
ob.a = 40; // legal because a is public in derived
ob.seti(10);
cout << ob.geti() << " " << ob.j << " " << ob.a;
return 0;
}

No comments:

Post a Comment