General design question

hi!

i'd like to design a class - let's call it CDrawObject - that is able to
contain some data and draw itself.
furthermore i'd like to have a class CDrawMultiObject that is derived from
CDrawObject and can contain objects of type CDrawObject.

i imagine to have the following situation:

CDrawMultiObject            -> base object (i.e. an object manager )
    CDrawObject                -> first element
    CDrawObject                -> secound element
    CDrawMultiObject        -> third element
        CDrawObject                -> first element
        CDrawObject                -> secound element
    CDrawObject                -> fourth element

i would like to be able to call baseobject.GetNoOfElements() which should
return 5 on the one hand on the other i'd like to be able to call
baseobject.Draw() which should call element0.Draw(), element1.Draw(), ...

my question is how to design such a structure.

i have two approches:
the first one using dynamic casts to be able to distinguish between normal
drawobjects and drawmultiobjects,
the secound one implementing at least some sort of interface function in the
base class (i.e. GetNoOfObjects)

i have heard that it is considered a bad programming style using dynamic
casts but on the other hand i do not think that it is a good idea
to implement "GetNoOfObjects" within the base class either.

so what do you think - how to solve this?

thanks, philipp


0
11/13/2003 9:23:30 AM
vc.mfc 33608 articles. 0 followers. Follow

5 Replies
792 Views

Similar Articles

[PageSpeed] 50

Look into composite design pattern.

- sami

"Philipp Huber" <philipp.huber@innval.com> wrote in message
news:bovi9l$t8d$00$1@news.t-online.com...
> hi!
>
> i'd like to design a class - let's call it CDrawObject - that is able to
> contain some data and draw itself.
> furthermore i'd like to have a class CDrawMultiObject that is derived from
> CDrawObject and can contain objects of type CDrawObject.
>
> i imagine to have the following situation:
>
> CDrawMultiObject            -> base object (i.e. an object manager )
>     CDrawObject                -> first element
>     CDrawObject                -> secound element
>     CDrawMultiObject        -> third element
>         CDrawObject                -> first element
>         CDrawObject                -> secound element
>     CDrawObject                -> fourth element
>
> i would like to be able to call baseobject.GetNoOfElements() which should
> return 5 on the one hand on the other i'd like to be able to call
> baseobject.Draw() which should call element0.Draw(), element1.Draw(), ...
>
> my question is how to design such a structure.
>
> i have two approches:
> the first one using dynamic casts to be able to distinguish between normal
> drawobjects and drawmultiobjects,
> the secound one implementing at least some sort of interface function in
the
> base class (i.e. GetNoOfObjects)
>
> i have heard that it is considered a bad programming style using dynamic
> casts but on the other hand i do not think that it is a good idea
> to implement "GetNoOfObjects" within the base class either.
>
> so what do you think - how to solve this?
>
> thanks, philipp
>
>


0
a
11/13/2003 2:09:20 PM
Philipp Huber wrote:

>hi!
>
>i'd like to design a class - let's call it CDrawObject - that is able to
>contain some data and draw itself.
>furthermore i'd like to have a class CDrawMultiObject that is derived from
>CDrawObject and can contain objects of type CDrawObject.

But a collection of X objects is usually not an X object. For example, an
array of int is not an int, and it would not be appropriate to derive array
of int from int, even if it were possible.

>i imagine to have the following situation:
>
>CDrawMultiObject            -> base object (i.e. an object manager )
>    CDrawObject                -> first element
>    CDrawObject                -> secound element
>    CDrawMultiObject        -> third element
>        CDrawObject                -> first element
>        CDrawObject                -> secound element
>    CDrawObject                -> fourth element
>
>i would like to be able to call baseobject.GetNoOfElements() which should
>return 5 on the one hand on the other i'd like to be able to call
>baseobject.Draw() which should call element0.Draw(), element1.Draw(), ...
>
>my question is how to design such a structure.
>
>i have two approches:
>the first one using dynamic casts to be able to distinguish between normal
>drawobjects and drawmultiobjects,
>the secound one implementing at least some sort of interface function in the
>base class (i.e. GetNoOfObjects)
>
>i have heard that it is considered a bad programming style using dynamic
>casts but on the other hand i do not think that it is a good idea
>to implement "GetNoOfObjects" within the base class either.
>
>so what do you think - how to solve this?

I might define a "Drawable" interface class and derive "SingleObject" and
"MultiObject" from it. Drawable would define a (pure) virtual function
"Draw", which the derived classes would override. MultiObject would contain
a vector or other container of pointers to Drawable objects, and its Draw
override would iterate over the container and call Draw on each element.

