0

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;
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
user2439492
  • 91
  • 1
  • 2
  • 8

2 Answers2

3

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.

coincoin
  • 4,595
  • 3
  • 23
  • 47
  • 2
    NB: You can, but shouldn't if you can avoid it, because you then perform a default-initialization followed by an assignment. – Quentin Jul 02 '15 at 11:21
  • @coincoin I am talking about member initializer list here – user2439492 Jul 02 '15 at 11:27
  • oh okay! yeah assignment will also be there if we don't use initializer list here. Actually I am new to all these types of concepts Thanks for the answers. – user2439492 Jul 02 '15 at 11:29
  • Question edited to clarify that it's about member initialization, not `std::initializer_list`, and overloading isn't relevant. – Toby Speight Jul 02 '15 at 14:33
0

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103