473,406 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

member variable initialization

200 100+
Hello everyone,


I am wondering in the following code, member variable a in class B is not put in the initialization list or constructor of B directly, but it is initialized. How and when member variable a of class B is created and initialized? Is constructor of B invokes constructor of a?

Output is,

In constructor A
In constructor B

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class A
  6. {
  7. public:
  8.  
  9.     A()
  10.     {
  11.         cout << "In constructor A" << endl;
  12.     }
  13. };
  14.  
  15. class B
  16. {
  17. public:
  18.  
  19.     A a;
  20.  
  21.     B()
  22.     {
  23.         cout << "In constructor B" << endl;
  24.     }
  25. };
  26.  
  27. int main()
  28. {
  29.     B b;
  30.  
  31.     return 0;
  32. }
  33.  
  34.  

thanks in advance,
George
Dec 18 '07 #1
12 2060
weaknessforcats
9,208 Expert Mod 8TB
The sequence of events is:

1) compiler allocates memory for B data members
2) compiler calls constructors for data members:
- calls A constructor if specified on B initilizer list
- calls A default constructor if no A constructor specified on B initializer list
3) compiler calls B constructor
Dec 18 '07 #2
George2
200 100+
Thanks weaknessforcats,


So, I think it is good code if we do not put member variable in initialization list of constructor and even the body of constructor, right?

The sequence of events is:

1) compiler allocates memory for B data members
2) compiler calls constructors for data members:
- calls A constructor if specified on B initilizer list
- calls A default constructor if no A constructor specified on B initializer list
3) compiler calls B constructor

regards,
George
Dec 19 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
So, I think it is good code if we do not put member variable in initialization list of constructor and even the body of constructor, right?
That's false. The member initialization list is used to intialize the members. If you have const member X that needs to be initialized to a value the user enters then you would:

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.    const int X;
  4.    public:
  5.    MyClass(int arg);
  6. };
  7.  
  8. MyClass::MyClass(int arg) : X(arg)
  9. {
  10.  
  11. }
  12.  
The initialization list is the only way to initialize a const data member. Later, when using inheritance, the initialization list is used to call you base class coinstrcuctor.

In short, use the initialization list whenever possible since the values in the list will be used when the member variable is being created.
Dec 19 '07 #4
George2
200 100+
Thansk weaknessforcats,


I do not agree that const member can not be initialized if it is not in the constructor initialization list. In the following code, const member has a default constructor, and it could be intialized.

Could you review it please? If I am wrong, please feel free to correct me. :-)

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class A
  6. {
  7. public:
  8.     A()
  9.     {
  10.         cout << "Initialized" << endl;
  11.     }
  12. };
  13.  
  14.  
  15. class MyClass
  16. {
  17.    A _a;
  18.    public:
  19.    MyClass();
  20. };
  21.  
  22. MyClass::MyClass()
  23. {
  24.  
  25. }
  26.  
  27. int main()
  28. {
  29.     MyClass instance;
  30.  
  31.     return 0;
  32. }
  33.  

regards,
George

That's false. The member initialization list is used to intialize the members. If you have const member X that needs to be initialized to a value the user enters then you would:

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.    const int X;
  4.    public:
  5.    MyClass(int arg);
  6. };
  7.  
  8. MyClass::MyClass(int arg) : X(arg)
  9. {
  10.  
  11. }
  12.  
The initialization list is the only way to initialize a const data member. Later, when using inheritance, the initialization list is used to call you base class coinstrcuctor.

In short, use the initialization list whenever possible since the values in the list will be used when the member variable is being created.
Dec 20 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
I don't see a const member in your example.
Dec 20 '07 #6
George2
200 100+
Sorry weaknessforcats,


Here is the code. You can see const member could be initialized even if it is not in the initialization list.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class A
  6. {
  7. public:
  8.     A()
  9.     {
  10.         cout << "Initialized" << endl;
  11.     }
  12. };
  13.  
  14.  
  15. class MyClass
  16. {
  17.    const A _a;
  18.    public:
  19.    MyClass();
  20. };
  21.  
  22. MyClass::MyClass()
  23. {
  24.  
  25. }
  26.  
  27. int main()
  28. {
  29.     MyClass instance;
  30.  
  31.     return 0;
  32. }
  33.  
I don't see a const member in your example.

