Saturday, February 18, 2012

Hide members on inheritance in C++

I was working on my personal Win32 classes, when I came across something I was willing to do. Suppose I have the following class:
class Base {
protected:
	int someValue;
	void doSomething();
public:
	void thePublicMethod();
	void anotherPublicMethod();
};
Since someValue and doSomething() are protected, they are visible and can be used by any subsequent derived class. Then, let’s have a derived class:
class Derived : public Base {
	void newStuff() {
		someValue = 42;
		doSometing();
	}
};
The public methods are still public. Now see that I used someValue and doSomething() inside newStuff() method, which is private. And now I don’t want subsequent derived classes to have access to someValue and doSometing(). I want to hide them from subsequent derived classes.

At first, I thought it wouldn’t be possible without redefining and overriding, which would add bloat here. But then I came across a trick I didn’t know, which allows you to hide both methods and variables without redefining or overriding them:
class Derived : public Base {
	Base::someValue;
	Base::doSomething; // now they are protected: hidden!

	void newStuff() {
		doSometing();
		someValue = 42;
	}
};
This trick changes the access modifier of methods and member variables without touching them, with zero overhead or additional bloat. Yes, C++ is a damn complex language.

No comments: