Change base class of existing derivated class - c++

At the moment I'm writing an application which shows level measurement data into some graphs. Always I have date/time on x-axis and data on th y-axis. I use Qwt for this and modified QwtPlotPicker class to show proper time labels. I did this by derivation and redefining a member function:
class myQwtPlotPicker : public QwtPlotPicker {
Q_OBJECT
public:
explicit myQwtPlotPicker( QWidget* canvas, bool DateScale = false );
explicit myQwtPlotPicker( int xAxis, int yAxis, QWidget* canvas, bool DateScale = false );
explicit myQwtPlotPicker( int xAxis, int yAxis, RubberBand rubberBand, DisplayMode trackerMode, QWidget* canvas, bool DateScale = false );
virtual ~myQwtPlotPicker() {};
protected:
virtual QwtText trackerTextF( const QPointF &position ) const {
... redefinition of the label text ...
}
};
As you can see I also added a new parameter DateScale which turns date labels on or off. This works perfectly, but there is a class QwtPlotZommer which is derivated from QwtPlotPicker:
class QWT_EXPORT QwtPlotZoomer: public QwtPlotPicker { };
Now, the problem is, how do I get the class QwtPlotZommer to derive from myQwtPlotPicker and not from QwtPlotPicker?
Or course I could edit the Qwt sources, but there has to be a proper way of doing this.
I hope there is a proper way to do this. I would be glad, if someone could help me with this.

Try multiple inheritance:
class myQwtPlotZoomer : public QwtPlotZoomer, public QwtPlotPicker { };

There's no way to change class hierarchy at runtime in C++.

I guess that you should reconsider your design - you cannot and should not change the inheritance hierarchy of some library class.
Did you look at some examples to see how the classes you mentioned are intended to be used? Perhaps you should ask a new question to find out how to solve the problem you are actually facing (i.e. how to create a zoomable plot in qwt if I understand you correctly)

You have to overload QwtPlotZoomer reimplementing trackerTextF(). If you also have a use case of a standalone QwtPlotPicker - not being a QwtPlotZoomer - you have to do it twice:
class YourPicker: public QwtPlotPicker ...
class YourZoomer: public QwtPlotZoomer ...
As your implementation is a one-liner I don't see a problem in writing it twice, but if you want to avoid that, you have to put the code to some other class, that is called in both overloaded methods.

Related

Qt and C++: Overwrite or Expand Class

I want to add some properties (like an ID) to a QPushButton. Therefore, I need to expand or overwrite the class Q_WIDGETS_EXPORT QPushButton : public QAbstractButton
How do I do that?
Thanks for the help.
you dont need to extend the class to just put an id in it ... instead make use of the property system.
as specified in the official doc here:
A property can be read and written using the generic functions QObject::property() and QObject::setProperty(), without knowing anything about the owning class except the property's name.
you just have to do:
ui->myButton->setProperty("Id", 123456);
can also be another object e.g a string (or even your own class if you define it to do that)
ui->myButton->setProperty("_name", "123456");
to read the property is the method property() there for you but read the doc because you get a QVariant as return example:
QVariant(int, 123456)
It really depends on the use case. There is no problem (and often the intended way) in inheriting from Qt-(Widget) Classes (correct me, if I am wrong).
So you could do:
class MyQPushButton : public QPushButton
{
Q_OBJECT
public:
MyQPushButton() : QPushButton(...) {}
private:
int ID = -1;
}
Qt has a very good documentation and you can look at the sources to see what to override.
You could also extend a new class with QPushButton, but than you always have to deal with the QPushButton reference in your class, if you want e.g. connect something. In the inherited class you can connect the slots and so on. But for example you could do this:
class MyQPushButton
{
public:
MyQPushButton() {}
const QPushButton& const GetQPushButton() { return pushButton; }
const QPushButton* const GetQPushButtonPtr() { return &pushButton; }
private:
QPushButton pushButton;
int ID = -1;
}
There is no right and wrong. But I would use the inheritance for Qt-classes.

I cant acces functions of a base class

