Hi.
Before all, please excuse me for bad english and for very newbie
questions. I hope to don't boring you.
I'm trying to write a very simple GUI using openGL.
So I'm writing some different widgets classes, like buttons, images,
slider, etc...
Each class has a draw() method.
The idea is to put all widget to draw in a vector, and after, in pseudocode:
-----------------------------
for each widget w in vector:
w.draw()
-----------------------------
So I should declare the vector, like
vector<widget> widgetList;
and this is my trouble: I've different classes (that has some common
methods, like draw(), on(), off() etc...) and I should put all in one
std container. It's possible?
Really I don't know even how to declare the vector. In example, if I've
the class
----------------------------
class foo {
private:
int width;
int height;
public:
int getWidth();
int getHeight();
};
----------------------------
how to declare a container for foo? Surely not writing
vector<foo> fooList;
Should I use typedef? Can you explain me this?
I know I'm a newbie and maybe these are very silly questions. However I
can't find these info on the books I'm reading (they are for beginners,
and don't write about STD) and the same using google.
Can you help me?
Thanks,
Manuel 20 5051
Manuel wrote: I'm trying to write a very simple GUI using openGL. So I'm writing some different widgets classes, like buttons, images, slider, etc...
Each class has a draw() method.
The idea is to put all widget to draw in a vector, and after, in pseudocode:
----------------------------- for each widget w in vector: w.draw() -----------------------------
Look at Design Pattern called Composite which can be used to wrap such
structure easily. GoF's book [1] includes case study very similar to
your problem so you may find this book intersting.
Simply, create abstract base class i.e. Widget and
inherit concrete (specialized) gadgets from the Widget.
Declare in Widget pure virtual method i.e. void draw(canvas)
and implement it in every concrete widget suitably.
Finally, store all widgets in a container through pointer to the base
class Widget (dynamic polymorphism).
So I should declare the vector, like
vector<widget> widgetList;
and this is my trouble: I've different classes (that has some common methods, like draw(), on(), off() etc...) and I should put all in one std container. It's possible?
Yes, do it as I explained above.
Here is simple implementation which should help to understand that idea:
#include <algorithm>
#include <iostream>
#include <vector>
////////////////////////////////////////////////////////////
struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};
////////////////////////////////////////////////////////////
class Widget
{
public:
virtual void draw() const = 0;
virtual ~Widget() {}
};
class Button : public Widget
{
public:
void draw() const { std::cout << "Drawing Button" << std::endl; }
};
class Label : public Widget
{
public:
void draw() const { std::cout << "Drawing Label" << std::endl; }
};
class Slider : public Widget
{
public:
void draw() const { std::cout << "Drawing Slider" << std::endl; }
};
int main()
{
std::vector<Widget*> v;
v.push_back(new Button());
v.push_back(new Label());
v.push_back(new Slider());
v.push_back(new Button());
std::vector<Widget*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->draw();
}
// Delete widgets
std::for_each(v.begin(), v.end(), DeleteObject());
return 0;
}
////////////////////////////////////////////////////////////
[1] Design Patterns: Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Mateusz Łoskot wrote: Look at Design Pattern called Composite which can be used to wrap such structure easily. GoF's book [1] includes case study very similar to your problem so you may find this book intersting.
Simply, create abstract base class i.e. Widget and inherit concrete (specialized) gadgets from the Widget. Declare in Widget pure virtual method i.e. void draw(canvas) and implement it in every concrete widget suitably. Finally, store all widgets in a container through pointer to the base class Widget (dynamic polymorphism).
Thanks you very much for the example!!
Some questions:
1) What happen if I use v.clear() instead DeleteObject() ??
2) In your example each class has the same number of methods. But what
happen if some classes have different numbers of methods? Should be not
a problem, right ??
3) Exist other way instead using a pointer in std::vector<Widget*> v; ??
Again, thanks, THANKS!
Ciao,
Manuel
Manuel wrote: Thanks you very much for the example!!
You're welcome!
Some questions:
1) What happen if I use v.clear() instead DeleteObject() ??
Look at older thread titled "STL map and memory management (clear() )",
about Dec, 15.
2) In your example each class has the same number of methods. But what happen if some classes have different numbers of methods? Should be not a problem, right ??
No problem. But remember that only common members may be accessed during
iterations (without casting). I mean, when iterating you "can see" all
widgets "through" base class interface - Widget.
Just a figurative explanation :-)
3) Exist other way instead using a pointer in std::vector<Widget*> v; ??
In your particular solution I don't see anything better - abstract base
class allow you to access specialized types through unified interface
(declared in base class). I strongly recommend you to read GoF's
explanation of Composite, then may be you will get the idea behind it
more clear.
Note: you can use "smart pointers" instead of raw pointers. Then memory
management is much simplier. Here they are: http://www.boost.org/libs/smart_ptr/smart_ptr.htm
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Mateusz Łoskot wrote: You're welcome!
[...] Look at older thread titled "STL map and memory management (clear() )", about Dec, 15.
[...]I strongly recommend you to read GoF's explanation of Composite, then may be you will get the idea behind it more clear.
Note: you can use "smart pointers" instead of raw pointers. Then memory management is much simplier. Here they are: http://www.boost.org/libs/smart_ptr/smart_ptr.htm
THANKS!!
I'll study your suggestions and trying some experiments before boring
you with other newbie questions.:-)
Best Regards,
Manuel
Manuel wrote in message <43**********************@reader1.news.tin.it>.. . Mateusz Łoskot wrote:
Some questions:
1) What happen if I use v.clear() instead DeleteObject() ??
You would leave objects in memory with no way to delete them. If you want to
use 'v.clear()', you can do it this way:
int main(){
std::vector<Widget*> v;
Button Btn;
v.push_back( &Btn );
Label Lbl;
v.push_back( &Lbl );
// .... etc. ....
std::vector<Widget*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it){
(*it)->draw();
}
v.clear() // vector will empty at this point.
Label Lbl2;
v.push_back( &Lbl2 );
v.clear() // vector will empty at this point.
return 0;
} // Btn, Lbl, etc. destructors will be invoked at this point.
Also read what Mateusz suggested.
Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to handle
the pattern (which he calls the 'Command pattern' ). You can download a legal
copy of the book here: http://www.bruceeckel.com/ [ref: //:
C10:CommandPattern.cpp ]
--
Bob R
POVrookie
BobR wrote: Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to handle the pattern (which he calls the 'Command pattern' ). You can download a legal copy of the book here: http://www.bruceeckel.com/ [ref: //: C10:CommandPattern.cpp ]
Thanks...a lot of things to read :-)
POVrookie
Curiosity: Are you POVray user?
Ciao,
Manuel
Manuel wrote: Mateusz Loskot wrote:
You're welcome! [...] Look at older thread titled "STL map and memory management (clear() )", about Dec, 15. [...]I strongly recommend you to read GoF's explanation of Composite, then may be you will get the idea behind it more clear.
Note: you can use "smart pointers" instead of raw pointers. Then memory management is much simplier. Here they are: http://www.boost.org/libs/smart_ptr/smart_ptr.htm
THANKS!! I'll study your suggestions and trying some experiments before boring you with other newbie questions.:-)
I recommend you use a deep copy (clone) smart pointer, instead. http://code.axter.com/copy_ptr.h
or a COW smart pointer http://code.axter.com/cow_ptr.h
Both the copy_ptr and the cow_ptr can perform a deep copy when needed.
Example usage:
vector<copy_ptr<foo> > vFoo;
vFoo.push_back(new FooDerived);
You can use the boost::shared_ptr only if you're sure sharing the
pointee will not negatively effect your code. In most cases, this is
rarely what you want in a container.
Boost also has a set of pointer containers, but the interface is poor,
and does not match the STL containers very well.
I recommend using copy_ptr or cow_pt instead.
For more information, read the following related Article: http://www.codeguru.com/cpp/cpp/algo...le.php/c10407/
In the above article it uses a clone_ptr smart pointer, but the
copy_ptr is a more optimize and complete version of the clone_ptr class.
Manuel wrote in message <43**********************@reader3.news.tin.it>.. . BobR wrote: Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to
handle the pattern (which he calls the 'Command pattern' ). You can download a
legal copy of the book here: http://www.bruceeckel.com/ [ref: //: C10:CommandPattern.cpp ]
Thanks...a lot of things to read :-)
POVrookie
Curiosity: Are you POVray user?
Yes. I am still a POVray rookie because I have been spending more time
learning C++.
One of my current projects is for POVray (though it also outputs OGL, RAW,
RAD, OBJ, TIN, RIB). It makes a 3D Rock (as triangle mesh) and
displays/animates in a OpenGL window in wxWidgets.
Some people think that POV is Point-Of-View, and I just answer them with a
smiley-face :-}
--
Bob R
POVrookie
--
POVray: http://www.povray.org/
Can you explain me (please be patient) because this structure
struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};
instead a function like
DeleteObject( *ptr){ delete ptr; };
??
Thanks,
Manuel
Manuel wrote: Can you explain me (please be patient) because this structure
struct DeleteObject { template <typename T> void operator()(const T* ptr) const { delete ptr; } };
instead a function like
DeleteObject( *ptr){ delete ptr; };
Easy: the function misses a type. Either you fix the type for
'ptr', or you make a function template DeleteObject<T>.
Now, if you want to delete every pointer in the range
container.begin(), container.end(), you need to pass the
correct deleter. The struct can delete all pointer types,
but the function (or an instantiation of the function template)
can delete only one type (in the functio template case,
the type it's instantiated with).
In practice, this means the function form needs a <TYPE>
argument. This may be a complicated expression which
must match exactly the type already known to the compiler.
That's just a game of 'guess what I'm thinking', not useful.
HTH,
Michiel Salters
Manuel wrote: Can you explain me (please be patient) because this structure
struct DeleteObject { template <typename T> void operator()(const T* ptr) const { delete ptr; } };
This is a Function Object (Functor) - read about in a book or Web.
Second, it also is a kind of "universal" Functor which can be
specialized to call delete on all types of pointers.
instead a function like
DeleteObject( *ptr){ delete ptr; };
This is a function (not complete definition, type is missing:
void DeleteObject(MyClass *ptr){ delete ptr; };
In the form above, it's (almost) like a specialized version of the
Functor - operates on one and the only one type - specialized with MyClass.
Template version is more flexible, you can use it for every*** type of
pointers in your container - one Functor for all (almost***).
*** - as you can see how delete operator is used then you see that it
can not be used to delete arrays (delete[] pointer_to_array).
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Thanks!
The functors are very advanced features, I must study a lot before fully
understand them...
However thanks to you now I've at least an idea about how the code work.
Thanks,
Manuel
Manuel wrote: Thanks! The functors are very advanced features, I must study a lot before fully understand them...
Yup! They are worth to learn, definitely.
Especially, when you use STL stuff like algorithms.
However thanks to you now I've at least an idea about how the code work. Thanks,
You're welcome.
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Ehm...I don't understad another error about this topic.
Using the code below:
----------------------------
#include <iostream>
#include <vector>
using namespace std;
class mhwidget {
public:
virtual void draw() const = 0;
};
class square : public mhwidget {
public:
void draw(){cout << "square!";}
};
class MHwindow {
vector<mhwidget*> widgetList;
public:
void addWidget(mhwidget* w) {cout << "added!";}
};
int main (){
MHwindow MHgui;
MHgui.addWidget(new square);
return 0;
}
-----------------------------
The compiler return this error:
In function `int main()':
cannot allocate an object of type `square'
because the following virtual functions are abstract:
virtual void mhwidget::draw() const
Deleting "const" it work...I'm trying to find the reason of this on
various books, but without success...
Ciao!
Manuel
Manuel wrote: Ehm...I don't understad another error about this topic. Using the code below:
---------------------------- #include <iostream> #include <vector> using namespace std;
class mhwidget { public: virtual void draw() const = 0; };
OK, but most likely you need to add public virtual destructor:
virtual ~mhwidget();
class square : public mhwidget { public: void draw(){cout << "square!";} };
Here is the problem.
Look, this declaration
void draw() const;
is not the same as thisone:
void draw();
The former declares const-member-function, the latter
non-const-member-function.
And this is what your compiler does not like, the confusion :-)
So, you need to define it this way (as a const function):
void draw() const {cout << "square!";}
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Mateusz Łoskot wrote: The former declares const-member-function, the latter non-const-member-function. And this is what your compiler does not like, the confusion :-) So, you need to define it this way (as a const function): void draw() const {cout << "square!";}
Ouch!
I'm stupid!
Sorry for !!another!! silly question!
Manuel wrote: Mateusz Łoskot wrote:
The former declares const-member-function, the latter non-const-member-function. And this is what your compiler does not like, the confusion :-) So, you need to define it this way (as a const function): void draw() const {cout << "square!";} Ouch! I'm stupid! Sorry for !!another!! silly question!
I'd not say that. Just try to understand what compiler is saying and
what his message means.
Cheers
--
Mateusz Łoskot http://mateusz.loskot.net
Mateusz Łoskot wrote: struct DeleteObject { template <typename T> void operator()(const T* ptr) const { delete ptr; } };
I've not fully understand functors yet.
I'm trying to write a generic container class: can I declare the
structure above into the class, and use it writing
std::for_each(v.begin(), v.end(), container::DeleteObject());
If yes...it work with any vector, even from differents classes?
Thanks,
Manuel
Manuel wrote: I'm trying to write a generic container class: can I declare the structure above into the class, and use it writing
This is my experiments:
----------------------------------------------
#include <windows.h>
#include "mhcontainer.h"
#include <iostream>//For debug
struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};
//Put widget into container
void MHcontainer::addWidget(mhwidget* w) { widgetList.push_back(w); }
//Draw all widgets
void MHcontainer::drawAll()
{
std::cout << "size: " << widgetList.size();
std::vector<mhwidget*>::iterator it = widgetList.begin();
while(it != widgetList.end())
{
std::cout << "widget!";
(*it++)->draw();
}
}
//Delete all widgets
void MHcontainer::deleteAll()
{
std::for_each(widgetList.begin(), widgetList.end(), DeleteObject());
}
---------------------------------------
where mhcontainer.h is:
---------------------------------------
#include "mhwidget.h"
#ifndef MHCONTAINER_H
#define MHCONTAINER_H
class mhcontainer
{
private:
bool active = 1;
std::vector<mhwidget*> widgetList;
public:
void setOn(){active = 1;}
void setOff(){active = 0;}
void addWidget(mhwidget*);
void drawAll();
void deleteAll();
~mhcontainer(){};
};
#endif //MHWIDGET_H
---------------------------------------
Maybe OK?
Manuel wrote: Manuel wrote:
I'm trying to write a generic container class: can I declare the structure above into the class, and use it writing
This is my experiments:
Please, don't consider a lot of minor errors (caps, ";", #include,
etc...) in the code I've just posted. I've write it very quickly, only
to ask if the *idea" is correct.
Sorry for errors,
Manuel This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Merlin |
last post by:
Hi
Imagine the following classes (A class diagram will help)
BASE, A, B, C, D, E, F, G.
A, B, C, D, G inherit from BASE.
E, F inherit from D.
|
by: Markus Dehmann |
last post by:
I defined a base class in order to put heterogeneous values into a
standard container: All values that I store in the container are
derived from my base class.
Now when I iterate over the...
|
by: Leslaw Bieniasz |
last post by:
Cracow, 20.09.2004
Hello,
I need to implement a library containing a hierarchy of classes
together with some binary operations on objects. To fix attention,
let me assume that it is a...
|
by: Johan |
last post by:
Hi,
Hi like to create a linked list with a template class ( see below ). How to
make one using the STL container list.
I want to create a linked list with different kind of types i.e....
|
by: Lokkju |
last post by:
I am pretty much lost here - I am trying to create a managed c++
wrapper for this dll, so that I can use it from c#/vb.net, however, it
does not conform to any standard style of coding I have seen....
|
by: jsale |
last post by:
I'm currently using ASP.NET with VS2003 and SQL Server 2003. The ASP.NET app
i have made is running on IIS v6 and consists of a number of pages that allow
the user to read information from the...
|
by: aaragon |
last post by:
Hello everyone,
I would like to know if there is a way to use the std::map to store
different types for one of its two types. That is, I'm trying to use
it as:
typedef...
|
by: PeterAPIIT |
last post by:
Hello all C++ expert programmer,
i have wrote partial general allocator for my container.
After reading standard C++ library and code guru article, i have
several questions.
1. Why...
|
by: raylopez99 |
last post by:
Hello all
Im trying to get the below to work and cannot get the format right.
Its from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx
What it is: Im trying...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: Aliciasmith |
last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: giovanniandrean |
last post by:
The energy model is structured as follows and uses excel sheets to give input data:
1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
|
by: NeoPa |
last post by:
Hello everyone.
I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report).
I know it can be done by selecting :...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM)
Please note that the UK and Europe revert to winter time on...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
| |