473,795 Members | 2,919 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

constructor syntax

65 New Member
i have the code fragment below,
is there anybody to explain me the meaning of this syntax:
BadIndex(int i) : badindex(i) {}

is it the same with this:
BadIndex(int i) {badindex=i; }
if it is the same why the former one is used instead of the latter?

Expand|Select|Wrap|Line Numbers
  1. class BadIndex      // exception class for indexing problems
  2.     {
  3.     private:
  4.         int badindex;   // problematic index value
  5.      public:
  6.         BadIndex(int i) : badindex(i) {}
  7.         virtual void Report() const;
  8.     };
May 29 '07 #1
6 1860
weaknessforcats
9,208 Recognized Expert Moderator Expert
This syntax:
Expand|Select|Wrap|Line Numbers
  1. BadIndex(int i) : badindex(i) {}
  2.  
use the constructor initializer list. Here badindex is created and intialized to i before the constructor starts.

Whereas this syntax:
Expand|Select|Wrap|Line Numbers
  1. BadIndex(int i) {badindex=i; }
  2.  
says to change the value of the existing badindex and make it equal to i.

Remember, when you get to the { of your constructor, the class member variables have already been created and initialized using the default constructors of the member variables. All you can do inside the BadIndex constructor is change things.

The two syntaxes are not equivalent. If the class has a const member, C++ requires that the const have a value at the time the const is created. By the time you reach the { of the constructor, the const member has already been created. You need a way to get a value to the const before the constructor starts. Here is where you use the initializer list.

Expand|Select|Wrap|Line Numbers
  1. class AClass
  2. {
  3.        const int Max;
  4.     public:
  5.        AClass(int theValue);
  6. };
  7.  
  8. AClass::AClass(int theValue) : Max(theValue)
  9. {
  10.  
  11. }
  12.  

A second difficulty arises when you use inheritance. C++ requires the base class portion of your derived object to be initialized before the derived constructor starts. Here, again, you use the initializer list to call the base class constructor.

Expand|Select|Wrap|Line Numbers
  1. class Base
  2. {
  3.        int theData;
  4.        public:
  5.           Base(int theValue);
  6. };
  7.  
  8. Base::Base(int theValue) : theData(theValue)
  9. {
  10.  
  11. }
  12.  
  13. class Derived
  14. {
  15.      public:
  16.         Derived(int theValue);
  17. };
  18.  
  19. Derived::Derived(int theValue) : Base(theValue) //calls Base ctor
  20. {
  21.  
  22. }
  23.  
};


A third difficulty arises when one of your member classes is the object of some other unrelated class and you need to call a constructor of that class becuse that class does not have a default constructor. Again, use the initializer list for this.

Expand|Select|Wrap|Line Numbers
  1. class Date
  2. {
  3.      int month;
  4.      int day;
  5.      int year;
  6.     public:
  7.        Date(int m, int d, int y);
  8. };
  9. Date::Date(int m, int d, int y) : month(m), day(d), year(d)
  10. {
  11.  
  12. }
  13.  
  14. class MyClass
  15. {
  16.      Date dt;
  17.  
  18.      public:
  19.        MyClass(int m, int d, int y);
  20. };
  21.  
  22. MyClass::MyClass(int m, int d, int y) : dt(m,d,y)   //call Date ctor
  23. {
  24.  
  25. }
  26.  
May 29 '07 #2
AdrianH
1,251 Recognized Expert Top Contributor
I agree with everything you said except this:
Remember, when you get to the { of your constructor, the class member variables have already been created and initialized using the default constructors of the member variables. All you can do inside the BadIndex constructor is change things.
The initialiser list is not the default constructor. It is just a list of initialisers that state the initial state of the class prior to executing the constructor's body. I think the reasoning is for increased efficiency of the constructor, and of course everything else you stated.

The basic steps are:
  1. Allocate the object.
  2. Call constructor which does:
    1. Calls base class constructor from initialiser list (if derived from a class).
    2. Init rest of member variables in the initialiser list in the order they appear in the class NOT the order they appear in the initialiser list (I’m not sure ordering is part of the standard or just gnu’s implementation) .
    3. Execute constructor’s body.


Adrian
May 29 '07 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
You are mostly correct. I have modified this quote below so that it is accurate

The initialiser list is not the default constructor. It is just a list of initialisers that state the initial state of the class prior to executing the constructor's body. I think the reasoning is for increased efficiency of the constructor, and of course everything else you stated.

The basic steps are:
Allocate the object.
Call constructor which does:
Calls base class constructor from initialiser list (if derived from a class).
Init rest of member variables in the initialiser list in the order they appear in the class NOT the order they appear in the initialiser list (I’m not sure ordering is part of the standard or just gnu’s implementation) .
Execute constructor’s body.
The initialiser list is not the default constructor. It is just a list of initialisers that provde the initial state of the class members. If the class member is an object of another class, that other class constructor must be called to initialize the member. When the class constructor starts at the {, all of the class data members have already been allocated and their constructors have already been called.




The basic steps are:

Allocate the object member-by-member as they are declared in the class

Call the constructor on each member before allocating the next member.
The correct constructor to call is either a) the default constructor or b) the constructor specified in the initializer list. This ordering is very important. For example, the third member may need the value of the second member in order to initialize itself. Note that fundamental types and pointers do not have a default initial value or a constructor.

Call the class constructor to change the values of any members that are fundamental types or pointers or have not been initialized as yet for whatever reason.

When inheritance is involved, the basic steps above are followed first for the base class and then for the derived class. The initializer list is the only method for the derived class constructor to specify which base class constructor to call.
May 29 '07 #4
AdrianH
1,251 Recognized Expert Top Contributor
You are mostly correct. I have modified this quote below so that it is accurate



The initialiser list is not the default constructor. It is just a list of initialisers that provde the initial state of the class members. If the class member is an object of another class, that other class constructor must be called to initialize the member. When the class constructor starts at the {, all of the class data members have already been allocated and their constructors have already been called.




The basic steps are:

Allocate the object member-by-member as they are declared in the class

Call the constructor on each member before allocating the next member.
The correct constructor to call is either a) the default constructor or b) the constructor specified in the initializer list. This ordering is very important. For example, the third member may need the value of the second member in order to initialize itself. Note that fundamental types and pointers do not have a default initial value or a constructor.
Agreed ordering is very important, that is why I mentioned it in point 2.2.
Call the class constructor to change the values of any members that are fundamental types or pointers or have not been initialized as yet for whatever reason.
Are you referring to point 2.3?
When inheritance is involved, the basic steps above are followed first for the base class and then for the derived class. The initializer list is the only method for the derived class constructor to specify which base class constructor to call.
That would be point 2.1.

