nass
nass

Reputation: 1485

c++ How can I use a protected assignment operator to do an assignment?

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

Answers (2)

Graphene
Graphene

Reputation: 51

You could call operator= directly in the derived class:

Derived()
{
    Base::operator=(Base::factoryBase());
}

Upvotes: 1

Jarod42
Jarod42

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

Related Questions