Home > Mobile >  How does conversion constructor work in this case?
How does conversion constructor work in this case?

Time:07-01

How does conversion constructor work?

Does the compiler creates a temporary object of myClass and uses the constructor myClass(int i) initialize the temporary object first and then pass the object to function output?

OR

Does the compiler directly initializes the output() parameter rhs using the myClass(int i) constructor.

quite confused with the flow of the conversion constructor.


#include <iostream>
using namespace std;


class myClass
{
public:

   myClass(int i)
   {
      a = i;

   }

   int getA() const
   {
      return a;
   }

private:
   int a;
};


void output(const myClass& rhs)
{
    cout << "rhs.getA(): " << rhs.getA() << endl;
}

int main()
{
   output(120);
}

CodePudding user response:

The parameter is a reference. A reference is not an object. It must be bound to some object instead and the type of the object must be compatible with the type of the reference.

So yes, a temporary object to which the reference can bind must be created. This temporary object is initialized by a call to the myClass(int i) constructor with 120 as argument.

This is also why the program won't compile if you remove the const in void output(const myClass& rhs). Binding a non-const lvalue reference to a temporary is generally not allowed.

  •  Tags:  
  • c
  • Related