Topic: Constructor calling a sibling


Author: dwalker07@snet.net.invalid (Daryle Walker)
Date: 2000/05/08
Raw View
Sorry if this has been discussed a ridiculous-high amount of times
already in this newsgroup.  I thought of this when seeing some questions
on c.l.c++.

Posters in that group were commenting on how you can't have a
constructor use a sibling constructor to do work.  The best you can do
is to factor the common code into a (private) method.  Unfortunately,
that paradigm prevents any optimizations from using an initializer list
instead of a call from the constructor body.  My thought would to the
initializer list call a sibling constructor:

//====================================================
class MyClass
{
private:
    int x_, y_;
public:
    MyClass( const int &x, const int &y );
    MyClass( const int &y );
};

MyClass::MyClass( const int &x, const int &y )
    : x_(x), y_(y)
{
}

MyClass::MyClass( const int &y )
    : MyClass(0, y)
{
    std::cout << "Hi there";
}
//====================================================

Note that:

1.  The sibling constructor call is the only item in the initializer
list.  Since the sibling will already call constructors for the base
classes and member objects, you must not call them again.

2.  You are limited to the sibling constructor call do all of its work
before anything in the current constructor's body gets executed, just
like regular initializer lists.

3.  The sibling constructor uses the same name as the class, like any
other constructor.  This prevents the pathological case of a class data
member from having the same name as the class.  If this was never
allowed anyway, never mind.

4.  Even though I didn't have it, you can still have the try-catch stuff
like in other constructors.  And you still have to structure the
arguments so it can resolve to the constructor you want.

--
Daryle Walker
Video Game, Mac, and Internet Junkie
dwalker07 AT snet DOT net

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]