Lets suppose I want to call Class 2 and Class 3 from Class 1... so I have to code this:
In Class1.h
#include Class2.h
#include Class3.h
then I add this:
on public slots:
void openClass2();
void openClass3();
on private:
Class2 * window2;
Class3 * window3;
on private slots:
void on_button2_clicked();
void on_button3_clicked();
then on Class1.cpp
void:Class1::on_button2_clicked(){ //If I click the button 2 then the window 2 shows up
openClass2();
}
void Class1::openClass2{
window2 = new Class2 (this);
window2->show;
}
void:Class1::on_button3_clicked(){ //If I click the button 3 then the window 3 shows up
openClass3();
}
void Class1::openClass3{
window2 = new Class2 (this);
window2->show;
}
The problem is that I don't know how to simplify openClass2 and openClass3 in the same method, so I don't have to create one for each window... I haven't worked much with classes before... so I'd like if you help me...
My code works, but it wastes too much space since it repeats the same thing...
I have the idea that I need to add something between the parenthesis of the declaration of the method in the .h file , but I have tried everything and doesn't work :p!
You could do that with a bit of templates and pointers to pointers, but why would you? The functions are 2 lines long. Did you omit all of the repetitive stuff? If you didn't, keep it as it is. It won't get any shorter or prettier than now.
I mostly agree with hamsterman, but strictly speaking, class2 and class3 has a common base, therefore you can create a base class for them that defines/provides the show() method or any other common methods.
But note that if it is only show(), you pretty much gain nothing right now because you cannot code a unified method to instantiate either class as needed (unless you use switch(), but then the code becomes larger).
So have the base class idea in mind if you have more common methods so the base class can provide actual code reuse.
template <typename T>
void Class1::openClass(T*& window) //pointer to reference to modify member variable
{
window = new T(this);
window->show();
}
Then you call it like this in on_button3_clicked for example: openClass(window3);
With template parameter desuction it should work.
Be careful though, as it is template you must put the method in the header file
But note that if it is only show(), you pretty much gain nothing right now because you cannot code a unified method to instantiate either class as needed (unless you use switch(), but then the code becomes larger).