I have the following situation where I have a base class and multiple polymorphics derived classes:
#include <iostream>
class Base {
public:
virtual void foo() = 0;
};
class Derived1 : public Base {
public:
virtual void foo() { std::cout << "Derived1::foo()\n"; };
};
class Derived2 : public Base {
public:
virtual void foo() { std::cout << "Derived2::foo()\n"; };
};
I want to make sure that my class users will always use the base class to use object of this hierachy. I got the idea to provide a factory methods returning the good object. From now, the methods look like this:
Base&& make_base(int i) {
if(i == 1)
return Derived1();
else
return Derived2();
}
The client can then use it that way:
int main() {
Base&& b = make_base(1);
b.foo();
}
Assuming C++03 compatibility is not needed, is this considered a good practice?
Edit
AS DeadMG pointed out, my initial make_base has undefined behaviour. If I can't require clients to only use Base class, I wish I could recommend it. Is this kind of factory a better idea?
#include <type_traits>
#include <string>
template <class Derived>
Derived make_base() {
static_assert(
std::is_base_of<Base, Derived>::value,
"'Derived' must derived from 'Base'.");
// Default behaviour
return Derived();
}
template <>
Derived2 make_base<Derived2>() {
// Specialise behaviour
// Do something
return Derived2();
}
int main() {
auto b = make_base<std::string>(); // Error, 'Derived' must derived from 'Base'.
Base&& b1 = make_base<Derived1>(); // call make_base()
Base&& b2 = make_base<Derived2>(); // call make_base<Derived2>()
b1.foo();
b2.foo();
}