Class Member Initialization Differences

Regarding the class definition for a complex number, I saw two types of definitions:

Definition 1

class Complex
{
   private:
      double re;
      double im;

   public:
      Complex(float r,float i) {re = r; im = i;}
      ~Complex() {};
};

Definition 2

class Complex
{
   private:
      double re;
      double im;

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

The first definition looks good to me, but I don’t quite understand the second definition, how

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

work? What does re () mean?

+3
source share
5 answers

He called the initialization list . In the class constructor, you can initialize member variables using this syntax. Thus, this is equivalent to placing statements re = r; im = i;in the constructor body.

POD, int, double , . const , :

  • const . .
  • , , . , ( , ).

, , - , , , , .

:

class Example
{
private:
    std::string m_string;
public:
    Example()
    {
        // m_string is first initialized by the std::string default constructor,
        // then we assign to it with operator=(const char *).
        // This is inefficient.
        m_string = "test";
    }

    Example(int dummy)
        : m_string("test")
    {
        // Better: we just call the std::string(const char*) constructor directly
    }
};
+4

Complex , ( ) .

re(...) , re , .

- double int :

double d(5.0d);
int i(5);

, .

+2

. re r, im - i.

, , , , .

+1

, ++ . .

,

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

Complex, r re im. .

, , , - . :

class MemberClass
{
    private:
        int mValue;

    public:
        MemberClass(int value): mValue(value) {}
};

class MemberHolder
{
    private:
        MemberClass mMember;

    public:
        MemberHolder(int value): mMember(value) {}
};

.

+1

++ .

a = 5;  // assignment
int b = 6; // initialization
int b(6);  // also initialization

. , re im , .

. . , + - . .

Generally, you should prefer to initialize your data members in the initialization list to assign their values ​​inside the constructor body. However, there is a warning. The data item in the initialization list is initialized in the order in which they are declared in the class, and not in the order in which they appear in the initialization list. Typically, you want the order of the members in the list to match their order of declaration. Otherwise, it can be very difficult for you to find errors if the initialization of one data item depends on the value of another.

+1
source

Source: https://habr.com/ru/post/1796406/


All Articles