std::fstream is a class but references std::fstream::trunc using namespace syntax?

62 views Asked by At

I was getting some help on creating files with fstream, but came across this method where you pass std::fstream::trunc to the constructor.

I was curious as to how fstream is a class, but referencing the trunc member is like fstream is a namespace (fstream::trunc, like NAMESPACE::MEMBER).

How is this done?

1

There are 1 answers

3
Vlad from Moscow On

trunc is a static member of the class std::ios_base. To access static members you need to use the class name where they are declared or an object of the class.

Here is a demonstration program

#include <iostream>

namespace N
{
    class A
    {
    public:
        inline static int x = 10;
    };

    class B : public A
    {
    };
}

int main()
{
    std::cout << N::B::x << '\n';
}

The program output is

10

Or you could declare the static data member like for example

const static int x = 10;

or

constexpr static int x = 10;

Or you could declare it within the class like

static int x;

and then define it outside the class like

int A::x = 10;