Reputation: 660
I don't really understand when I need the using
keyword. Do you always need it when you want to use a function or object from the base class? I find I have to use it even when I'm not overloading the function.
Upvotes: 1
Views: 91
Reputation: 1
You have to use it if you deal with namespaces. For example:
using namespace std;
using std::cout;
using std::endl;
// without that you have to type it in following way
std::cout << std::endl;
// which is not the best way if you use it very often,
// but good if you want to use some names in your code
That allows you to use some libraries which have namespaces. It has been created for incapsulation (hiding) variables, classes and methods, otherwise it would take more namespaces and forbid you to use some names in your project.
Upvotes: 0
Reputation: 153840
You only need a using
-directive for base class members when you are overloading the corresponding name in a derived class and you want to make the base class overloads visible. When you don't overload the name in the detived class you don't need a using
-directive at all.
The background is that it was considered surprising if a change to a base class would hijack a function overload. Thus, overloads from base classes are hidden by default. If you want them to be used, you are doing an explucit change.
Let's assume that rule were not in place and Consider the derived class defining a member f(double)
which is called as object.f(0)
. If the base class is changed to provide f(int)
and overloads are visible the new function would be a better match. That is, without being visible before the behavior would silently be changed. That is probably a bad idea.
Upvotes: 2
Reputation: 308216
There are only two cases where you need to use using
in a class. First is when you are defining a function in the class with the same name as one in the base class, and you want to use overloading with both of them considered. The other is when you want to use the base class constructor as the derived constructor.
Upvotes: 2