Currently, I am learning c++ and just for fun, I wanted to code a little chess game (without an AI of course). I use visual studio community aside and SFML 2.5 as a renderer and for graphical objects. I tried to make a model called "figure" for all figures. So I have a figure class that inherits from sfml sprite (a drawable) and a pawn class f.e. that inherits from the figure. Sf:: sprite -> figure-> pawn/queen/tower etc... but for some reason, I can't use the pawn as a sprite, for example, I can't draw it with the draw function of my windowRenderer.
But the function documentation says it requires a drawable object. I get an error message that says something like: the conversation in the base class that is not accessible is not valid. Have I done something wrong or is it not possible to use a sprite like this. Here are my constructors because I think I its most likely I made an error there. I have only coded in java so far so the separation into header and implementation file is a little foreign for me also the constructor syntax is different.
figure.h:
class figure : sf::Sprite {
public:
figure(int startPosition);
void changeImage(std::string);
void dissapear();
void loadImage(std::string);
private:
sf::Image img;
};
figure.cpp:
figure::figure(int startPosition):sf::Sprite(){
}
pawn.h:
class pawn :
public figure
{
public:
pawn(int startPosition);
~pawn();
private:
void move(bool canBeat, bool isAsStart);
};
pawn.cpp:
pawn::pawn(int startPosition):figure (startPosition)
{
}
in main.cpp:
pawn pawn1(position);
sf::RenderWindow window(sf::VideoMode(sets.windowX, sets.windowY), "frame");
window.draw(pawn1);
Try this
class figure : public sf::Sprite
Inheritence for classes is private by default.

Does cocos2d-x force multiple inheritance?

I have a class,
class Ticket : public cocos2d::CCNode, public cocos2d::CCTargetedTouchDelegate { ... };
Which works fine when I register for touch events on that node using:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
However, if I alter my class so that it uses composition rather than inheritance for the CCNode bit:
class Ticket : public cocos2d::CCTargetedTouchDelegate {
private:
cocos2d::CCNode* node_;
public:
Ticket() { node_ = new CCNode(); node_->init(); }
cocos2d::CCNode* node() { return node_; }
...
};
Then the following blows up with a SIGSEGV 11:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
I have added ticket_->node() to the current layer, but I am wondering if the touch dispatcher somehow doesn't like the node and the delegate to be different things. Or to put it another way, is touch dispatcher is expecting the node and the delegate to be the same thing?
So in short, my code works when I use multiple inheritance, but it doesn't when I use composition. Without delving into the framework, can anyone say that this is true, or have I just missed something obvious? I am using cocos2d-2.1rc0-x-2.1.2
Yes, it seems cocos2d-x indeed does force multiple inheritance. It expects the touch delegate to be dynamically castable to a CCObject, which your Ticket class isn't when you use composition. When you inherit from CCNode, which itself inherits from CCObject, you're in the clear. You can see the problem here on github.
This does not seem to be a mistake though, since the documentation actually hints at this by noting
IMPORTANT: The delegate will be retained.
for CCTouchDispatcher::addTargetedDelegate.

C++ How can achieve this Interface configuration?

