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?
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.
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 ...
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.
The members of base aggregate class cannot be individually initialized in the constructor of the derived class.
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)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With