Polymorphism and the new operator [C++] - c++

I am working on an api, which during runtime decides which higher-level api to use, I have many abstract classes, and derived classes for each high-level api, and a context class which provides me with the correct derived classes for the job, using a function (for example):
Mesh* genMesh(data d) { if(m_useA_API) return new A_mesh(d); else return B_mesh(d); }
something like that, now the question is, is it possible to make the code less ugly ? and instead of using methods inside the context class, can I override new operator in the base class to return the appropriate derived class instance?
if not, what are some possible solutions?
tl;dr this is what i'd like to do
Mesh* m = new Mesh(data); // and the base class decides which derived class to use instead of the Context class.
Thanks.

You can not use new as factory, but you could use Implementation Pattern for it:
class Mesh {
std::unique_ptr<MeshImpl> _impl;
public:
Mesh(int data)
: _impl(
m_use_A_API
? new A_mesh(data)
: new B_mesh(data)
) {
}
MeshImpl& get_value() { return *_impl; }
};
Classes A_mesh, B_mesh are different classes that inherited from class MeshImpl and will be initialized by correct way;
Or you can improve your factory code by next way:
move your method genMesh(int) inside class Mesh
make constructors of Mesh private, for be sure that nobody call it directly.

Related

How can I override the member of (->) operator of a base class

