0

I am new to C++ I do not understand this type of declaration. For example this is my class:

class Complex
{
  public:
    Complex( double r, double i ) : re(r), im(i) {}
    Complex operator+( Complex &other );
    void Display( ) {   cout << re << ", " << im << endl; }

    double re, im;
};

I don't understand the declaration in this constructor:

Complex( double r, double i ) : re(r), im(i) {}

i.e what is the symbol ":" used for and what happen if we declare like this in constructor re(r), im(i).

Mat
  • 202,337
  • 40
  • 393
  • 406

1 Answers1

3

This is a member initialization list. It is used to initialize members (believe it or not). In this case, it states that the member re should be initialized with r and the member im should be initialized with i.

It is particularly useful for class type members to avoid a potentially expensive unnecessary default initialization at the beginning of the constructor. For example, if you had a std::string member, the following constructor would first default construct it to an empty string and then assign to it:

Class() { string_member = "Hello"; }

Whereas the following constructor would simply construct it with "Hello" as an argument to the constructor:

Class() : string_member("Hello") { }

A const member cannot be assigned to after initialization, so must be initialized by the member initialization list (unless you provide an in-class initializer in C++11).

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324