Explicit – c++ what is it for ?

The explicit keyword in c++ is make sure that user of your class only creates and uses the class only creates it in the way that you was expecting and not via any references as such.

For example in the following code example

class mainClassWith {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    explicit mainClassWith(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWith(const mainClassWith &theClass)
{
    cout << "the value with " << theClass.internal_value << endl;
}

The functionWith will take a parameter of mainClassWith of which has a explicit keyword on its constructor, this means that if we try and do something like

    mainClassWith mainWith(4);
 
    functionWith(mainWith);

then the compiler will compile and also the output would be printed to the screen of “the value with 4”, but since we know that the mainClassWith takes a integer value as a constructor and try to bypass any object creation of that mainClassWith and try and do this

functionWith(3);

then the compiler will complain because we cannot setup a mainClassWith on the fly like this and let the compiler pass a value of “3” to the class and hope that it works!!!, we have explicitly declared that the constructor must be initialised before using.

But if we did take off the explicit keyword as in the class example below.

class mainClassWithOut {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    mainClassWithOut(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWithout(const mainClassWithOut &theClass)
{
    cout << "the value without  "<< theClass.internal_value << endl;
}

then we are able to call the new function (functionWithout) without actually setting up the object and allow the compiler to make up its own instance of that object and pass to the function.

functionWithout(5);

would work and the output would be “the value without 5” which is correct, but the compiler and created the mainClassWithout object and setup with the value of 5 via its constructor, which if there was a few different constructors etc then how would you be sure that the correct constructor was called and thus would the value that you want back from the class really be 5, it could be 0 and another value be that 5!!.

Leave a Reply

Your email address will not be published.