Incorrect use of explicit keyword in c++

464 Views Asked by At

I wanted to create a class MPSList where constructor has an explicit keyword associated with it.

Following is the bare minimal code:

class MPSList {                                                                           
public:                                                                                   
    explicit MPSList(int n) : n_(n) {                                                     
        mpsL.resize(n_, std::vector<MPSNode>{});                                          
        std::cout << mpsL.size() << std::endl;                                            
     }

private:
    struct MPSNode {                                                                      
        double s_;                                                                        
    };

    std::vector<std::vector<MPSNode>> mpsL;
    int n_ = -1;
}; 

CPP file that creates the object of MPSList class.

#include <iostream>

#include "MPSList.hpp"

int main() {
    double n = 10.9;
    MPSList mps(n);    
}

On compiling the above CPP file, I had expected to see an error in initializing the object. As I am passing a double whereas the constructor is explicitly expecting an int.

Command to compile:

g++ -std=c++14 -I../include test.cpp 
./a.out
1

There are 1 best solutions below

0
On

Explicit stops the compiler from doing something like this:

void fn(MPSNode x); // or void fn(const MPSNode& x)
fn(3.0);

The above snippet would compile if you didn't use explicit, and the line that calls fn is equivalent to:

fn(MPSNode(3.0));

This is an implicit conversion from double to MPSNode. Narrowing conversions have relatively little to do with it.

However, you will find that the following will not compile:

MPSList mps{n};

Use uniform initialisation syntax if you want to catch problems like that.