-3

I've read a number of questions on stackoverflow regarding implicit and explicit constructors, but I'm still having trouble distinguishing between an implicit and explicit constructors.

I was wondering if someone could give me a good definition and some examples or maybe direct me to a book / resources that explains this concept well

dwnenr
  • 443
  • 1
  • 4
  • 15

1 Answers1

0

Take this as an example:

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<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
    }
    int main() {
      complexNumbers one(1);
      display(one);
      display(300);   //This code compiles just fine and produces the ouput Real Part: 300 Imag Part: 0
      return 0;
    }

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.

To overcome this situation, we have to force the compiler to create an object using explicit construction only, as given below:

 explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }  //By Using explicit keyword, we force the compiler to not to do any implicit conversion.

and after this constructoris present in your class, the statement display(300); will give an error.

Nishant
  • 1,635
  • 1
  • 11
  • 24