Background: I have Qt generated UI classes with no common ancestor. I am subclassing a class (say, "Door") that uses one of these UI classes, and the derived class ("OakDoor") will use a different UI class, although much of the UI elements will have the same name.
Until now I have been hiding the base UI class (i.e the derivied class uses a UI class of different type but the same name) but now need to rely on inheritance to handle cases where the base class does work on the UI classes; hiding doesn't work in this case.
I have already asked about a way to do this using inheritance and got pointed in the direction of using composition. So I am trying to find an efficient way to do this without having to define an access function for every UI element. It's not really composition but I thought it was getting me close for little effort.
class form_container
{
public:
form_container(){};
form_container(Ui_A_Form * form){_form = form;}
~form_container(){ delete _form; }
Ui_A_Form *_form;
Ui_A_Form & operator->()
{
return *_form;
}
};
the idea was then to have Door use this class and OakDoor a subclass of it:
class B_form_container : public form_container
{
public:
B_form_container(Ui_B_Form * form){_form=form;}
~B_form_container(){delete _form;}
Ui_B_Form *_form;
Ui_B_Form & operator->()
{
return *_form;
}
};
So I'm really just shifting the hiding. Anyway the problem seems to be with my overloading of the operator ->().
In my Door class, I have
form_container *_myform;
which is constructed thusly:
_myform = new form_container(new A_Form());
But it won't compile when I try to access anything in an A_Form, for instance the Qt SetupUI function:
_myform->setupUi(_a_widget);
I'm obviously doing something wrong. Would appreciate any help out there - many thanks! (I can see problems when the subclass tries to delete _form in the base class but I'll sort that out later)
Edit: OK this is compiling now (many thanks to #(R Sahu)), but I am not seeing the overloading that I expect. e.g:
class base_class()
{
form_container *_myform;
};
class derived_class(): public base_class()
{
//inherit _myform;
};
//(constructor for derived class)
derived_class()::derived_class()
{
_myform = new B_form_container(new B_form());
(*_myform)->setupUI(new QWidget()); // tries to setupUi on an A_form
}
This is calling form_container::operator->(), presumably because it isn't virtual. If I make it virtual in the base class form_container, the derived class B_form_container complains about the function only differing by return type.
Is there a way around this?
Can I do something like this for instance:
class base : public A_form
{
virtual base * operator->()
{
// not sure how to return ->() operator of A_form
return A_form::operator->(); // ???
}
};
class derived : public base, public B_form
{
virtual base *operator->()
{
return B_form::operator->(); // again???
}
} ;
Another edit: I don't think what I am trying to do is possible anymore. If you can correct me, please do. In the meantime I'm off to write something to process moc output and create classes with access functions which I can override.
_myform = new form_container(new A_Form());
_myform->setupUi(_a_widget);
is not the right syntax to use to access the operator->() function. With that syntax, the compiler expects a member function setupUi() in the class form_container. The right syntax is:
_myform = new form_container(new A_Form());
(*_myform)->setupUi(_a_widget);
// This translates to:
// Invoke the operator->() function on (*_myform)
// Use the return value of the function and call `setupUi()` on the returned pointer.
or
_myform = form_container(new A_Form());
_myform->setupUi(_a_widget);
Also, the function needs to return a pointer, not a reference.
Ui_B_Form* operator->()
{
return _form;
}
As I eventually realised above, this isn't possible. The operator ->() has to return the type upon which it is acting, and for that reason it can't be used as a virtual function.

Using a static method in C++ to implement a factory pattern

I am a relatively new C++ programmer.
In writing some code I've created something similar in concept to the code below. When a friend pointed out this is in fact a factory pattern I read about the pattern and saw it is in similar.
In all of the examples I've found the factory pattern is always implemented using a separate class such as class BaseFactory{...}; and not as I've implemented it using a static create() member function.
My questions are:
(1) Is this in fact a factory pattern?
(2) The code seems to work. Is there something incorrect in the way I've implemented it?
(3) If my implementation is correct, what are the pros/cons of implementing the static create() function as opposed to the separate BaseFactory class.
Thanks!
class Base {
...
virtual ~Base() {}
static Base* create(bool type);
}
class Derived0 : public Base {
...
};
class Derived1 : public Base {
...
};
Base* Base::create(bool type) {
if(type == 0) {
return new Derived0();
}
else {
return new Derived1();
}
}
void foo(bool type) {
Base* pBase = Base::create(type);
pBase->doSomething();
}
This is not a typical way to implement the factory pattern, the main reason being that the factory class isn't typically a base of the classes it creates. A common guideline for when to use inheritance is "Make sure public inheritance models "is-a"". In your case this means that objects of type Derived0 or Derived1 should also be of type Base, and the derived classes should represent a more specialised concept than the Base.
However, the factory pattern pretty much always involves inheritance as the factory will return a pointer to a base type (yous does this too). This means the client code doesn't need to know what type of object the factory created, only that it matches the base class's interface.
With regard to having a static create functions, it depends on the situation. One advantage, as your example shows, is that you won't need to create an instance of the factory in order to use it.
Your factory is ok, except for the fact that you merged the factory and the interface, breaking the SRP principle.
Instead of making the create static method in the base class, create it in another (factory) class.

correct Inheritance/class structure

i want to write a library for linear program solving. Thereby several solvers such as cplex or gurobi are used. What i already have is an interface for each of them (all containing the same functions wrapping them to solver specific code).
Now I want to have a class 'LinearProgram' which can be instantiated e.g. by LinearProgram("cplex") which then invokes the cplex solver.
My first idea was to use a super class 'solver' which is a base class of all solver interfaces containing the respective functions as virtual declarations. But then I get an abstract class which can not be instantiated.
So in LinearProgram i wanted to have a variable Solver which is instantiated depending on the string given in the constructor.
I'm sure a proper solution is quite obvious, but all I can think about in the moment is not satisfying.
Thanks for your help.
This illustrates what you describe:
class Solver {
...abstract base
};
class SolverFactory {
public:
Solver* NewSolverWithName(const std::string& pSolverName);
};
class LinearProgram {
public:
LinearProgram(const std::string& pSolverName) :
d_solver(SolverFactory::NewSolverWithName(pSolverName)) {
}
private:
some_auto_pointer<Solver> d_solver;
};
class cplex_Solver : public Solver {
...
static std::string Name();
};
Solver* SolverFactory::NewSolverWithName(const std::string& pSolverName) {
if (pSolverName == cplex_Solver::Name()) {
return new cplex_Solver();
}
...
}
This is a job for two different design patterns combined.
The first is the Envelope Letter pattern, and the second is the Strategy Pattern.
Keep on with the base class that you currently have and make a derived class that simply forwards the call to an embedded pointer to the base class. The derived class is now something you can freely pass around by value.
The base class could also contain a static member function that returns a pointer to the base class. This static member function would allow you to instantiate a derived class by using a string name to look it up. That provides a convenient way to select an algorithm at runtime.
But people who knew which derived class (which strategy) they wanted could just create one with 'new' and stuff it inside an instance of the envelope class.
You can optionally do away with the envelope class if you decide to just use a shared_ptr to the base class instead.

Static method definition delegated to derived class (c++)

Last year I saw some source code (C++) where its author declares static function in base class, but leaves its definition to derived class. I remember there was constraint that only one derived class was permitted to define aforementioned static function.
I know that it is impossible to override static methods, but this trick is exactly what I need. I just can't make it work in my code :) Does anyone know about this feature?
Lets look why this would be useful. Suppose we have some base class (Shape), and its derived classes (Circle, Triangle...). Suppose Shape is part of my core architecture, and derived classes are treated as plugins. I don't want to change my core architecture in future. So we have:
class Shape
{
//other stuff here
static Shape* Factory();
}
class Circle:Shape
{
//other stuff here
static Shape* Factory();
}
Shape is sort of abstract class, and it will not implement Factory method. Method is implemented by one (and only one) of the derived classes. In implementation derived class will return new instance of itself, so it is just a factory method. This trick allowed its author to use this static method in client class in following way:
class Client
{
public Shape* shape;
public Client();
//other stuff here
}
In implementation of constructor he had something like:
Client::Client()
:shape(Shape::Factory())
{
}
This way he was able to instantiate "right" shape derivation without changing core classes in engine. When he wanted some other shape to be used in core classes he just had to define static Factory method in that derived class (and to remove the existing one in other derived class).
This way we have some sort of "static polymorphism". I can't find anything about this technique on the web. Does it even have a name? I am especially interested if something like this could be achieved in C# language? :)
Thanks in advance, and sorry for my bad English.
What it sounds like you are trying to do is a bit messy in my opinion. It feels like a combination of a Factory class, a Singleton and then trying to squish them all back into your result class hierarchy.
The simplest (not necessarily the best) solution I can think of is forget about having either Circle::Factory() or Shape::Factory() and just have a free function called get_default_shape().
class Shape
{
};
class Circle: public Shape
{
};
Shape * get_default_shape()
{
return new Circle;
}
Client::Client()
:shape(get_default_shape())
{
}
The nice bit about this is that its only the implementation of get_default_shape that needs to include Circle.h, all the definition needs is a forward declaration of the Shape class.
Hmm. I have not seen exactly what you describe. It could be that the piece of code you refer to defined the base class static function in the cpp file containing your derived class.
// definition of Circle class
.....
Shape* Shape::Factory()
{
return new Circle();
}
This is not useful in this example but it could be a useful trick if you want to hide the implementation of a class and only publish an abstract base class (to reduce compile time dependencies). It won't work if the base and derived classes are not in the same dll/exe.
Similar things can be achieved in C# by using an IOC framework, with generics, or by registring a factory delegate in your base class. I tend to prefer generics and delegates.

Clone abstract base class (without meddling with derived)

I'm experiencing a challenging problem, which has not been solvable - hopefully until now. I'm developing my own framework and therefore trying to offer the user flexibility with all the code complexity under the hood.
First of all I have an abstract base class which users can implement, obviously simplified:
class IStateTransit
{
public:
bool ConnectionPossible(void) = 0;
}
// A user defines their own class like so
class MyStateTransit : public IStateTransit
{
public:
bool ConnectionPossible(void){ return true; }
}
Next, I define a factory class. Users can register their own custom state transit objects and refer to them later by simply using a string identifier they have chosen:
class TransitFactory : public Singleton<TransitFactory>
{
public:
template<typename T> void RegisterStateTransit(const string& name)
{
// If the transit type is not already registered, add it.
if(transits.find(name) == transits.end())
{
transits.insert(pair<string, IStateTransit*>(name, new T()));
};
}
IStateTransit* TransitFactory::GetStateTransit(const string& type) const
{
return transits.find(type)->second;
};
private:
map<string, IStateTransit*> transits;
}
Now the problem is (probably obviously) that whenever a user requests a transit by calling GetStateTransit the system currently keeps returning the same object - a pointer to the same object that is. I want to change this.
PROBLEM: How can I return a new (clone) of the original IStateTransit object without the user having to define their own copy constructor or virtual constructor. Ideally I would somehow like the GetStateTransit method to be able to cast the IStateTransit object down to the derived type it is at runtime and return a clone of that instance. The biggest hurdle is that I do not want the user to have to implement any extra (and probably complex) methods.
4 hours of Googling and trying has led me nowhere. The one who has the answer is a hero!
The problem is that you don't have the type information to perform the clone as you only have a pointer to base class type and no knowledge as to what derived types have been implemented and are available.
I think there's a reason that 4 hours of googling haven't turned anything up. If you want IStateTransit to be cloneable you have to have an interface where the derived class implementer provides some sort of clone method implementation.
I'm sorry if this isn't what you wanted to hear.
However, implementing a clone method shouldn't be a big burden. Only the class implementor knows how a class can be copied, given a correct copy constructor, clone can be implemented for a leaf-node class like this:
Base* clone() const
{
return new MyType(*this);
}
You could even macro-alize it; although I wouldn't.
If I understand the problem correctly, you shouldn't insert new T -s into the map, but rather objects that create new T-s.
struct ICreateTransit
{
virtual ~ICreateTransit() {}
virtual IStateTransite* create() const = 0;
};
template <class T>
struct CreateTransit: public ICreateTransit
{
virtual IStateTransit* create() const { return new T(); }
};
And now insert:
transits.insert(pair<string, ICreateTransit*>(name, new CreateTransit<T>()));
And retrieve "copies" with:
return transits.find(type)->second->create(); //hopefully with error handling
It shouldn't be impossible to modify StateTransit<T> so it holds a T of which to make copies of, should the default one not do.
I think the general name for techniques like this is called "type erasure" (derived types "remember" particular types, although the base class is unaware of those).
This problem to me sounds that the abstract factory pattern might be of help. Using this pattern the libraries client can define how your framework builds its types. The client can inject his own subclass of the factory into the framework and define there what types should be build.
What you need is (additionaly)
A base class for the factory
As a client: Derive a concrete factory
A way to inject (as a client) a subtype of the factory into the framework
Call the factory metods to create new types.
Does this help you?