This post will introduce a key word explicit that can forbid the implicit type casting by constructor with only one parameter.
Implicit type casting
In C++ class, a constructor with only one parameter (or parameters with default values except the first one) has two functions. One is to contruct an object, another is that will be called when an implicit type casting is performed. However, this is not always good. In some cases, it will lead to logical error.
|
|
The result is:
|
|
In this case, chr
is a char
type and MyString s5 = chr;
will be interpreted by compiler as MyString s5 = MyString((int)chr)
where chr
is implicitly cast to int
. This logical error is caused by the constructor MyString(int n)
which make this implicit casting enable. To avoid this, the key word explicit
should be used to restrict it.
|
|
To restrict by explicit
, only MyString(const char* p)
can be used for implicit casting and it will cause compile-time error.
Copy contructor
There are three cases where the implicit casting will be performed by copy constructor.
- An object is passed into a function by pass-by-value.
- An object is retured from a function by pass-by-value.
- Call like:
Myclass myobj1 = myobj2;
wheremyobj2
is another object ofMyclass
.
So if restricting a copy constructor by explicit
, all operations above will cause error in compiling. That means explicit
is not a good design for copy constructor.