Gelldur
Gelldur

Reputation: 11558

Passing variables by reference and construct new objects

Hello there i have code like this one below and i don't know why it doesn't work.

class Clazz2;
class Clazz
{
    public:
    void smth(Clazz2& c)
    {

    }

    void smth2(const Clazz2& c)
    {

    }
};

class Clazz2
{
    int a,b;
};

int main()
{
    Clazz a;
    Clazz2 z;
    a.smth(z);
    //a.smth(Clazz2()); //<-- this doesn't work
    a.smth2(Clazz2()); // <-- this is ok
    return 0;
}

I have compilation error:

g++ -Wall -c "test.cpp" (in directory: /home/asdf/Desktop/tmp)
test.cpp: In function ‘int main()’:
test.cpp:26:17: error: no matching function for call to ‘Clazz::smth(Clazz2)’
test.cpp:26:17: note: candidate is:
test.cpp:5:7: note: void Clazz::smth(Clazz2&)
test.cpp:5:7: note:   no known conversion for argument 1 from ‘Clazz2’ to ‘Clazz2&’
Compilation failed.

Upvotes: 0

Views: 161

Answers (2)

David G
David G

Reputation: 96800

Your first smth2 takes a reference, which cannot be bound to a temporary like your constructor call a.smth(Claszz2()). However, a const reference can be bound to a temporary because we cannot modify the temporary, so it is allowed.

In C++11, you can use an rvalue-refrerence so that you have the ability to bind temporaries as well:

void smth2(Clazz2 &&);

int main()
{
    a.smth(Claszz2()); // calls the rvalue overload
}

Upvotes: 2

Andy Prowl
Andy Prowl

Reputation: 126432

This is because non-constant references are not allowed to bind to temporary objects. References to const, on the other hand, can bind to temporary objects (see 8.3.5/5 of the C++11 Standard).

Upvotes: 6

Related Questions