Explicit Constructor
#include <iostream>
#include <string>
class MyString {
private:
std::string str;
public:
// Non-explicit constructor
MyString(const char* s) : str(s) {
std::cout << "Char* constructor called" << std::endl;
}
// Explicit constructor
explicit MyString(int n) : str(n, 'a') {
std::cout << "Integer constructor called" << std::endl;
}
void print() const {
std::cout << str << std::endl;
}
};
void takeMyString(const MyString& ms) {
ms.print();
}
int main() {
MyString s1 = "Hello"; // OK: Calls char* constructor
s1.print();
MyString s2(5); // OK: Calls integer constructor
s2.print();
// MyString s3 = 5; // Error: Implicit conversion not allowed
MyString s4 = MyString(5); // OK: Explicit conversion
takeMyString("World"); // OK: Implicit conversion allowed
// takeMyString(10); // Error: Implicit conversion not allowed
takeMyString(MyString(10)); // OK: Explicit conversion
return 0;
}Last updated