user784668
user784668

Reputation:

Difference between `T&` and `const T&` for all-const class

Suppose that I have a class like that:

class Foo : boost::noncopyable
{
public:
  Foo(int a, int b);

  const int something;
  const int something_else;
  const std::string another_field;
  // and that's that, no more methods nor fields
};

Now, is there any practical difference between accessing the objects of this class through a Foo&, as opposed to const Foo&, other than that these two are two distinct types?

There shouldn't be any difference for accessing its fields, as they're const, so they will be accessed to through a const T& anyway.

But is there any difference when it comes to the class as a whole? Something to do with templates, perhaps? Anything?


Now that templatetypedef has written a nice answer, which unfortunately is not helpful in this case, I think it'd be nice to underline that it's very much about what can you do when you already have a reference (note all these "accessing"), not about what you can bind to the reference.

So, you can assume that the ref is already there, bound to some object. Now it's all about what can be done with it.

Upvotes: 8

Views: 425

Answers (1)

templatetypedef
templatetypedef

Reputation: 372972

I'm not sure if this is what you're looking for, but consider this function:

void DoSomething(Foo& fooRef);

In this case, you cannot call

DoSomething(Foo()); // Error- can't bind a reference to a temporary

However, if we have this function:

void DoSomethingConst(const Foo& fooRef);

Then we can indeed call

DoSomethingConst(Foo()); // Okay - const reference can bind to a temporary

So there is a slightly difference in that a const reference can potentially bind to a temporary Foo when a non-const reference cannot. Consequently, you'd probably want functions taking in Foos to take in a const Foo& rather than a Foo& to make it possible to call the function with temporaries.

Hope this helps!

Upvotes: 13

Related Questions