Search code examples
c++classassignment-operatordefault-constructor

Dealing with private default constructor


I'm working with a library which has a class X, whose default constructor is declared private.

Note that class X supports assignment operator.

I want to implement a class which includes class X.

class MyClass
{
    X x;
    Y y;
    Z z;
public:
    MyClass(X xv, Y yv, Z zv);
};

My purpose for implementing this class is that I've to insert this triplet value into a list.

But I'm not able to implement this class as the default constructor of X is declared private, also I won't prefer meddling with code of X as rest of the library functions depend on it.

Can I use the fact that class X has an assignment operator, to achieve what I want? Thanks.

Edit 1: There is no other constructor available for that class.


Solution

  • There is almost certainly a copy constructor. (It would be a very strange class that had an assignment operator but not a copy constructor.) If the class author has not declared a copy constructor, the compiler will create one for them.

    Your problem is that you are writing:

    MyClass::MyClass(X xv, Y yv, Z zv)
        // x, y, z default constructed here.
    {
        x = xv; y = yv; z = zv;
    }
    

    What you need, is to copy construct x,y,z directly (look up "initializer list". So:

    MyClass::MyClass(X xv, Y yv, Z zv)
    : x(xv), y(yv), z(zv)
    {
    }
    

    Having said that, you are passing xv etc by value. It would be much more natural to write it as:

    MyClass::MyClass(const X& xv, const Y& yv, const Z& zv)
    : x(xv), y(yv), z(zv)
    {
    }
    

    (and change the declaration as well of course)