SOURCE :: codeproject
#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
double real, img;
public:
complexNumbers() : real(0), img(0) { }
complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
complexNumbers( double r, double i = 0.0) { real = r; img = i; }
friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
cout<<"Real Part: "<<cx.real<<" Imag Part: "<<cx.img<<endl;
}
int main() {
complexNumbers one(1);
display(one);
display(300);
return 0;
}
A similar example, just added one more line in
main
===> display(300);
. And, here we go, the output becomes:Real Part: 1 Imag Part: 0
Real Part: 300 Imag Part: 0
Bang!!! That was really not expected. First, the code is itself confusing, what does
display(300)
mean? 300 itself is never an object/instance of the class complexNumbers
that the method display
expects as an argument. So, how does this happen?
Since the method
display
expects an object/instance of the class complexNumbers
as the argument, when we pass a decimal value of 300, an implicit conversion happens in-place, which in-turn transfers the decimal value of 300 to a temporary object of class complexNumbers
(and thereby assigns the value 300 to the real part of that temporary object).
How doe we overcome this situation??
Simple, force the compiler to create an object using explicit construction only, as given below:
#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
double real, img;
public:
complexNumbers() : real(0), img(0) { }
complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }
friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
cout<<"Real Part: "<<cx.real<<" Imag Part: "<<cx.img<<endl;
}
int main() {
complexNumbers one(1);
display(one);
complexNumbers two =2;
display(200);
return 0;
}
Consider the following statement:
explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }
Here, we are forcing the compiler not to do an implicit conversion for this piece of code. Now, if the programmer puts a line containing an implicit conversation, the compiler returns back with an error:
bash-3.2$ g++ -g -o hello test2.cpp
test2.cpp: In function ‘int main()’:
test2.cpp:22: error: conversion from ‘int’ to non-scalar type ‘complexNumbers’ requested
test2.cpp:23: error: conversion from ‘int’ to non-scalar type ‘complexNumbers’ requested
From this point onwards, the programmers need to use this:
display(complexNumbers(200)); //only explicit conversion is allowed…………
No comments:
Post a Comment