I’ve updated my steps to be more detailed. Do these changes make it accurate?

The basic steps are:
  1. Allocate the object.

  2. Call constructor which does:

    1. Calls base class constructor from initialiser list (if derived from a class).

      This can be the base class’s default constructor if you didn’t specify which or one of your choosing.

    2. Init rest of member variables as stated in the initialiser list in the order they appear in the class NOT the order they appear in the initialiser list (I’m not sure ordering is part of the standard or just gnu’s implementation) .

      If you do not explicitly initialise a member variable, then it is initialise it with its default constructor or if it doesn’t have one but does have members that have constructors (and so on) then initialise them in the order they appear in the class.

      If the member variable has no constructor or any of its members have no constructor (and so on) then do nothing with it. Its initial value is undefined.


    3. Execute constructor’s body.


Adrian
May 29 '07 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
If the member variable has no constructor or any of its members have no constructor (and so on) then do nothing with it. Its initial value is undefined.
Looks good except for the above.

If the member variable is a an instance of a class, then you will die with a compile time error for no appropriate constructor.


If the member variable is a fundamental type or a pointer, then your statement is correct.
May 29 '07 #6
AdrianH
1,251 Recognized Expert Top Contributor
Looks good except for the above.

If the member variable is a an instance of a class, then you will die with a compile time error for no appropriate constructor.


If the member variable is a fundamental type or a pointer, then your statement is correct.
I don't believe you are correct. Can you create a bit of sample code to show this property?


Adrian
May 29 '07 #7

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

Similar topics

34
3116
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is this in any way used to create singletons. Can someone say how? Cheers, Andy
23
5185
by: Fabian Müller | last post by:
Hi all, my question is as follows: If have a class X and a class Y derived from X. Constructor of X is X(param1, param2) . Constructor of Y is Y(param1, ..., param4) .
18
3004
by: Matt | last post by:
I try to compare the default constructor in Java and C++. In C++, a default constructor has one of the two meansings 1) a constructor has ZERO parameter Student() { //etc... } 2) a constructor that all parameters have default values
24
3786
by: slurper | last post by:
i have the following class sequence { public: sequence (const sequence& mysequence, const int newjob) { job_sequence(mysequence.job_sequence) job_sequence.push_back(newjob); ... }
4
1897
by: Dan Stromberg | last post by:
Hi folks. I'm working on building some software, some of which is written in C++, for a researcher here at the University. I have an extensive background in C and python, but I haven't done much with C++ - I kind of mostly abandoned C++ some time ago, when I coded a project in C++, and some of my coworkers refused to use it -because- it was in C++.
6
2467
by: daveb | last post by:
I'm trying to write some code that calls the constructors of STL containers explicitly, and I can't get it to compile. A sample program is below. One compiler complains about the last two lines (the map constructor calls), saying that I'm trying to take the address of a constructor. Another compiler complains about all four of the last lines, just saying "invalid use of class". What is the correct syntax for calling a container...
74
16038
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
12
7216
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
3
2445
by: mhvaughn | last post by:
struct S1 { int i; }; struct S2 { S1 s; // version 1 S2() {} ; // version 2
3
1530
by: willo | last post by:
Greetings all, I have run into a small problem with my understanding of some C++ language syntax, and seek some clarification. Below is a condensed version of some code I'm having difficulty with: =============================================================== #include <cstddef// size_t
0
9673
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10443
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10165
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10002
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7543
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.