What does the explicit keyword in C++ do?

Asked 2 years ago, Updated 2 years ago, 143 views

I'm going around the internetgo I saw the C++ code below What does this explicit do for you?

class String {
public:
    explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
};

c++ constructor explicit explicit-constructor

2022-09-22 22:31

2 Answers

The C++ compiler can change the value that comes into the function's factor to suit its type. I'll explain what this means in the following example.

class Foo{
public:
    int m_foo;
    Foo (int foo) : m_foo (foo) {}
};

void printM_foo (Foo foo){
    cout << foo.m_foo << endl;
}

int main (){
    int num = 43;
    printM_foo(num);
}

Result: 43

printM_foo(Foofoo) receives the foo type parameter foo and outputs foo.m_foo. However, main() is now passing the int type parameter, not the Foo type. It even prints well. How does a compiler work to produce this result?

When printM_foo(num) is invoked, The compiler calls the constructor that receives int as a parameter in the Foo class printM_foo(Foooo) Transform the type to Foo which is the appropriate parameter type.

The explicit keyword is used in this situation. If the use is not intended for automatic conversion, it can cause a bug Use the explicit keyword to prevent bugs by preventing the compiler from calling the constructor for parameter type conversion.

Therefore, if you specify explicit in front of the constructor of the above code as follows, explicit Foo (int foo) : m_foo (foo) {}

printM_foo(num); The compiler displays an error From here on, the parameter type conversion should be done by the programmer, not by the compiler.

class Foo{
public:
    int m_foo;
    explicit Foo (int foo) : m_foo (foo) {}
};

void printM_foo (Foo foo){
    cout << foo.m_foo << endl;
}

int main (){
    int num = 43;
    printM_foo(num); // Error
}


2022-09-22 22:31

If you get 43 as a factor in the void printM_Foo (Foooo) declaration, Foo foo = 43 Isn't a temporary object created when it becomes Foofoo (43)


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.