What is explicit keyword?
- A constructor that takes a single argument operates as an implicit conversion operator by default. This is also referred as converting constructor.
- To prevent this implicit conversion keyword explicit has been introduced in C++. This makes the constructor as non-converting.
- This keyword has effect only when defined on a single argument constructor or on a constructor which has default arguments for all but one argument.
- Compile time error will be reported if an attempt is made to create an object via conversion as in statements like "MyClass obj2 = 200;".
Demonstrate the usage of explicit keyword
#include <iostream>
using namespace std;
class MyClass {
int data;
public:
explicit MyClass(int aData) {
cout << "Constructor invoked" << endl;
data = aData;
}
};
int main ()
{
MyClass obj1(100);
/*
* Object creation by conversion as below reports a compiler error.
* Error E2034 explicit.cpp 15: Cannot convert 'int' to 'MyClass'
* in function main()
*/
// MyClass obj2 = 200;
}
0 comments:
Post a Comment