Reputation: 1485
I am dealing with a class that I cannot tamper with. This is basically what I have:
class Base
{
public:
static Base factoryBase()
{
return Base();
}
protected:
Base() {};
Base(Base const & other) { }
Base & operator=(Base const & other) { return *this; }
};
In essence I have a static factory method, to instantiate the Base
class.
In my part of the code I want to do this
Base b = Base::factoryBase();
but this fails because the copy constructor and assignment operator are protected
. I can only assume that they are so, so that I can use them in a derived class.
How should I go about it though?
class Derived : public Base
{
public:
Derived()
{
//Base::factoryBase(); //what do I do here and how do I store the result?
}
};
I am unsure how to assign the result of Base::factoryBase() to the Derived class itself. Is it even possible? How else am I supposed to use the fact that the constructors and assignment operators are protected
?
note: compilation is done with earlier that c++11 versions. Thank you for your help
Upvotes: 2
Views: 872
Reputation: 51
You could call operator=
directly in the derived class:
Derived()
{
Base::operator=(Base::factoryBase());
}
Upvotes: 1
Reputation: 217135
You may still do:
class Derived : public Base
{
public:
Derived() : Base(/*Base::factoryBase()*/) {}
// Not really useful, but for demonstration
static Derived factoryDerived() { return Derived(); }
};
And then
Derived d = Derived::factoryDerived();
Upvotes: 3