Chaining constructors in c++

Started by
9 comments, last by Zahlman 15 years ago
I googled this topic, and apparently this is syntacticly allowed, but doesn't work properly, I'm wondering if I can get some confirmation of this.
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
Advertisement
That depends on what you mean by "chaining constructors".
having a constructor (say a no-arguement constructor) internally call another constructor to avoid code duplication. I'll give an example.

class Point2D
{

float x,y;

public:

Point2D(float x, float y)
{
this->x = x;
this->y = y;
}


Point2D()
{
this(0,0); //or Point2D(0,0) , i'm not sure whch c++ would use

}


};
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
clicky
However see also this.
In your simple example you can give the parameters default values. e.g.

class Point{public:    float x,y;    Point(float x = 0.0f, float y = 0.0f)        : x(x), y(y){}};


You could also use named constructors as in C++ FAQ lite explained or wait for C++0x. ^^
Quote:Original post by megamoscha
In your simple example you can give the parameters default values. e.g.

class Point{public:    float x,y;    Point(float x = 0.0f, float y = 0.0f)        : x(x), y(y){}};

Careful there. That expands out to THREE constructors, taking from zero to two arguments. And the one-constructor one will act as an implicit conversion constructor. Which means that code like Point p(1,2); p = p + 3; will compile fine, and almost certainly do something you weren't expecting. As a rule of thumb, any constructors that can take exactly one argument should be declared explicit, unless you actually want that behavior.
Ah good point, never thought about that. I'm anyway for named constructors, because it makes it clear what is meant.
Quote:Original post by SiCrane
However see also this.


This technique can also be used in pre-0x C++, if you make a dummy base class (although in most cases it won't really save you any work):

struct PointBase {  float x, y;  PointBase(float x, float y): x(x), y(y) {}};struct Point: PointBase {  Point(float x, float y): PointBase(x, y) {}  Point(): PointBase(0, 0) {}};
thanks a lot for the help guys. *--- I believe(but I could be wrong) that some way of constructor chaining may be included in the C++ 0x specs, but since the website didn't mention a specific source, I can't confirm.--* - *EDIT* I should have read the improving construction from one of those links before i said this, as it mentions it as well

I've been trying to apply some of the techniques i've been learning in school to my c++ programming to clean my code up a little, and just generally adhere to better software engineering principles.
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried

This topic is closed to new replies.

Advertisement