vendredi 29 avril 2016

What is the difference between constand and constant reference argument

I have seen many people set their function argument as:

function(const myType &myObj)

I do not understand why they use & after the type?

It seems const is enough to stop the constructor from being called.

So, I wrote the following code and I see no advantage in the result. Can someone explain that?

#include <iostream>
using namespace std;

class myclass
{
public:

    myclass()
    {
        cout<<"constructor is called\n";
    }

    int field;
};

void func1(myclass a)
{
    cout<<"func1: "<<a.field<<"\n";
}


void func2(const myclass a)
{
    cout<<"func2: "<<a.field<<"\n";
}


void func3(const myclass &a)
{
    cout<<"func3: "<<a.field<<"\n";
}

int main ()
{
    myclass obj;
    obj.field=3;
    cout<<"----------------\n";
    func1(obj);
    cout<<"----------------\n";
    func2(obj);
    cout<<"----------------\n";
    func3(obj);
    cout<<"----------------\n";
    return 0;
}

Result:

constructor is called
----------------
func1: 3
----------------
func2: 3
----------------
func3: 3
----------------

Aucun commentaire:

Enregistrer un commentaire