-- 
Doug Harrison
Microsoft MVP - Visual C++
0
dsh (2498)
11/13/2003 5:51:38 PM
> But a collection of X objects is usually not an X object. For example, an
> array of int is not an int, and it would not be appropriate to derive
array
> of int from int, even if it were possible.

but what if i want to collect both a collection of X and X within one object
(object manager)?

> I might define a "Drawable" interface class and derive "SingleObject" and
> "MultiObject" from it. Drawable would define a (pure) virtual function
> "Draw", which the derived classes would override. MultiObject would
contain
> a vector or other container of pointers to Drawable objects, and its Draw
> override would iterate over the container and call Draw on each element.

ok, i agree with you related to the draw function - but how about the
function GetNoOfObjects() which actually should be present only in a
MultiObject.
since i'd like to be able to collect both MultiObjects and SingleObjects in
one collection this would lead to a secound interface "arraw member"
defining a function
GetNoOfObjects().

Philipp


0
11/14/2003 9:57:50 AM
Philipp Huber wrote:

>
>> But a collection of X objects is usually not an X object. For example, an
>> array of int is not an int, and it would not be appropriate to derive
>array
>> of int from int, even if it were possible.
>
>but what if i want to collect both a collection of X and X within one object
>(object manager)?

Then you provide a common base class which can refer to either. That's what
I described when I talked about "Drawable".

>> I might define a "Drawable" interface class and derive "SingleObject" and
>> "MultiObject" from it. Drawable would define a (pure) virtual function
>> "Draw", which the derived classes would override. MultiObject would
>contain
>> a vector or other container of pointers to Drawable objects, and its Draw
>> override would iterate over the container and call Draw on each element.
>
>ok, i agree with you related to the draw function - but how about the
>function GetNoOfObjects() which actually should be present only in a
>MultiObject.
>since i'd like to be able to collect both MultiObjects and SingleObjects in
>one collection this would lead to a secound interface "arraw member"
>defining a function
>GetNoOfObjects().

You can put it in MultiObject if you want to expose the collection. However,
whoever calls the Draw function through a Drawable pointer typically doesn't
care if it resolves to SingleObject or MultiObject; the target object knows
how to draw itself, and if it contains a collection of objects, it iterates
over the objects it contains, telling them to draw themselves.

-- 
Doug Harrison
Microsoft MVP - Visual C++
0
dsh (2498)
11/14/2003 6:52:38 PM
Avoid dynamic casts unless you know what you already have. In general, I would create the
superclass with a "Draw" virtual method. For the CDrawMultiObject, this actually does a
recursive walk. For the CDrawObject, it does nothing. So all you do is a treewalk, e.g.,
an LRN (left-to-right-then-parent-node) walk. Furthermore, I'd put a CDrawObject abstract
class above them with a PURE version of this method.
	
	/* virtual */ void CDrawMultiObject::Draw(CDC & dc)
                 {
                  POSITION p;
                  p = subtrees.GetHeadPosition();
                  while(p != NULL)
                      {
                       CDrawObject * object = subtrees.GetNext(p);
	          object->Draw(dc);
                      }
                  }
let CDrawRectangle be a subclass of CDrawObject. Then you would supply the virtual method
shown below (I would tend to pass the dc in as a parameter)

	/* virtual */ void CDrawRectangle::Draw(CDC & dc)
                  {
                   int save = dc.SaveDC();
                   dc.SelectObject(&pen);
                   dc.SelectObject(&brush);
                   dc.FillRectangle(&r);
                   dc.RestorDC(save);
                  }
	
A MultiObject never draws itself; it just is a container for objects. If the object picked
up is CMultiObject, the program recurses; if it is a real draw object, graphics happen.

Note that at no point here do I actually need a cast. Nor do I need an IsKindOf, or any
kind of type test. This would be the cleanest interface (in fact, I have actually built
structures like this, and they are very, very easy to use and extend)
					joe

                       
On Thu, 13 Nov 2003 10:23:30 +0100, "Philipp Huber" <philipp.huber@innval.com> wrote:

