Thursday, 15 August 2013

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

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?

No comments:

Post a Comment