regards,
George
Dec 21 '07 #7
weaknessforcats
9,208 Expert Mod 8TB
That's fine. But how do you intialize that constant if the value isn't known until run time???

What you show is a compile time initialization.
Dec 21 '07 #8
George2
200 100+
Sorry weaknessforcats,


I do not quite understand what do you mean. Could you show some pseudo code please?

That's fine. But how do you intialize that constant if the value isn't known until run time???

What you show is a compile time initialization.

regards,
George
Dec 22 '07 #9
weaknessforcats
9,208 Expert Mod 8TB
Here you go:
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.     private:
  4.        const int data;
  5.     public:
  6.        A(int arg);
  7.        int GetData();
  8. };
  9. int A::GetData()
  10. {
  11.      return this->data;
  12. }
  13. int main()
  14. {
  15.      cout << "Enter your constant value: ";
  16.      int value;
  17.      cin >> value;
  18.      A  obj(value);
  19.      cout << "A created with " << obj.GetData() << endl;
  20. }
  21.  
Now write the A constructor to initialize the A::data member.
Dec 22 '07 #10
George2
200 100+
Thanks weaknessforcats,


I think you mean in your sample below, we must put the intialization of const member variable data into constructor's initialization list, right?

Here you go:
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.     private:
  4.        const int data;
  5.     public:
  6.        A(int arg);
  7.        int GetData();
  8. };
  9. int A::GetData()
  10. {
  11.      return this->data;
  12. }
  13. int main()
  14. {
  15.      cout << "Enter your constant value: ";
  16.      int value;
  17.      cin >> value;
  18.      A  obj(value);
  19.      cout << "A created with " << obj.GetData() << endl;
  20. }
  21.  
Now write the A constructor to initialize the A::data member.

regards,
George
Dec 24 '07 #11
weaknessforcats
9,208 Expert Mod 8TB
That's correct.

The initialization list is used to call constrcutors on any of your member variables. Some classes don't have default constructors and without a feature like this, there would be no way to have an object of these classes be a data member.

Also, you use the initialization list in inheritance so you can call your base class constructor. That constructor must execute before your derived class constructor starts.
Dec 24 '07 #12
George2
200 100+
Thanks for your clarification, weaknessforcats!


I agree this time. :-)

That's correct.

The initialization list is used to call constrcutors on any of your member variables. Some classes don't have default constructors and without a feature like this, there would be no way to have an object of these classes be a data member.

Also, you use the initialization list in inheritance so you can call your base class constructor. That constructor must execute before your derived class constructor starts.

regards,
George
Dec 25 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Fred Ma | last post by:
Are there any reasons that would make it bad for C++ to allow simultaneous declaration and initilization of member data? Current way: ------------ class DerivedClass : BaseClass { { enum {...
3
by: Tran Tuan Anh | last post by:
Dear all, I am new with C++ and very confused with some features. Really appreciate if you can explain to me some of stuffs below. I define a class: class A { static A* instance = 0; };
8
by: Tim Clacy | last post by:
1) Is this initialising the reference 'u' to the address of the literal '2' or to the address 0x00000002? unsigned const& u = 2; 2) What is the different between the initialisation of 'u'...
6
by: markww | last post by:
Hi, I put a static member variable in my class. class CMine { static int m_nCount; }; How do I initialize it to zero? I can't do that in the constructor of the class can I? Won't that...
11
by: asdf | last post by:
The oder of member initialization is the order in which the members are defined. So the following code is problematic: class X{ int i; int j; public: X(int val):j(val),i(j){}
10
by: Dennis Jones | last post by:
Hello, I have a hierarchy of classes in which there will be a data element that is common to all descendant classes. This element (a string in this case) is constant, but specific to each...
10
by: n.torrey.pines | last post by:
Are global variables (and const's) guaranteed to be initialized before static class members (and methods) ? const int x = 19907; int get_x() { return x; } // another compilation unit: ...
15
by: Bob Johnson | last post by:
I have a base class that must have a member variable populated by, and only by, derived classes. It appears that if I declare the variable as "internal protected" then the base class *can*...
15
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
2
by: Peng Yu | last post by:
Hi, I'm wondering if there is a way to initialized a member array just as the initialization of a member variable? Or I have to initialized the array inside the function body of the constructor?...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.