>hi!
>
>i'd like to design a class - let's call it CDrawObject - that is able to
>contain some data and draw itself.
>furthermore i'd like to have a class CDrawMultiObject that is derived from
>CDrawObject and can contain objects of type CDrawObject.
>
>i imagine to have the following situation:
>
>CDrawMultiObject            -> base object (i.e. an object manager )
>    CDrawObject                -> first element
>    CDrawObject                -> secound element
>    CDrawMultiObject        -> third element
>        CDrawObject                -> first element
>        CDrawObject                -> secound element
>    CDrawObject                -> fourth element
>
>i would like to be able to call baseobject.GetNoOfElements() which should
>return 5 on the one hand on the other i'd like to be able to call
>baseobject.Draw() which should call element0.Draw(), element1.Draw(), ...
>
>my question is how to design such a structure.
>
>i have two approches:
>the first one using dynamic casts to be able to distinguish between normal
>drawobjects and drawmultiobjects,
>the secound one implementing at least some sort of interface function in the
>base class (i.e. GetNoOfObjects)
>
>i have heard that it is considered a bad programming style using dynamic
>casts but on the other hand i do not think that it is a good idea
>to implement "GetNoOfObjects" within the base class either.
>
>so what do you think - how to solve this?
>
>thanks, philipp
>

Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
11/18/2003 2:01:59 AM
Reply:

Similar Artilces:

Question from an Idiot
Yes, I think I've asked this before, but my brain has lost the information. Does anyone here use Outlook Express Quick Backup? If so, can you tell me if I can back up to a USB stick, and then carry the stick to another computer, restore the data, and use my OE data? I'll be traveling soon, and I need this ability. Thanks. -- ------------------------------------------ Jeffrey Needle jeff.needle@gmail.com ...

Tabs and Controls
Hi All, I have created an app with a - FormView - 3 Dialogs - Each Dialogs have a List Control How to I get the I get a pointer to the List Control easier than this HWND myWindowHandle = (HWND)m_Tabpages[2]; HWND myHAdapterList = ::GetDlgItem(myWindowHandle,IDC_ADAPTER_LIST); CListCtrl* myAdapterList = (CListCtrl*)FromHandle(myHAdapterList); I am sure it is easy and equally sure i am a fool. Thanks, Iain New Zealand Iain William Wiseman wrote: > Hi All, > > I have created an app with a > > - FormView > - 3 Dialogs > - Each Dialogs have a List Control > >...

exhange server back up-restore question
We have Windows 2003 server with Domain Server. Echange 2000 Server We use regularly back up system for Exchange Server. But to restore for a special date for only one user what should we do? PS. Our back up file's size approx. 80 GB. You don't really have a choice unless you use a 3rd party utility like Quest Recovery Manager. Restore all the data and then Exmerge the specific items you want. I'd also suggest migrating to Exch 2003 if possible as your backup and recovery options are much improved. Nue "ilyas" <ilyas@discussions.microsoft.com> wrote in me...

Modal dialog box question #2
Hi, In my application, I have a modal dialog box, and I want that some of the commands from the main menu will be available. (all other events outside the dialog should be blocked - just like a regular modal dilaog). How do I do it ? Yoav. Modality is like pregnancy. Either the dialog box is modal, in which case you can't click the menus or it's modeless in which case you can click any menu item. I suggest you have two choices: 1) keep the dlg modal and place extra buttons on it to represent the commands. On click then pass the command message to the CMainFrame. 2) Make the ...

general question!
Hello there. Outlook XP in a networked environment. When viewing an email (that has an attachment)in the preview pane, I can see the attachment icon on that little header area between the list of emails and the previewed email. However, when I click away to an email that is a reply to a meeting request (that I sent out)and then click back on the attachment-email, in the information viewer the little attachment icon is no longer on the header. Obviously I can still tell if the email in question has an attachment from the information viewer. This is more annoying more than anything els...

basic mfc question
hi, i just started with vc8 and created a dialog-based mfc project and added some controls and all. the default class was the dialog class... I could create a textbox and reference it to a variable m_*. somehow, now that default class has changed, everytime I double click any control it asks me to create a new class. even the old controls that worked (and still work when I recompile and run) don't show the same options in the context menu. any ideas how to change it? thank you. dtor Complain to Microsoft. They have so totally screwed up Visual Studio that it is nearly unusable. The...

What is document design in PowerPoint?
I am confused about document design and layout and presentation templete with powerpoint? Hi, a template is a set of parameters that govern your whole presentation, including colors and text defaults. Layouts are the way your actual slides can be constructed of Placeholders- gives a consistent look to where your indebted objects, etc are placed. Look at the following links at (1) slide masters and layouts and (2) Colors and themes. Themes is used more in PowerPoint 2007. http://www.echosvoice.com/2007_tutorials.htm -- Regards, Glen Millar Microsoft PPT MVP Tutori...

