user2439492
user2439492

Reputation: 91

What is the use of member initializers list in constructors?

I was trying to understand the concept of operator overloading, but can't understand the use of member initializer lists in this program. What is their real use, and could I rewrite this program without them ?

#include <iostream>
using namespace std;
class Complex
{
    private:
  float real;
  float imag;
    public:
   Complex(): real(0), imag(0){ }
   void input()
   {
       cout<<"Enter real and imaginary parts respectively: ";
       cin>>real;
       cin>>imag;
   }
   Complex operator - (Complex c2)    /* Operator Function */
   {
       Complex temp;
       temp.real=real-c2.real;
       temp.imag=imag-c2.imag;
       return temp;
   }
   void output()
   {
       if(imag<0)
           cout<<"Output Complex number: "<<real<<imag<<"i";
       else
           cout<<"Output Complex number: "<<real<<"+"<<imag<<"i";
   }
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();
result=c1-c2; 
result.output();
return 0;

Upvotes: 0

Views: 79

Answers (2)

Toby Speight
Toby Speight

Reputation: 30834

The difference is small in this case, but becomes very significant when the members to be initialized are references, or declared const. Then they cannot be assigned, and must be initialized.

Upvotes: 0

coincoin
coincoin

Reputation: 4685

I think there is some kind of confusion. You are not talking about std::initialize_list but rather member initializer list.

Yes you can write your constructor without using it :

Complex(): real(0), imag(0){ }

becomes :

Complex(): { real=0; image=0; }

However I would not recommend it. See here why.

Upvotes: 3

Related Questions