Curriculum
Course: Learn C++ Programming
Login

Curriculum

Learn C++ Programming

Text lesson

Granting Access

[post-views]

 

In this lesson, you will learn,

  • Granting Access to Private Data
  • Example

 

Granting Access to Private Data

You know, when a base class is inherited as private, all public and protected members of that class become private members of the derived class.

 

For example, in some circumstances, 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 mode.

 

You can restore an inherited member’s access specification by employing an access declaration within the derived class.

 

An access declaration takes this general form:

 

base-class::member;

 

Notice that no type declaration is required (or, indeed, allowed) in an access declaration.

 

Example

 

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
};

 

 

Example: Access Declaration

 

//GrantingAccessEx2.cpp
#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:
    /* The next three statements override
    base's inheritance as private and restore j,
    seti(), and geti() to public access. */
    
    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;
}

 

Output

 

using-declarations; suggestion: add the 'using' keyword [-Wdeprecated]
     base::seti; // make seti() public
     ^~~~
GrantingAccessEx2.cpp:22:5: warning: access declarations are deprecated in favour of 
using-declarations; suggestion: add the 'using' keyword [-Wdeprecated]
     base::geti; // make geti() public
     ^~~~
10 20 40

 

Access declarations are currently supported by Standard C++, but they are deprecated.

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories