Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 / Generated constructor

Tags:

c++

c++11

I have been working on a C++ project started by someone else (who left the company). He has written a piece of code which seems to work pretty well but I cannot understand it.

Here is below a simplified version of the code:

There are two classes :

class Algo_t {
protected :
    Matrix_t m_Matrix ;
public:
    Algo_t(Matrix_t && Matrix) {
        DoSomething();
    }
};

class Matrix_t {
protected :
    std::ifstream & m_iftsream ;
public:
    Matrix_t(std::ifstream && ifstream) {
        DoSomething();
    }
};

In the main:

There is the following call in the main function:

char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));

First I was very surprised that the code compiled without any error because there is no constructor of Algo_t taking ifstream as a parameter. I was more surprised to notice that this code works very well.

Are the constructor generated by the compiler or there is some new feature introduced by C++11 (with the rvalue...)?

like image 305
clam37 Avatar asked Dec 06 '22 17:12

clam37


2 Answers

In C++ you are allowed up to one user defined conversion. You cannot directly construct a Algo_t from a ifstream but you can construct a Matrix_t with a ifstream. So in

Algo_t MyAlgo(ifstream(pMyFileName));

The compiler construct a temporary Matrix_t(your one user defined conversion) and then you use that temporary to construct MyAlgo

like image 144
NathanOliver Avatar answered Jan 06 '23 14:01

NathanOliver


As explained here:

Single-argument constructors: allow implicit conversion from a particular type to initialize an object.

Hence, there is an implicit conversion option from ifstream to Matrix_t due to the constructor:

Matrix_t(std::ifstream && ifstream)

So when you called:

Algo_t MyAlgo(ifstream(pMyFileName));

the ifstream(pMyFileName) object convert to Matrix_t object and then used by the constructor Algo_t(Matrix_t && Matrix)

like image 35
Ohad Eytan Avatar answered Jan 06 '23 15:01

Ohad Eytan