Search code examples
c++referencetemporary-objects

Confused about object and dereferenced pointer


I don't get the difference between passing the instance of an object to passing a dereferenced object. I have

class A
{
public:
  A() {}

  void m() {}
};

void method(A& a)
{
  a.m();
}

int main(int argc,char** argv)
{
  method(A());
  return 0;
}

The call above does not work with compiler errors:

In function 'int main(int, char**)':
error:no matching function for call to 'method(A)'
note: candidates are:
note: void method(A&)
note: no known conversion for argument 1 from 'A' to 'A&'
note: void method(B&)
no known conversion for argument 1 from 'A' to 'B&'

But if I write

method(*(new A()));

it does.

Can anyone please tell my why and how to resolve the problem if I cannot change the method I want to call?


Solution

  • Here you are creating a temporary object:

    method(A()); // A() here is creating a temporary
                 //     ie an un-named object
    

    You can only get const& to temporary objects.
    So you have two options:

    1. Change the interface to take a const reference.
    2. Pass a real object.

    So:

    // Option 1: Change the interface
    void method(A const& a)  // You can have a const
                             // reference to a temporary or
                             // a normal object.
    
    
    // Options 2: Pass a real object
    A a;
    method(a); // a is an object.
               // So you can have a reference to it.
               // so it should work normally.