Usage of 'std::' and questions about objects/classes

What is the purpose of std:: ?
I read that it accesses libraries and it can use classes/objects from there?
I’m confused on the object/class usage and ‘std::’.

For example:

  • std::cout << “Hello!”;

  • std::vector data_points = {3,2,31,34,445}

Lastly, does #include mean that it loads or preloads a library?

std is a namespace in C++. What this essentially means is that it’s like a library of functions and operators that can be used. Therefore when you use std:: it’s giving you access to whatever functions/operators/data_types are available within that namespace, some of which include cout cin and string. If you go off-site with a C++ project, say by using VS Code and install a C++ Intellisense extension you will see this more clearly.
Screenshot of VS Code with the autocorrect options for std:: showing.
If we look at this, we can see that upon typing std:: Intellisense brought up a list of everything available within that namespace. This gives us an idea of the amount of things available in the std namespace and how useful it is. std:: is essentially just a namespace reference, it’s telling the compiler “I would like to use a function within the std namespace”, thus telling it where to look and avoiding conflicts.
This can be demonstrated by leading the script with using namespace std and seeing how we can drop that part from every function call. However this is considered bad practise as it isn’t good to load in more functions that you need, since that’s how you get memory issues and conflict errors.

// An example of how using namespace std can work #include <iostream> using namespace std; int main() { string name; cout << "Please enter your name: \n"; name = "Adam"; cout << "Hello " << name << "\n"; return 0; }

On your last point, C++ comes pre-installed with a bunch of code packages as part of the install. Therefore using #include essentially just tells the compiler to load in these code packages to allow your code to function. That’s why it’s important to only include exactly as many packages as you require. Otherwise your compile will take longer as it has to load in all these extra packages, for which you don’t even use in your project.
Much of this is related to C++ being a compiled language, as you need to go through that extra step of using g++ or whatever other compiler you wish to use before a program can be run. Using things like #include and std:: are essentially leaving messages to the compiler saying “hey, you’ll find this function here” or “this code uses a function from time.h so please include it”.

Hopefully that adds a bit more clarity for you, if not I can try clear anything up!


Thank you Adam!

I appreciate the information.

1 Like