Friday, July 17, 2009

[C++] Override inherited scope

Hi,

This particular possibility in C++ took me by surprise when I tried it out. Consider a (child) class inheriting another (parent) class in 'protected' scope. Ideally it seems that the parent's 'protected' methods should be accessible only by the child. An object of the child could not be used to access the parent's protected methods. Think again!

Consider this:
#include<iostream>
class parent
{
protected:
void method() {
std::cout<<"parent: I am a protected method"<<std::endl;
}
};

class child:protected parent
{
public:
parent::method;
};

int main(){
child cObj;
cObj.method();
return 0;
}

This compiles/runs perfectly on my g++ v4.1.2 on a Linux box. I had tried this earlier on SunOS CC and it worked just fine. Dev C++ 4.9.9.2 doesn't complain either.

I wonder if this is a feature overlooked by Stroustrup or am I missing something obvious?! - Comments most welcome :-)

Until we meet again,
- Srini -

No comments:

Post a Comment