1. 程式人生 > >C++ write constructors using a constructor initializer 建構函式 初始化資料

C++ write constructors using a constructor initializer 建構函式 初始化資料

C++‘s constructor is different than java or C#.

A C++ constructor like any other function, has a name, a parameter list, and a function body. Unlike other functions, a C++ constructor may also contain a constructor initializer list:

class ClassC{

public:
	ClassC():m_a(1),m_b(1.5){ // the constructor initializer list
	}
private:
	int m_a;
	float m_b;
};

The constructor initializer starts with a colon, which is followed by a comma-separated list of data members each of which is followed by an initializer inside parentheses. The constructor initializes the m_a to 1, and initializes m_b to 1.5

What's the different between  the two ways.

class ClassC{

public:
	ClassC(){ 
		m_a = 1;
		m_b = 1.5;
	}
private:
	int m_a;
	float m_b;
};

Look at the example below:

#ifndef _TESTCLASS_
#define _TESTCLASS_


#include <iostream>

using namespace std;


class ClassA{

public:
	ClassA(){
       cout << "call ClassA's default constructor" << endl;
	}
	ClassA(int a){
		m_a = a;
        cout << "call ClassA's \"ClassA(int a)\" constructor" << endl;
	}

private:
	int m_a;

};


class ClassB{

public:
	ClassB(){
	  classa = ClassA(1);
      cout << "call ClassB's constructor" << endl;
	}
private:
	ClassA classa;
};


#endif

When we call

ClassB b;

The classa is initialize before call classa = ClassA(1)!. The result is not we expected.

When we use the constructor initializer, the result is OK now.

#ifndef _TESTCLASS_
#define _TESTCLASS_


#include <iostream>

using namespace std;


class ClassA{

public:
	ClassA(){
       cout << "call ClassA's default constructor" << endl;
	}
	ClassA(int a){
		m_a = a;
        cout << "call ClassA's \"ClassA(int a)\" constructor" << endl;
	}

private:
	int m_a;

};


class ClassB{

public:
	ClassB():classa(1){ //use constructor initializer list 
      cout << "call ClassB's constructor" << endl;
	}
private:
	ClassA classa;
};


#endif

ClassB b;

In many classes, the distinction between initialization and assignment is strictly a matter of low-level efficiency: A data member is initialized and assigned when it could have been initialized directly.