2

I'm trying to understand constructors calling with l/r values, so I created the class A below :

class A {
    public :
    A()            { cout << "called default constructor" << endl ; }
    A(const A&)    { cout << "called copy constructor" << endl ; }
    A(const A&&)   { cout << "called move constructor" << endl ; }
};

in the main function, I created an instance a

int main()
{
    A a(A());
    return 0;
}

but no constructor among the implemented constructors is called !

any explanation? thank you!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Saif Faidi
  • 509
  • 4
  • 15

1 Answers1

5

This

A a(A());

is a function declaration that has the return type A and one parameter of the type A(), which is a function type that takes no arguments and returns an A. The compiler implicitly adjusts the parameter to pointer type to function like A (*)().

To declare an object you should write either

A a( ( A() ));

Or

A a {A()};

or for example

A a( A{} );

Here is a demonstrative program

#include <iostream>

using namespace std;

class A {
    public :
    A()            { cout << "called default constructor" << endl ; }
    A(const A&)    { cout << "called copy constructor" << endl ; }
    A(const A&&)   { cout << "called move constructor" << endl ; }
};

int main() 
{
    A a1( ( A() ) );
    A a2( A{} );

    A a3 { A() };


    return 0;
}

Its output is

called default constructor
called default constructor
called default constructor

Pay attention to that in these object declarations there is copy elision.

To call for example the copy constructor you could write

A a1;
A a2( a1 );

And a simple way to invoke the move constructor is for example

A a1;
A a2( std::move( a1 ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335