Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of explicit keyword for constructors

I was trying to understand the usage of explicit keyword in c++ and looked at this question on SO What does the explicit keyword mean in C++?

However, examples listed there (actually both top two answers) are not very clear regarding the usage. For example,

// classes example
#include <iostream>
using namespace std;

class String {
public:
    explicit String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

String::String(int n)
{
    cout<<"Entered int section";
}

String::String(const char *p)
{
    cout<<"Entered char section";
}

int main () {

    String mystring('x');
    return 0;
}

Now I have declared String constructor as explicit, but lets say if I dont list it as explicit, if I call the constructor as,

String mystring('x');

OR

String mystring = 'x';

In both cases, I will enter the int section. Until and unless I specify the type of value, it defaults to int. Even if i get more specific with arguments, like declare one as int, other as double, and not use explicit with constructor name and call it this way

String mystring(2.5);

Or this way

String mystring = 2.5;

It will always default to the constructor with double as argument. So, I am having hard time understanding the real usage of explicit. Can you provide me an example where not using explicit will be a real failure?

like image 247
SandBag_1996 Avatar asked Mar 30 '16 13:03

SandBag_1996


People also ask

What is implicit and explicit constructor C++?

In C++ programming, initialization using assignment operator = is called implicit initialization, and initialization using parentheses () and curly braces {} is called explicit initialization.

Can default constructor be explicit?

A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5). It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above.

What does explicit keyword mean in CPP?

The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo − class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p };

What is explicit constructor invocation?

Explicit constructor invocations appear as the first statement in the body of some other constructor. Typically they invoke a constructor of a superclass, although they may also invoke an alternative constructor of the current class. The syntax is either.


1 Answers

explicit is intended to prevent implicit conversions. Anytime you use something like String(foo);, that's an explicit conversion, so using explicit won't change whether it succeeds or fails.

Therefore, let's look at a scenario that does involve implicit conversion. Let's start with your String class:

class String {
public:
    explicit String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

Then let's define a function that receives a parameter of type String (could also be String const &, but String will do for the moment):

int f(String);

Your constructors allow implicit conversion from char const *, but only explicit conversion from int. This means if I call:

f("this is a string");

...the compiler will generate the code to construct a String object from the string literal, and then call f with that String object.

If, however, you attempt to call:

f(2);

It will fail, because the String constructor that takes an int parameter has been marked explicit. That means if I want to convert an int to a String, I have to do it explicitly:

f(String(2));

If the String(char const *); constructor were also marked explicit, then you wouldn't be able to call f("this is a string") either--you'd have to use f(String("this is a string"));

Note, however, that explicit only controls implicit conversion from some type foo to the type you defined. It has no effect on implicit conversion from some other type to the type your explicit constructor takes. So, your explicit constructor that takes type int will still take a floating point parameter:

f(String(1.2))

...because that involves an implicit conversion from double to int followed by an explicit conversion from int to String. If you want to prohibit a conversion from double to String, you'd do it by (for example) providing an overloaded constructor that takes a double, but then throws:

String(double) { throw("Conversion from double not allowed"); }

Now the implicit conversion from double to int won't happen--the double will be passed directly to your ctor without conversion.

As to what using explicit accomplishes: the primary point of using explicit is to prevent code from compiling that would otherwise compile. When combined with overloading, implicit conversions can lead to some rather strange selections at times.

It's easier to demonstrate a problem with conversion operators rather than constructors (because you can do it with only one class). For example, let's consider a tiny string class fairly similar to a lot that were written before people understood as much about how problematic implicit conversions can be:

class Foo {
    std::string data;
public:
    Foo(char const *s) : data(s) { }
    Foo operator+(Foo const &other) { return (data + other.data).c_str(); }

    operator char const *() { return data.c_str(); }
};

(I've cheated by using std::string to store the data, but the same would be true if I did like they did and stored a char *, and used new to allocate the memory).

Now, this makes things like this work fine:

Foo a("a");
Foo b("b");

std::cout << a + b;

...and, (of course) the result is that it prints out ab. But what happens if the user makes a minor mistake and types - where they intended to type +?

That's where things get ugly--the code still compiles and "works" (for some definition of the word), but prints out nonsense. In a quick test on my machine, I got -24, but don't count on duplicating that particular result.

The problem here stems from allowing implicit conversion from String to char *. When we try to subtract the two String objects, the compiler tries to figure out what we meant. Since it can't subtract them directly, it looks at whether it can convert them to some type that supports subtraction--and sure enough, char const * supports subtraction, so it converts both our String objects to char const *, then subtracts the two pointers.

If we mark that conversion as explicit instead:

explicit operator char const *() { return data.c_str(); }

...the code that tries to subtract two String objects simply won't compile.

The same basic idea can/does apply to explicit constructors, but the code to demonstrate it gets longer because we generally need at least a couple of different classes involved.

like image 121
Jerry Coffin Avatar answered Oct 18 '22 10:10

Jerry Coffin