Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 14, 2021 02:47 am GMT

Quick Introduction to using in C

If you've ever written a c++ code snippet, I predict that you've seen this particular line :

using namespace std;

and thought to yourself, 'what does using mean?'

using is a keyword in C++ which is applicable in the following cases:

Bring all members from the namespace into the current scope.

The using directive allows all the names in a namespace to be used without the namespace-name as an explicit qualifier.

using namespace std; // brings all namespace names in the current scopestring my_string;// std::string can now be referred as string throughout the scopeORstd::string my_string; // string is now recognized, // however, will have to be addressed as std::string // wherever required

So now you know what using does in :

using namespace std

It brings namespace std in scope which makes it handy to use names in std without the explicit prefix std::

If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is, therefore, a good practice to not bring complete namespaces in scope in long code files to avoid such cases where an intuitive identifier name has to be dropped because same name exists in the namespace brought in scope by using. A workaround is to bring a specific name from a namespace in scope as:

using std::string;

Bring a base class method or variable into the current class scope.

class BaseClass {   public:      void sayHi() {         cout << "Hi there, I am Base" << endl;;      }};class DerivedClass : BaseClass {   public:      using Base::greet;       void sayHi(string s) {         cout << "Hi, " << s << endl;         // Instead of recursing, the greet() method         // of the base class is called.         sayHi();      }};

Create type aliases

template <typename T>using MyName = MyVector<T, MyAlloc<T> >; MyName<int> p; // sample usage
using flags = std::ios_base::fmtflags;// identical to // typedef std::ios_base::fmtflags flags;

typedef already exists in the C++ language which makes one wonder, why using was introduced to create type aliases. This is a valid question and an interesting one. There are a few interesting facts associated with typedef and using type aliases declarations which I will cover in my next post, stay tuned .

There are more caveats to using but are not covered here because this is a quick introduction, and also because of how rarely they are encountered. I encourage you to read more about using here.

Thanks for giving this article a read and I'll see you in the next one


Original Link: https://dev.to/guptaaastha/quick-introduction-to-using-in-c-4n73

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To