What does "::" mean in C++?

Asked

Viewed 5,408 times

7

I have doubts about the use of the two points ::, used to implement classes, [tipo] [classe]::[método]. It is also used, for example, in std::cout. What exactly would these two double points be and what they serve?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

8

This is the scope resolution operator. He gives context to what he is referring to, he disambiguates a possible situation where there may be confusion between two or more members. It is used in two situations.

  • To indicate that a member belongs to a particular namespace as in the example of std::cout. std is a namespace. It’s a different family of components, so to use members of a different family from the current one you can’t just use the member’s name, you have to use their last name too.

  • Specify to which class a member belongs. This is necessary when you will define the methods (not when you will declare). Without telling which class it belongs to the compiler there is no way to know what it is implementing and this is fundamental information.

It is also used to access members who belong globally to the class and not to the instance, i.e., to access static members.

Well, there is a way to not need the name fully qualified, but this is another matter.

So you’ve learned essentially everything you need to learn about him.

Simplified example:

namespace exemplo {
    public class classe {
        static int membro = 0;
        int metodo(); //declarou o método dentro da classe
    }
}
int classe::metodo() { //definiu o método já declarado que pertence a "classe"
    return 0;
}

auto x = new exemplo::classe(); //instanciando "classe" que faz parte do "exemplo"
std::cout << x.metodo(); //estou chamando pela instância
std::cout << exemplo::classe::membro; //estou chamando um membro da classe

I put in the Github for future reference.

Both will print 0.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.