开发者

Initializing data-member references using initialization lists in C++

Fellow Stackers,

Consider the following two simple classes in the header file:

Class CC
{
 public:
 CC(int& value);
 C& operator=(const C& other);
 {
   cout<<" From copy constructor ";
 }

 int m_cc;
};

Class AA
{
 public:
 AA( CC& refCC);

 CC m_cInstance;
}

The following is in the .cpp file.

CC:CC(int& value): m_cc(value)
{
   cout<<" Constructor of CC" <<endl;
   m_cc++;
}

AA:AA(CC& refCC): m_cInstance(refCC)
{
   cout<<" The value of m_cc in refCC is: "<< refCC.m_cc; 
   cout<<" The address of m_cc in refCC is: "<< &refCC.m_cc;
   cout<<" The address of refCC is: "<< &refCC;

   cout<<" The value of m_cc in m_cInstance is: <<m_cInstance.m_cc;
   cout<<" The address of m_cc in m_cInstance is: <<&m_cInstance.m_cc;
   cout<<" The address of m_cInstance is: <<&m_cInstance;
}

I use the above two declared simple classes in the follwing way in my main.cpp file:

int cvalue = 1000; CC refCC(cvalue);

AA aaObj(refCC);

Here is the output of the program:

 Constructor of CC
 The value of m_cc in refCC is: 1001
 The address of m_cc in refCC is: 0x12ff20
 The address of refCC is: 0x12ff20

 The value of m_cc in m_cInstance is: 1001
 The address of m_cc in m_cInstance is: 0x12ff14
 The address of m_cInstance is: 0x12ff14

Here are few observations:

  1. Notice that address of m_cI开发者_JAVA百科nstance in the instance AA is different from the address of refCC.

  2. Though the instance of CC is passed by reference(refCC) in the constructor of AA, the member variable "m_cInstance" is seperate instance by itself.

  3. Constructor of the instance to CC is called once when "refCC" is created even though two distinct instances of CC are present in the program carrying the same state.

  4. The overridden assignment operator is never called.

My question is simple:

How is the "m_cInstance" created in the constructor of AA without a call to constructor of CC or the assignment operator defined in CC ??

And if CC contains a handle to a file on disk as a member variable ? What is its behavior in "m_cInstance"??

Thanks,

De Costo.


m_cInstance is created using the (compiler provided in your case) copy constructor. As a sanity check, if you need to define the assignment operator, you probably need to define the copy constructor and the destructor as well (know as the rule of three here and on wikipedia)


You're copy constructing to create m_cInstance so it doesn't appear that you log that. m_cInstance is updated once with a copy of refCC and won't change even if the refCC changes outside the instance.


there is a copy constructor that is provided to your class (by the compiler) and if i understand correctly you are probably confusing the operator=(const C& other) that you have defined with the copy constructor.

For a class CC the copy constructor will have have a declaration like this

CC(const CC& C);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