forumulator
forumulator

Reputation: 875

C++ const correctness with reference members

I have a fstream & member in a class, on which I'm calling the seekg function in a const function of the class, and yet the code compiles. I checked, and the seekg is not declared const (nor should it be), so how is this happening?

This is my code:

class Test {
    fstream &f;
public:
    Test(fstream &f_): f(f_) {}
    int fid() const {
        f.seekg(5);
        return 0;
    }
};

Upvotes: 2

Views: 367

Answers (2)

Oliv
Oliv

Reputation: 18041

The rule is defined in [expr.ref]/4:

If E2 is declared to have type “reference to T”, then E1.E2 is an lvalue; the type of E1.E2 is T. [...]

In practice you should consider a reference to T, as a const pointer to T with automatic dereferencement. Internaly this is what are reference. And inside the standard, all rules that applies to reference (see [basic.life] for example) are those rules that would apply to a const pointer:

class Test {
  fstream * const f;
public:
  Test(fstream &f_): f(&f_) {}
  int fid() const {
    f->seekg(5);
    return 0;
  }
};

Upvotes: 0

Heath Raftery
Heath Raftery

Reputation: 4159

It turns out the const does not apply to members that are pointers or references, as stated here.

The best explanation I've seen of this is here where it states that inside const member functions, this is a const T *, where T is the class.

In your example that means that all the const modifier on fid() does is to change this from a Test * to a const Test * inside the function. When you write f., this is accessed as this->f. which is of type fstream & const. The reference is const but what it refers to is not, so calling a function that modifies it causes no problems.

Upvotes: 2

Related Questions