zLeon
zLeon

Reputation: 137

What's the purpose of scope resolution operator when using ios_base in C++

the following example is from Bjarne's book - " Programming and principles using C++" , The example:

fstream fs;
fs.open("foo",ios_base::in);
fs.close();
fs.open("foo",ios_base::out);

I understand that I use scope resolution operator for namespaces , when using enumerations , when there's a class inside a class, but What I don't understand is , what is the purpose of the scope resolution operator while using the ios_base::in and ios_base::out?

Upvotes: 2

Views: 464

Answers (3)

Billy ONeal
Billy ONeal

Reputation: 106539

ios_base refers to a class, specifically std::ios_base (see C++11 27.5.3 [ios.base] in the standard). ios_base::in is defined to be a static constexpr variable of type fmtflags.

Thus, ios_base::in and ios_base::out and friends merely name constant variables.

e.g.:

class ios_base
{
    public:
    static constexpr fmtflags out = 1234 /* (or any other constant) */;
};

int main()
{
    // Access static member `out` of class `ios_base`
    printf("%d", ios_base::out);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

A general way to view the scope resolution operator is to say that you use it for resolving things that can be resolved statically. This includes the things that you listed in the question, but other things should be included as well.

Most notably, your list does not include static members of a class. This is precisely what in and out are - they are static data members, so you need scope resolution operator to resolve them. The applicability is not limited to static data members: static member functions are also resolved using the scope resolution operator.

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

What is the purpose of the scope resolution operator while using the ios_base::in and ios_base::out?

The purpose is to, um, resolve scope.

It's to specify that the symbols in and out in this context are inside the scope [std::]ios_base.

Otherwise, your compiler would not have the faintest clue which in and out you are talking about.

Specifically, in this case, they are static members of the class std::ios_base.

Upvotes: 7

Related Questions