Name hiding in C++

What is name hiding in C++?

Solution:
Let us explain through an example. In C++, when you have a class with an overloaded method, and you then extend and override that method, you must override all of the overloaded methods.
For example:

class FirstClass {
public:
	virtual void MethodA (int);
	virtual void MethodA (int, int);
};

void FirstClass::MethodA (int i) {
	std::cout << "ONE!!\n";
}

void FirstClass::MethodA (int i, int j) {
	std::cout << "TWO!!\n";
}

This is a simple class with two methods (or one overloaded method). If you want to override the one-parameter version, you can do the following:

class SecondClass : public FirstClass {
public:
	void MethodA (int);
};

void SecondClass::MethodA (int i) {
	std::cout << "THREE!!\n";
}

int main () {
	SecondClass a;
	a.MethodA (1);
	a.MethodA (1, 1);
}

However, the second call won’t work, since the two-parameter MethodA is not visible:

error: no matching function for call to ‘SecondClass::MethodA(int, int)’
note: candidates are: virtual void SecondClass::MethodA(int)

That is name hiding.

Advertisements

1 Comment (+add yours?)

  1. Alex
    Oct 27, 2012 @ 23:37:51

    NIce post!

    This page on name hiding helped my understanding as well:

    http://www.programmerinterview.com/index.php/c-cplusplus/c-name-hiding/

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: