explicit

I am trying to understand the explicit keyword. if my understanding is correct the explicit keyword prevents this from happening.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class circle
{
public:
    circle(int size) : size(size){}

    void print() const
    {
        cout << size << endl;
    }

private:
    int size;
}; 

int main(int argc, char* argv[])
{
    circle circ = 42; // implicit conversion
    circ.print(); // prints 42
}


i guess what im asking is what other meaning could it have; what else would you be trying to do. I could see if what you were assigning was the same type like another circle. then you may for instance expect a member wise copy. not initialization. but passing an int, what could you be trying to do that results in this error.

I dont understand how this even comes up. your using the assignment operator. this implies some kind of copy assignment. but why would you pass a integral value like that. you dont have any information on the class where that assignment would even go. so what the heck could you be trying to do. i agree its strange and unexpected what happens to it. but why would you do it in the first place.
Last edited on
Consider the std::string class, with it's constructor that takes a C-style string.
1
2
std::string random_str = "stuff"; // if it was explicit, you could not do this
std::string random_str2("stuff");

As to the purpose of doing that, consider a std::vector class that had a constructor that looked like so:
vec(std::size_t initial_size);
Suppose it allocated enough memory for initial_size elements. In that case, something like the following would work:
vec random_vector = 3;
Declaring the constructor explicit prevents that odd calling of the constructor.
ok thanks Zhuge
Topic archived. No new replies allowed.