Thursday, May 22, 2008

c++: default initializers

In c++.03 you are unable to call explicitly one constructor within another:

class A
{
    public:
        A(int x, int y) : x(x), y(y) {}
        A(int x) { A(x, 0); }

        int x, y;
}
This will produce compilation errors. As a workaround developers usually use an initialization function that can be called within the constructor:
class A
{
    public:
        A(int x, int y) : {init(x, y);}
        A(int x) {init(x,0);}

        int x, y;

    protected:
        void init(int a, int b) {x = a; y = b;}
}
The idea I got today is to make an abstraction of class data in base struct, derive class from the struct and initialize struct data with it's constructor. This will make things clear and will allow to separate data from its manipulation:
struct A
{
        A(int x, int y) : x(x), y(y) {}

        int x, y;
};

class B : public A
{
    public:
        B() : A(0, 0) {}
        B(int x) : A(x, 0) {}
};

No comments: