What is the 'using' keyword in C++?

​The using keyword is used to:

  1. Bring a specific member from the namespace into the current scope.
  2. Bring all members from the namespace into​ the current scope.
  3. Bring a base class method ​or variable into the current class’s scope.
svg viewer

Examples

1. Bringing string and cout in the current scope

#include <iostream>
int main() {
using std::string;
using std::cout;
string s = "Hello World";
cout << s;
return 0;
}

2. Bringing the entire std namespace in the current scope

#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
return 0;
}

3(a). Bringing greet() in the scope of the Derived class

#include <iostream>
using namespace std;
class Base {
public:
void greet() {
cout << "Hello from Base" << endl;;
}
};
class Derived : Base {
public:
using Base::greet;
void greet(string s) {
cout << "Hello from " << s << endl;
// Instead of recursing, the greet() method
// of the base class is called.
greet();
}
};
int main() {
Derived D;
D.greet("Derived");
return 0;
}

3(b). Bringing sum() in the scope of the Derived class

#include <iostream>
using namespace std;
class Base {
public:
void sum(int a, int b) {
cout << "Sum: " << a + b << endl;;
}
};
class Derived : protected Base {
public:
using Base::sum;
};
int main() {
Derived D;
// Due to protected inheritance, all the public methods
// of the base class become protected methods of the
// derived class. If the using keyword word was not used,
// calling sum like this would not have been possible.
D.sum(10, 20);
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved