explicit কীওয়ার্ড কনস্ট্রাক্টরে ব্যবহার করে ইমপ্লিসিট কনভার্সন (implicit conversion) বন্ধ করা যায়। এটি অনিচ্ছাকৃত টাইপ কনভার্সন থেকে রক্ষা করে।
প্রব্লেম: ইমপ্লিসিট কনভার্সন
class Point {
double x, y;
public:
Point(double a = 0.0, double b = 0.0) : x(a), y(b) {}
bool operator==(Point p2) { return x == p2.x && y == p2.y; }
};
int main() {
Point p(5, 0);
if (p == 5) cout << "Same"; // কম্পাইল হয়! 5 -> Point(5,0) ইমপ্লিসিট কনভার্সন
}
আউটপুট
They are same
সমাধান: explicit কনস্ট্রাক্টর
class Point {
double x, y;
public:
explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {}
bool operator==(Point p2) { return x == p2.x && y == p2.y; }
};
int main() {
Point p(5, 0);
if (p == 5) cout << "Same"; // Error: no match for operator==(Point, int)
if (p == (Point)5) cout << "Same"; // Explicit cast দিয়ে কাজ করবে
}
আউটপুট (explicit সহ)
[Error] no match for 'operator==' (operand types are 'Point' and 'int')
C++11 থেকে: explicit কনভার্সন অপারেটর
class Wrapper {
int val;
public:
explicit operator bool() const { return val != 0; } // if(w) কাজ করবে, কিন্তু bool b = w; করবে না
};
সেরা অনুশীলন: একোয়ারগুমেন্ট কনস্ট্রাক্টর প্রায়ই explicit হওয়া উচিত, বாஙলা কনভার্সন সেমান্টিক্স স্পষ্টভাবে চাইলে বাদে।