0

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Rammy Aly
  • 29
  • 2
  • 1
    If you declare a class `A` with a constructor, in your `.cpp` you already know that you would define that constructor as `A::A(parameters...){ ... }` in your `.cpp` file. If the class has a method named `foo` that returns a `void` that gets declared as `void A::foo(){ // code }` -- doesn't this observation offer a little bit of a clue, here? – Sam Varshavchik Sep 15 '22 at 19:09
  • wait then trunc is a function? – Rammy Aly Sep 15 '22 at 19:15
  • No, but this is not limited to functions, but to anything that's declared in the class. Like a `typedef` or another class, for example. – Sam Varshavchik Sep 15 '22 at 19:16
  • i tried int s::something = 3; but that didnt work – Rammy Aly Sep 15 '22 at 19:18
  • Well, did you declare `something` in your `s` class? What is it? – Sam Varshavchik Sep 15 '22 at 19:20

1 Answers1

1

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;
fabian
  • 80,457
  • 12
  • 86
  • 114
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335