lidong
lidong

Reputation: 608

Difference of these two C++ functions

Consider:

template<class T1, class T2>
class pair
{
    private:
        T1 a;

    public:
        T1 & first(){return a;}
        T1 first() const{return a;}
}

What's the difference between these two "first" functions? When are they used?

Upvotes: 1

Views: 87

Answers (5)

archibaldis
archibaldis

Reputation: 130

T1 & first(){return a}

Returns a reference to your 'a' object of type T1. Changing a returned object will change object inside the object it was returned from.

T1 first() const{return a;}

Returns a copy of 'a'. Doing changes to returned object won't change object it was copied from.

Upvotes: 0

Axel
Axel

Reputation: 14159

The first one returns a reference to a, the second returns a copy of a and is declared const. That means, whenever you have an object of class pair the first one will be called if the object is not declared const, and the second if it is.

However the standard way IMHO would be to use this to avoid the copying:

T1 & first(){return a;}
const T1 & T1 first() const{return a;}

PS: There's a semicolon missing in your code.

Upvotes: 3

DevSolar
DevSolar

Reputation: 70263

The first one is returning a reference, so you get access to a directly. If you act on the return value, you are acting on the a from the instance.

Code smell, breaking encapsulation.

The second one returns a copy of a. Because you cannot change the a inside the instance that way, the function can be const, i.e. you can call it on constant instances of the class (which you cannot with the first function).

I assume that the t1 (sp!) in the template declaration is a typo, right? Should be T1.

Upvotes: 1

rerun
rerun

Reputation: 25505

The one with the const is a const function that returns a copy of a. The second is non-const and returns a reference to a.

If you pass pair to a function by const reference you cannot call the non const version.

Upvotes: 0

Shoe
Shoe

Reputation: 76240

What's the difference between these two "first" functions? when are they used?

The first one (T1 first() const) will be called when the object is const qualified and will return a copy of a, the other (T1 & first()) when the object not const qualified and will return a reference to a.

As an example:

pair<int, int> x;
const pair<int, int> y;
x.first(); // T1 & first()
y.first(); // T1 first() const

Upvotes: 4

Related Questions