Home arrow C++ Programming arrow Inheritance & Composition

Language Translator

Hacking Zone

Hacking Tools
Attacking

Configure Windows

Windows Configuration

Novels

Mix Novels

Human Personality

Body Language
Inheritance & Composition PDF Print E-mail
Written by Hemanshu Patel   
Wednesday, 24 October 2007
Article Index
Inheritance & Composition
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
Page 8

protected

Now that you’ve been introduced to inheritance, the keyword protected finally has meaning. In an ideal world, private members would always be hard-and-fast private, but in real projects there are times when you want to make something hidden from the world at large and yet allow access for members of derived classes. The protected keyword is a nod to pragmatism; it says, “This is private as far as the class user is concerned, but available to anyone who inherits from this class.”

The best approach is to leave the data members private – you should always preserve your right to change the underlying implementation. You can then allow controlled access to inheritors of your class through protected member functions:

//: C14:Protected.cpp
// The protected keyword
#include <fstream>
using namespace std;

class Base {
int i;
protected:
int read() const { return i; }
void set(int ii) { i = ii; }
public:
Base(int ii = 0) : i(ii) {}
int value(int m) const { return m*i; }
};

class Derived : public Base {
int j;
public:
Derived(int jj = 0) : j(jj) {}
void change(int x) { set(x); }
};

int main() {
Derived d;
d.change(10);
} ///:~

You will find examples of the need for protected in examples later in this book, and in Volume 2.

 

protected inheritance

When you’re inheriting, the base class defaults to private, which means that all of the public member functions are private to the user of the new class. Normally, you’ll make the inheritance public so the interface of the base class is also the interface of the derived class. However, you can also use the protected keyword during inheritance.

Protected derivation means “implemented-in-terms-of” to other classes but “is-a” for derived classes and friends. It’s something you don’t use very often, but it’s in the language for completeness.

   

Last Updated ( Wednesday, 24 October 2007 )
 
< Prev   Next >
Your Ad Here

Donate us!!

Enter Amount:

RSS socialnet

Add to MyYahoo!
Subscribe in NewsGator Online
Add to Newsburst
Add to Google
Add to My AOL
Add to Pluck
Subscribe in FeedLounge
Add to Windows Live
Add to NetVibes
Subscribe in Rojo
Subscribe in Bloglines
Add to MyMSN
Add to Plusmo for your cellphone
Add to PageFlakes
Add to Technorati
Add to BlinkBits