Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ base class reference initialize with different derived class object

class Base
{
public:
    void operator()() { func(); }
private:
    virtual void func() {}
};

class Derived1 : public Base
{
private:
    void func() override {/*do something*/}
};

class Derived2 : public Base
{
private:
    void func() override {/*do something else*/}
};

Because I want to use operator overloading,
Reference is a better option than pointer.

What I intend to do is like:

if (condition) {
    Base& obj = Derived1();
} else {
    Base& obj = Derived2();
}

But obj will be destroyed and end of scope.

Base& obj;
if (condition) {
    obj = Derived1();
} else {
    obj = Derived2();
}

Will not work either,
Because reference need to be initialized on declaration.

If I try:

Base& obj = condition ?
    Derived1() : Derived2();

Still an error, Because ternary operator expect convertible type.

What is the best solution to deal with this problem?

like image 273
gnephiak Avatar asked Aug 15 '13 12:08

gnephiak


People also ask

What happens when a reference to a derived class object is assigned to a base class reference variable in C#?

Moreover, Object slicing happens when a derived class object is assigned to a base class object, and additional attributes of a derived class object are sliced off to form the base class object.

Can you assign a base class object to a derived class reference?

No, that's not possible since assigning it to a derived class reference would be like saying "Base class is a fully capable substitute for derived class, it can do everything the derived class can do", which is not true since derived classes in general offer more functionality than their base class (at least, that's ...

Why would one create a base class object with reference to the derived class?

One reason for this could be that BaseClass is abstract (BaseClasses often are), you want a BaseClass and need a derived type to initiate an instance and the choice of which derived type should be meaningful to the type of implementation.

Can derived class initialize base member?

The members of base aggregate class cannot be individually initialized in the constructor of the derived class.


1 Answers

You can not use ?: in this case as Derived1 and Derived2 are different types.

One possible way is to use pointer, this is valid:

condition ? pObj.reset(new Derived1()) : pObj.reset(new Derived2());

Or

#include <memory>
std::unique_ptr<Base> pObj;
if (condition)
{
    pObj.reset(new Derived1());
}
else
{
    pObj.reset(new Derived2());
}

You could call operator() this way:

(*pObj)();  
like image 52
billz Avatar answered Oct 06 '22 01:10

billz