Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

foo(int a): b(a) {} What is this sintax??

Status
Not open for further replies.

jmborr

Instructor
Feb 16, 2004
7
0
0
US
Hi
Here's a sintax in the constructor I've never seen, nor can I find an explanation:
class foo{
public:
foo(int a): b(a) {} //the constructor
private:
int b;
};
One could define foo(int a){ b=a; }. Why the different definition?
jmborr
 
It's called an Initialization List.
It's more efficient, since it doesn't need to create any temporary variables to hold the values being passed to the constructor.
 
Great! Many thanks for the info.

-jmborr
 
Actually, I don't think that is the reason it is more efficient.

It is better because it does exactly what you are trying to do. It initializes the member variables and base classes.

It is also generally more efficient for non-POD types because it avoids a default construction followed by an assignment in favor of a direct construction.

For example, if a and b were strings, then that code would construct b with the contents of a. The alternative { b=a } would construct an empty string b (which might allocate some memory), then assign a to b, which might require the original memory to be deallocated and larger memory to be created to fit the contents of a.

For built-in and POD types like int, the values are left uninitialized if they are not found in an initialization list, so the assignment { b=a } is just as efficient as the initialization list. However, most people advise to use the initialization list anyway for consistency and clarity of intent.

More information: specifically FAQ #10.6.
 
PIntialization lists in derived classes can also call the constructors of the base/super classes with passed information before the body of the current class's constructor. It allows you to build this object on a certian instance of the base class, not just calling the default constructor and repeating the code to create the base classes... In this way it can act like Java's super() method.

Aside from all that, it also brings to the fore the programmer's holy obligation to initialize the variables in the base classes and bring the parent objects into a viable state, which may be unset or set by the default constructor and reset by the programmer if we don't use the initalization list.

[plug=shameless]
[/plug]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top