PDA

View Full Version : beginner C++ question on constructor syntax.


dinofelis
08-20-2010, 12:50 PM
Hello,

I think I master more or less the ideas behind user-defined constructors in C++. However, I've seen code that does something of which I can guess what it means, but I've not seen the syntax that way. I've learned C++ essentially from the C++ tutorial on http://www.cplusplus.com/doc/tutorial/
and I don't seem to find the construction that is used in other places (meaning: the syntax escapes me).

It goes like follows:

Imagine there's a class defined with a constructor (example taken literally from above-mentioned tutorial:


// example: class constructor
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area () {return (width*height);}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
int main () {
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}



I understand what this does.

However, I've seen constructor definitions more in the kind of:


CRectangle::CRectangle (int a, int b)
:
width(a) , height(b)
{
}


Now, I can GUESS what this does:
probably width(a) is a call to the "width constructor" which is just an integer here, and in the same way: height(b) is a call to the "height constructor".

But I don't know syntactically:

where the ":" after the function declaration comes from,
why this is OUTSIDE the body block {},
why there is a comma "," instead of an end-of-statement ;


I've seen this syntax only with constructors, not with other functions. Is it limited to constructors ?
Is this standard ANSI C++ ?

Thanks!

oracleguy
08-20-2010, 04:19 PM
It is called base member initialization and it applies only to constructors. It is also some times called base member initialization list.

The colon is there to separate the initialization list from the function header. And it is outside of the brackets because it happens before the code in the brackets. There are times were you have to use it such as if you want to set the value of any data members that are declared as constants.

Generally speaking initializing your data members that way is a good idea.