I certainly don't know how to title this question, sorry.
I'm having some problems to design the following system.
I need a class which will make some work, but this work can be done in a bunch of different ways, say that this work will be made through "drivers".
These drivers can have different interfaces and because of that I need to build a wrapper for each driver.
So I got (or I need) this:
Me ---> MainClass ----> Wrapper ----> Drivers
MainClass is the class I will touch and will call the drivers methods through different wrappers.
Here an example of usage:
MainClass worker;
worker.set_driver("driver_0");
worker.start_process(); //Start process calls a wrapper method which calls a driver's method.
To achieve this I made an interface class:
class Driver_Interface : public QObject
{
Q_OBJECT
public:
Driver_Interface(QObject* parent=0) : QObject(parent){}
virtual bool open()=0;
virtual bool close()=0;
virtual bool write()=0;
virtual bool set_config()=0;
};
A driver wrapper has this shape:
class Driver0 : public Driver_Interface
{
Q_OBJECT
public:
Driver0( QObject* parent=0);
Driver0();
bool open();
bool close();
bool write();
bool set_config();
};
Finally here comes the conflicting point, defining the MainClass:
I would like to avoid to create one member for each wrapper, so I tried this, and right now compiler doesn't complains:
class MainClass
{
public:
MainClass();
~MainClass();
void init();
void set_driver( const QString& );
void start_process();
protected:
QString driver_str;
Driver_Interface* driver; //!<--- Here Here!!!
};
When setting the driver chosen, I do this:
if( driver_str.compare("driver_0")==0 )
this->driver = new Driver_0();
Is this a valid C++ configuration or will I have problems sooner or later?
Basically, what worries me is the creation of the driver of a different type from Driver_Interface, I'm seeing that it casts automatically and no one complains...
Actually I have some problems now compiling, the infamous vtables not defined in Driver_0... does this have some relation with what I want to achieve? UPDATED: I fixed this by deleting the *Driver_Interface* constructor.
To me your basic idea seems to be fine. I would consider separating the creation of drivers into a factory (or at least a factory method) though.
This seems reasonable to me. Having a FactoryMethod or class (AbstractFactory) that creates an object of the required concrete subclass based on some config value is a common pattern.
You could consider having the MainClass implement something like
DriverInterface* createDriver(const string& driverType)
instead of encapsulating the resulting concrete DriverInterface subclass in MainClass. But if you only ever want one concrete DriverInterface instance, the above looks fine.
I would pass "driver_0" to the constructor, and call MainClass::set_driver from there. You can then make MainClass::set_driver private unless you need to change drivers.

supplying dependency through base class

I have a list of Parts and some of them need a pointer to an Engine, lets call them EngineParts. What I want is to find these EngineParts using RTTI and then give them the Engine.
The problem is how to design the EnginePart. I have two options here, described below, and I don't know which one to choose.
Option 1 is faster because it does not have a virtual function.
Option 2 is easier if I want to Clone() the object because without data it does not need a Clone() function.
Any thoughts? Maybe there is a third option?
Option 1:
class Part;
class EnginePart : public Part {
protected: Engine *engine
public: void SetEngine(Engine *e) {engine = e}
};
class Clutch : public EnginePart {
// code that uses this->engine
}
Option 2:
class Part;
class EnginePart : public Part {
public: virtual void SetEngine(Engine *e)=0;
};
class Clutch : public EnginePart {
private: Engine *engine;
public: void SetEngine(Engine *e) { engine = e; }
// code that uses this->engine
}
(Note that the actual situation is a bit more involved, I can't use a simple solution like creating a separate list for EngineParts)
Thanks
Virtual functions in modern compilers (from about the last 10 years) are very fast, especially for desktop machine targets, and that speed should not affect your design.
You still need a clone method regardless, if you want to copy from a pointer-/reference-to-base, as you must allow for (unknown at this time) derived classes to copy themselves, including implementation details like vtable pointers. (Though if you stick to one compiler/implementation, you can take shortcuts based on it, and just re-evaluate those every time you want to use another compiler or want to upgrade your compiler.)
That gets rid of all the criteria you've listed, so you're back to not knowing how to choose. But that's easy: choose the one that's simplest for you to do. (Which that is, I can't say based of this made-up example, but I suspect it's the first.)
Too bad that the reply stating that 'a part cannot hold the engine' is deleted because that was actually the solution.
Since not the complete Engine is needed, I found a third way:
class Part;
class EngineSettings {
private:
Engine *engine
friend class Engine;
void SetEngine(Engine *e) {engine = e}
public:
Value* GetSomeValue(params) { return engine->GetSomeValue(params); }
};
class Clutch : public Part, public EngineSettings {
// code that uses GetSomeValue(params) instead of engine->GetSomeValue(params)
}
Because GetSomeValue() needs a few params which Engine cannot know, there is no way it could "inject" this value like the engine pointer was injected in option 1 and 2. (Well.. unless I also provide a virtual GetParams()).
This hides the engine from the Clutch and gives me pretty much only one way to code it.