Idiom : Declare constructors as explicit --> Constructors declared as explicit are preferred to non-explicit ones. This prevents unwanted complications and misuse of the constructors. Consider the following piece of code -->
#include <iostream>
using namespace std;
class Ai{
public:
int x;
A(int xx){
x=xx;
}
void dummy(A a){
cout<<a.x<<" of A";
}
};
class B {
public:
int x;
explicit B(int xx){
x=xx;
}
void dummy1(B b) {
cout<<b.x<<" of B";
}
};
int main(){
A a(150);
B b(200);
a.dummy(100);
b.dummy1(500);
}
Note that the constructor of the class B is made explicit.
Consider the statement a.dummy(100), first. Note that the function dummy actually takes in a parameter of class type A, but we are able to pass an integer! What this means is that the integer is cast into an object of class type A by the constructor since, by default, without the extern preamble, it is allowed to do an implicit conversion.
However, with the statement b.dummy1(500),you will see that this does not work because the constructor associated with B is declared explicit. Consequently, when you try to compile this program, you will get the following error -->
g++ explicit.cpp
explicit.cpp: In function 'int main()':
explicit.cpp:31:14: error: no matching function for call to 'B::dummy1(int)'
explicit.cpp:31:14: note: candidate is:
explicit.cpp:22:8: note: void B::dummy1(B)
explicit.cpp:22:8: note: no known conversion for argument 1 from 'int' to 'B'
#include <iostream>
using namespace std;
class Ai{
public:
int x;
A(int xx){
x=xx;
}
void dummy(A a){
cout<<a.x<<" of A";
}
};
class B {
public:
int x;
explicit B(int xx){
x=xx;
}
void dummy1(B b) {
cout<<b.x<<" of B";
}
};
int main(){
A a(150);
B b(200);
a.dummy(100);
b.dummy1(500);
}
Note that the constructor of the class B is made explicit.
Consider the statement a.dummy(100), first. Note that the function dummy actually takes in a parameter of class type A, but we are able to pass an integer! What this means is that the integer is cast into an object of class type A by the constructor since, by default, without the extern preamble, it is allowed to do an implicit conversion.
However, with the statement b.dummy1(500),you will see that this does not work because the constructor associated with B is declared explicit. Consequently, when you try to compile this program, you will get the following error -->
g++ explicit.cpp
explicit.cpp: In function 'int main()':
explicit.cpp:31:14: error: no matching function for call to 'B::dummy1(int)'
explicit.cpp:31:14: note: candidate is:
explicit.cpp:22:8: note: void B::dummy1(B)
explicit.cpp:22:8: note: no known conversion for argument 1 from 'int' to 'B'
No comments:
Post a Comment