more of a thought question
Hello. This post is more of a thought type posting to see what and how others manage a webapp that needs to be connected to the production db, a clone db for training, a clone for development, a clone for testing, you get the idea here. What concerns me is someone might think they are on the training db but actually on the production db. My first thought is to have some type of display in the header of the masterpage indicating which db the user is connected to (other then the production). Most, if not all of the above variations would be set up by someone in IT (most likely ...

Signitures Question
I created several signitures using Word, Dreamweaver and writing my own HTML code. When selected in options and loaded, I get the logo but no text. The files are saved in the signiture folder. ...

Question about virtual
Hi, when we use Wizard to create a new class. The destructor is generated as "virtual". Can you please explain why is that ? Will it be a problem if we remove virtual keyword ? thanks, You will need a virtual destructor if there is a chance that a child class could be deleted when it is casted to a parent class. class CMyWnd : public CWnd { public: CMyWnd() { m_pInt = new int[100]; } virtual ~CMyWnd() { delete [] m_pInt; } private: int *m_pInt; }; In the following situation: CMyWnd *pMyWnd = new CMyWnd(); CWnd *pWnd = pMyWnd; delete pWnd; //if the destructo...

Question on Investing performance calculation
How does Money calculate the Investing performance percentage that shows up in Investing/Investment Tools in Money 2006? While the percentages for Dow Jones and S&P match the newspaper so I assume they are calculated as current price - beginning of year price divided by beginning of year price, that same calculation does not appear to be true for my own investments. I could even verify this a few days into the year, before any pruchases/expenses etc. showed up which could mask the numbers for me. Does anyone know? Thanks! ...

A question about CImage
in CDoc CImage m_pImg; in CView ::GlobalLock(HBITMAP(pDoc->m_img)); == NULL GetLastError(); > invalid handler before try to get the handle, I have initialized it successfully, and my OnDraw() can works well. Till I Know CImage is not a Predefined MS MFC Class, are you using some external Library!!! -- With Regards Alok Gupta Visit me at http://alok.bizhat.com "I think this will Help" "ckacka" <ckacka@discussions.microsoft.com> wrote in message news:B320B34E-4D86-4179-88AC-D6E6E08A5BDC@microsoft.com... > in CDoc > CImage ...

General
I created a workbook with several worksheets that are protected and when it is opened it is to go to sheet1 and select cell A10. My problem is that when I open it not only is sheet1/A10 selected but a cell in sheet2 which causes half of each sheet to be visible. Now if I unprotect sheet2 the problem goes away but cells in the two sheets are linked and both need to be protected. Any help with this would be greatly appreciated. Thank you. Carl, care to post the code you are using? maybe somebody can see why it is doing that -- Paul B Always backup your data before trying something new Usin...

design report margin
I have a report based off of a query and the paper is set to legal. In Print Peview, it looks like I have more room to move my columns over to the right margin, but in design view if I try to move my columns to the right, it then goes to the next page when I go back to print preview. I have 18 columns on the page and I need as much room as I can get to space it better. I have the margins set at 0.3 left and right. Thanks, ...

Question about queries
I am trying to query a database that will include building some calculated fields. I am having trouble with the conditions I am trying to place on the calculations. An example is: IIf([recShortName]<>"sm/ WASH TRACTORS" OR "sm/WASH ALL TRAILERS" OR [recShortName] Not Like "bnsf*", Nz([bilUnit1],0)+Nz([bilUnit2,0),0) If the records recShortName is not "sm/WASH TRACTORS" OR "sm/WASH ALL TRAILERS" OR does not contain the text "bnsf" then I want to add the fields bilUnit1, bilUnit2, etc. The way I have it written above is obvious...

MACRO development question
In word, the easy way to write a macro is to record it, then make any alterations. 1. Is there a way to do this with Visio 2002? 2. Does anyone have a macro to export to another image format (esp PCX) they would be willing to share? TIA Andrew a b a k e r AT f l o w l o g i c DOT c o m DOT a u Macro recording will be introduced into Visio 2003 which will be released next month. There examples of VBA code for Visio at http://www.mvps.org/visio/VBA.htm John... Visio MVP Need stencils or ideas? http://www.mvps.org/visio/3rdparty.htm Need VBA examples? http://www.mvps.org/vis...

redo my design
I'm trying to build a database with minimal working knowledge of Access so even though I've been through the tutorial it seems way more complicated then what I need. I have a list of people's name for an annual event and basically need an address book for mailing labels but I need to be able to sort them for about 10 different fields (author, speaker, speaker's guest, media,) but some people belong to more than one group so if I do a print out of labels I want to be able to select to just print 'media and speakers' etc. was this still supposed to be two ta...

vbAdvance general dll problem
I want to create a plugin for an external application in VB6. To do this I create a regular dll, export the necessary functions and compile the dll. So far so good. The problem comes when I developed a second plugin (also in vb6 with vbAdvance) and try to load both in the external application. The first plugin is loaded fine, but the second fails with error 998 (ERROR_NOACCESS). I traced the problem to the code that starts the required vb stuff, in MRuntimeInit: ... pGetClass = GetProcAddress(hMod, "DllGetClassObject") If pGetClass Then CopyMemory pCall, InitDelegato...

Rounding question
I'm using Excel 2007 but 'save as' 97-2003 as colleagues have different versions. All number formats are set to 2 decimal places. I'm finding that percentage calculations are rounding up to 2 decimal places but when the result in currency is subtracted from another figure the sum is rounded down. This gives results such as 6 - 3 = 4. I'm sure there must be a simple answer but I can't find it. Hoping someone here knows, as checking all simple calcuations is getting ridiculous ! Carrie "Carrie" <pantscarolyn.smith2@ntlworld.com> w...

A simple vlookup question
Hello, So I have the text "abc301" in cell A1 and "301" in cell A2. When I do a vlookup using A2 as the lookup value, it works. However, if I use RIGHT(A1, 3) as the lookup value, I get a N/A. Does anyone know how I can use the 3 final characters in a cell as the lookup value? Hi, I do not really understand what you want to do. Is cell A2 (301) a figure or text? Try this. =VLOOKUP(VALUE(RIGHT(A1;3));A1:A2;1;FALSE) Wkr, JP "eggman2001" <sodani@gmail.com> wrote in message news:4f658713-79ba-49a9-897c-7aeeef8ef1f0@z28g2000vbl.googlegroups.com... > ...

Dataset serialization question
I am creating a dataset like so: data = new DataSet("_DATA"); DataTable mm = new DataTable("T_IDS"); mm.Columns.Add(new DataColumn("C_PKEY",Type.GetType("System.Int32"))); mm.Columns.Add(new DataColumn("C_IDS",Type.GetType("System.Collections.ArrayList"))); data.Tables.Add(mm); and later I use the WriteXml method of the dataset to serialize it and after that readXml to deserialize it. Unfortunately the ArrayList ends up just saying System.Collections.ArrayList. So it doesn't deserialize properly. It is an arraylist of int...

Upgrade question
I want to get Office Publisher upgrade version. If I get Office Home and Student will this qualify me for the upgrade version of publisher? I also have Works Suite 2002. Will this qualify me for the Publisher upgrade as well? Thanks Yes to Office Home and Student 2007; no to Works Suite. You need one of the following: Microsoft Publisher 2000-2002; Microsoft Office Publisher 2003; Microsoft Publisher Deluxe 2000-2002; Microsoft Office Publisher 2003 with Digital Imaging; any 2000-2007 Microsoft Office suite; any Microsoft Office XP suite. -- JoAnn Paules MVP Micros...

alt.windows7.general
Windows 7 is Vista regurgitated. But it now has it's own news group. alt.windows7.general (uncensored) Canuck57 wrote this, with guidance from inner voices: > Windows 7 is Vista regurgitated. > > But it now has it's own news group. > > alt.windows7.general (uncensored) Just couldn't leave them in peace, could ya? -- Vita brevis breviter in brevi finietur, Mors venit velociter quae neminem veretur. Canuck57 wrote: > Windows 7 is Vista regurgitated. > > But it now has it's own news group. > > alt.windows7.general ...

PKI Question (IECA)
Has anybody had to deal with the not so new requirement by DoD to implement PKI for all contractors who need to exchange email between themselves and DoD? The requirement is called IECA. I'm just trying to find out if anyone has had to do this, what's involved, besides paying the $100-$150 extortion fee to simply verify who I say I am. Thanks, Tom I haven't had to deal with this, but a Google search turns up the following. http://www.digsigtrust.com/federal/dod.html "Tom Pennington" <NONEt2pennington@comcast.net> wrote in message news:u84WAabTEHA.2128@TK2MS...

User Guide Question
I have Money 2004 and I was wondering if there was a way to print out the entire user guide without having to save every screen? I'm getting more frustrated with Money as time goes on, I thought M05 would help me with things but it doesn't appear to be that way. I might think about switching to Quicken. I like the fact that they have books about how to do certain things and such. There isn't any way to print the on-net User's Guide in total that's been identified here. I find it hard to imagine that M05 will fix any issues you are having with M04--indeed it see...