cast between base classes

Hi,

Id like to check if a Control in my Dialog has a specific base class.
Therefor i walk through all children by getting the CWnd object from their
handle and test if the object has the base class in question, like this:

Class hierarchy:
---CWnd----CButton-----CMyButton
BaseClass-------------------'

Doesnt work:
    ...
    CWnd * pWnd = CWnd::FromHandle(hWndChild);
    BaseClass pbase = dynymic_cast<BaseClass*>(pWnd); // Access Violation +
CException
    ...

Works:
    ...
    CWnd * pWnd = CWnd::FromHandle(hWndChild);
    if (pWnd->isKindof(RUNTIME_CLASS(CMyButton))) {
        CMyButton* pBtn = (CMyButton*)pWnd;
        BaseClass pbase = dynymic_cast<BaseClass*>(pBtn);
    ...

but doesnt make much sense as with this solution I have to hardcode every
single class derived from BaseClass for the downcast.
How do I cast directly a CWnd-object to my BaseClass or how do I get the
last ojbect in the hierarchy (here CMyButton)?

Thx Mark




0
9/2/2004 12:38:45 PM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
841 Views

Similar Articles

[PageSpeed] 3

I do not understand your diagram. Could you write out the class declarations, e.g., I
understand

class CWnd  { }
class CButton : public CWnd {}
class CMyButton : public CButton {}

but what is a BaseClass? How is it declared in C++?  It is impossible to guess from the
funny two-line description how this syntactically fits into the C++ structure.

And note that CWnd::FromHandle is not guaranteed to return anything meaningful that can be
downcast beyond CWnd. If it gives you a CMyButton, then the downcast is safe, but in
general you have no guarantees.

Presumably you have enabled RTTI.

But without something coherent to work with, it is impossible to guess what could be going
on.
				joe
On Thu, 2 Sep 2004 14:38:45 +0200, "Mark Daring" <cap_nemesis@hotmail.com> wrote:

>Hi,
>
>Id like to check if a Control in my Dialog has a specific base class.
>Therefor i walk through all children by getting the CWnd object from their
>handle and test if the object has the base class in question, like this:
>
>Class hierarchy:
>---CWnd----CButton-----CMyButton
>BaseClass-------------------'
>
>Doesnt work:
>    ...
>    CWnd * pWnd = CWnd::FromHandle(hWndChild);
>    BaseClass pbase = dynymic_cast<BaseClass*>(pWnd); // Access Violation +
>CException
>    ...
>
>Works:
>    ...
>    CWnd * pWnd = CWnd::FromHandle(hWndChild);
>    if (pWnd->isKindof(RUNTIME_CLASS(CMyButton))) {
>        CMyButton* pBtn = (CMyButton*)pWnd;
>        BaseClass pbase = dynymic_cast<BaseClass*>(pBtn);
>    ...
>
>but doesnt make much sense as with this solution I have to hardcode every
>single class derived from BaseClass for the downcast.
>How do I cast directly a CWnd-object to my BaseClass or how do I get the
>last ojbect in the hierarchy (here CMyButton)?
>
>Thx Mark
>
>
>

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)
9/2/2004 4:19:59 PM
You should have posted your followup on the newsgroup instead of sending me private email.

MFC does not play well with multiple inheritance. It is not a recommended practice. There
is so little you can do in the alternate class that generally it doesn't help much. I have
never used multiple inheritance, because the few times I thought it would work, I hit
problems like this, which seem to be fundamental problems in MFC's interaction with
multiple inheritance.
					joe

On Thu, 02 Sep 2004 12:19:59 -0400, Joseph M. Newcomer <newcomer@flounder.com> wrote:

>I do not understand your diagram. Could you write out the class declarations, e.g., I
>understand
>
>class CWnd  { }
>class CButton : public CWnd {}
>class CMyButton : public CButton {}
>
>but what is a BaseClass? How is it declared in C++?  It is impossible to guess from the
>funny two-line description how this syntactically fits into the C++ structure.
>
>And note that CWnd::FromHandle is not guaranteed to return anything meaningful that can be
>downcast beyond CWnd. If it gives you a CMyButton, then the downcast is safe, but in
>general you have no guarantees.
>
>Presumably you have enabled RTTI.
>
>But without something coherent to work with, it is impossible to guess what could be going
>on.
>				joe
>On Thu, 2 Sep 2004 14:38:45 +0200, "Mark Daring" <cap_nemesis@hotmail.com> wrote:
>
>>Hi,
>>
>>Id like to check if a Control in my Dialog has a specific base class.
>>Therefor i walk through all children by getting the CWnd object from their
>>handle and test if the object has the base class in question, like this:
>>
>>Class hierarchy:
>>---CWnd----CButton-----CMyButton
>>BaseClass-------------------'
>>
>>Doesnt work:
>>    ...
>>    CWnd * pWnd = CWnd::FromHandle(hWndChild);
>>    BaseClass pbase = dynymic_cast<BaseClass*>(pWnd); // Access Violation +
>>CException
>>    ...
>>
>>Works:
>>    ...
>>    CWnd * pWnd = CWnd::FromHandle(hWndChild);
>>    if (pWnd->isKindof(RUNTIME_CLASS(CMyButton))) {
>>        CMyButton* pBtn = (CMyButton*)pWnd;
>>        BaseClass pbase = dynymic_cast<BaseClass*>(pBtn);
>>    ...
>>
>>but doesnt make much sense as with this solution I have to hardcode every
>>single class derived from BaseClass for the downcast.
>>How do I cast directly a CWnd-object to my BaseClass or how do I get the
>>last ojbect in the hierarchy (here CMyButton)?
>>
>>Thx Mark
>>
>>
>>
>
>Joseph M. Newcomer [MVP]
>email: newcomer@flounder.com
>Web: http://www.flounder.com
>MVP Tips: http://www.flounder.com/mvp_tips.htm

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)
9/2/2004 9:29:09 PM
On Thu, 2 Sep 2004 14:38:45 +0200, "Mark Daring"
<cap_nemesis@hotmail.com> wrote:

>Hi,
>
>Id like to check if a Control in my Dialog has a specific base class.
>Therefor i walk through all children by getting the CWnd object from their
>handle and test if the object has the base class in question, like this:
>
>Class hierarchy:
>---CWnd----CButton-----CMyButton
>BaseClass-------------------'

I assume you have comething like 

class CButton : public CWnd { ... };
class CMyButton: public CButton, public BaseClass { ... };

>
>Doesnt work:
>    ...
>    CWnd * pWnd = CWnd::FromHandle(hWndChild);
>    BaseClass pbase = dynymic_cast<BaseClass*>(pWnd); // Access Violation +
>CException
>    ...

That is not supposed to work, and cannot work if you try to think what
you asked the compiler to do. 

- You have a CWnd* 
- you cast it to BaseClass*

CWnd and BaseClass are in NO WAY related to each other. They are
completely different, and at the point of conversion the compiler does
not know that they are both part of a larger class, in this case. 

Do it like this: 

CWnd * pWnd = ... whatever ...
CMyButton* p1 = dynamic_cast<CMyButton*>( pWnd );

if ( p1 )
{
  BaseClass* p2 = p1; 
  // ... do what you want ...

}

Note that the definition of p2 is not really necessary: Since
CMyButton is derived from BaseClass, you can access members of
BaseClass directly via p1. 

Some people think that MFC is not suited for Multiple Inheritance.
This is only true if you use the now deprecated RUNTIME_CLASS - stuff.
MFC implements its own RTTI and sometimes uses it itself. The MFC RTTI
implementation is not suited for Multiple Inheritance. As long as you
use the C++ functionality for MI, you are safe .... well, nearly. 

MFC sometimes assumes a certain object memory layout. This is
preserved when you use Single Inheritance. Therefore, when using
Multiple INheritance, ALWAYS write 

      class CMyButton: public CButton, public BaseClass { ... };

and NEVER

      class CMyButton: public BaseClass, public CButton { ... };

i.e. the MFC-related baseclasses must be FIRST in the inheritance
list. After that, you can have an arbitrary number of additional base
classes. 

Also note that virtual inheritance does not work well, too, Thing like


      class CMyButton: public CButton, virtual public BaseClass { ...
};

or something along that lines is not guarantee to work, because the
positiononing of base classes in the containing class might be
different. 

BTW, the cast from one base to another (unrelated) base in a larger
class is called "cross cast" in the literature. 

My 2 cents....

------------------------------------------------
Martin Aupperle
------------------------------------------------
0
9/11/2004 9:30:36 PM
On Thu, 02 Sep 2004 17:29:09 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:

>MFC does not play well with multiple inheritance. It is not a recommended practice. There
>is so little you can do in the alternate class that generally it doesn't help much. I have
>never used multiple inheritance, because the few times I thought it would work, I hit
>problems like this, which seem to be fundamental problems in MFC's interaction with
>multiple inheritance.

You can use it, if you obey some restrictions. See my previous post in
this thread. 

IMHO, MI is inevitable for good design. Even Java has it in the form
that a class can implement several interfaces. To me, absolutely
necessary. 

------------------------------------------------
Martin Aupperle
------------------------------------------------
0
9/11/2004 9:32:55 PM
Reply:

Similar Artilces:

Autocomplete date for cell based on other cell values
I have two situations where I want the cell to be filled with a specific value based on values in other cells on a given row. In the first case I need the CaseID to generate the WorkerID where the WorkerID is determined by the last three digits of the CaseID. In the second I need to have a date placed in the Case Due Column based on two different criteria, if the case is Timely then it would be the last day of the given month, if the item is not timely then the due date is 30 days from the date of application. To determine timely or not first it has to be shown as a review c...

exec usp_MyProc cast(@MyParam as int)
Can you pass expressions to a proc? No, only values. -- Tibor Karaszi, SQL Server MVP http://www.karaszi.com/sqlserver/default.asp http://sqlblog.com/blogs/tibor_karaszi "nzrdb6" <nzrdb6@googlemail.com> wrote in message news:76ca6815-fb69-4a25-822f-df3a32437f44@b7g2000yqd.googlegroups.com... > Can you pass expressions to a proc? nzrdb6 wrote: > > Can you pass expressions to a proc? Tibor answered that. Having said that, you don't really need an expression for the example you posted in the subject, because an implicit conversion wil...

about casting
Hello! I have a COM dll where I have some problem with casting for one method. Below you see a signature for method InitRules2 which is a method that is located in the COM dll and is called from C# asp.net web application. STDMETHODIMP CSyntaxObj::InitRules2(IHandle_DS* handle_ds, BSTR Provider, BSTR DataSource, BSTR UserId, BSTR Password, BSTR ProductID, BSTR Revision, BSTR ApplicationID, BSTR ApplicationRev, BSTR SubfileID, VARIANT_BOOL *bRes) { .... Handle_DS* m_handle_DS = handle_ds; .... } I create this object handle_ds from C# by calling C-tor in the COM dll. This object is the...

auto populate fields in the form based on lookup record
Does anyone know how to (or what you need to do to) automatically populate fields in a form with the values from parent entity based on the lookup value you select in CRM4.0? For example, if I select a record from a lookup list/table, I want other fields in the form to be auto filled with related data from the lookup record I selected. I know CRM has mapping functionality but this is only applicable if you are creating a record from the parent. I need similar functionality of mapping but from choosing a lookup value. -- JL You need to access the CRM web services to achieve this. Se...

Conditional Formatting based on deadlines #4
Thanks, all! Problem solved -- madblok ----------------------------------------------------------------------- madbloke's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1442 View this thread: http://www.excelforum.com/showthread.php?threadid=27448 ...

How can I create a class reunion directory from a spreadsheet?
I have set up personal data in columns that are titled classname, present name, address, phone, email, occupation, children, grandchildren, interests, etc. for a high school class reunion directory. How can I turn this into a layout whereby it prints on pages and looks like this: SMITH, Brenda (bold face and underlined) COWELL, Brenda 3220 Main Street Columbus, OH 43007 614-228-3223 bcowell@atlasbutler.com Business Owner Spouse: John Cowell Tom (32), Bob (30), Sally (28) Emily (7); Sammy (4) Bridge, Reading, Tennis If possible, I would like the layout to show two columns across the page...

UML: using existing classes/structures in a library
Hi, How can I create a UML diagram that uses existing classes in a library. For example, I want to build a UML static structure that has a class ProxyConfiguration. That class has a method that takes a SoapEnvelope as a parameter. SoapEnvelope is a class that is not part of my application, it is part of an existing library. So I don't want to add a class with the name SoapEnvelope just to allow me to make my diagram. Thanks, -- Sven > So I don't want to add a class with the name SoapEnvelope just to allow me > to make my diagram. That is EXACTLY what the Wrox book on ...

Casting CWnd-derived Pointers ?
Hi guys, I'm pretty sure it's bad practice to "downcast" a pointer but if it compiles and works do I have to worry ? Is it possible that it can work sometimes and not work other times ? I'm working with some custom CWnd-derived classes and it's much easier to use a CWnd* as the parent when I need access to it (the parent) and just cast it, like this: // this is kind of like a CView class CCustomParentWnd : public CWnd { CCustomChildWnd m_childWnd; // the child // lots of stuff } // this is like a control class CCustomChildWnd : public CWnd { // store the paren...

Fill in Date based on E1
I have a date (MMM YY) entered into cell E1. I would like to increment by month F1 Thru whenever data is no longer populated in row 2. My Current spreadsheet: E F G H I Row1 Jun 10 Row2 $80 $1600 $1706 $272 $352 How I need to modify: E F G H I Row1 Jun 10 Jul 10 Aug 10 Sep 10 Oct 10 Row2 $80 $1600 $1706 $272 $352 The Data in Row 2 may extend to any column. Any help is greatly appreciated. Put your starting date in E1. Then enter the following in F1 and copy to the right for as many columns as you need. =IF(F2="","",DATE(YEAR(E1),M...

Cast? Which is the correct way?
Hello, Is there a difference between using: controller = ObjectFactory.GetInstance(controllerType) as IController; Or controller = (IController)ObjectFactory.GetInstance(controllerType); I see the first one with a VB similar sintax and the second one as C#. But C# accepts both ... How should I use it? Thank You, Miguel On 5/17/2010 00:07, shapper wrote: > Hello, > > Is there a difference between using: > controller = ObjectFactory.GetInstance(controllerType) as > IController; > > Or > controller = (IController)ObjectFactory.GetIns...

data base query
I have a workbook with 2 work sheets. Eacch contains data from a database query( 2 different databases) Is it possible to create a pivot table from the 2 sheets ? ...

Create Worksheets Based on Template
I have an Excel 2000 workbook which has two worksheets: a template sheet and a sheet with a list of names in column A. Is there a (relatively) simple method to create new worksheets based on the template worksheet for each name in the list of names. For example, if I was doing it manually, I would copy the template worksheet and rename the copy to the first name in the list and repeat for each name in the list. This would be very tedious as the list is fairly long (75 to 100 names). I would like to do this automatically if possible, expecially as I have to set up several workbooks like th...

Fly in based on keys?
I have a list of items 1 A 2 B 3 C I want to start with 1 2 3 on a page and ask for items on the list. If somebody says "B" I want to show 1 2 B 3 etc. Is there any easy way to do this? You will need to use triggers http://www.pptalchemy.co.uk/powerpoint_hints_and_tips_tutorials.html#triggers -- john ATSIGN PPTAlchemy.co.uk Free PPT Hints, Tips and Tutorials http://www.pptalchemy.co.uk/powerpoint_hints_and_tips_tutorials.html "Mike Painter" wrote: > I have a list of items > 1 A > 2 B > 3 C > > I want ...

Help with simple sales data base
Hi need help with a school project for one of my off spring ;) They are writing a simple sales database and have become stuck. Any help would be appreciated. We have an Orders table, Customers table (with a link to orders) and a product table. What we are trying to do is have an orders form where you select a customer (done that), and have a subreport pick out the products you are selling - however I cant figure out how to link products to orders as i may have many lines of products on one order and wish to show totals etc? Any pointers.... On 5 mrt, 21:47, CP <C...@di...

form base authentication #2
This is killing me. I'm implementing form base authentication. I have SSL and everything working but for one problem when use won't to get to owa they type mail.domain.com which then defaults to http://mail.domain.com. the problem I'm having is that FBA need it to default to https not http. How can I get it to default to HTTPS with out telling the uses to type https? I am implementing this on a FE/BE environment wayne .. What I do is change the http port on the main site to something like 8080, and then create a new site that listens on 80. For that site, instead of...

delete columns based on selection
I want to highlight cells and if a certain word is found in the selection, delete the column. So I highlight the cells, press alt+f8 and run the code. ...

What's the interface of the class interator int Standard C++ of STL
For example : How to understand : T0 template<class T, class A = allocator<T> > class vector { public: typedef A allocator_type; typedef A::size_type size_type; typedef A::difference_type difference_type; typedef A::reference reference; typedef A::const_reference const_reference; typedef A::value_type value_type; typedef T0 iterator;// do not know the details of T0 typedef T1 const_iterator; typedef reverse_iterator<iterator, value_type, reference, A::pointer, difference_type> reverse_iterator; typedef reve...

Large Data base
I have a database that is made up of product codes, part numbers, cos and prices. This database is 10 columns wide by 60,000 rows. Thi file is used by 3 or 4 other workbooks. One being a quote form, on being a purchase order, one being a order sheet. I would like to be able to update the database in 1 excel file and lin to the other 3 or 4 other excel files. I currently use this format bu have my database in each of the other4 excel files. So when th database is updated (from corporate) I have to copy this database int the 4 other excel files. My question to all of you is there a wa...

Issues with SignedXml Class
Class SignedXml is used to produce/verify signature over XML document. One of its methods, function GetIdElement, is used to select Xml elements for signature and verification and consist following line: xmlElement = document.SelectSingleNode(String.Concat("//*[@Id=\"", idValue, "\"]")) is XmlElement; I can see two issues with this line 1. URI injection - there is no validation of idValue whatsoever; therefore I can successfully validate document below (see what is the URI). I have control over XPATH query you are performing. Although I cannot find any "da...

void* and cast
I am not very good at managing void* pointer. I want to convert the variable pointed by a void* into a int so I do that : void foo(void* handle) { int* pTmp; int nValue; CString csTmp; pTmp = (int*) handle; nValue = *pTmp; csTmp.Format("Value pointed by handle = %d", nValue ); AfxMessageBox(csTmp); } Is there any shorter way of doing it ? Something like : nValue = *( (int*) handle). I think I tried a long time ago and it didn't work, don't know why because it seems logic to me. I want to deference the pointer after having cast it into int, so what's wron...

HTML based E-Mail from Publisher 2003
I have been given the task of creating a newsletter that will be displayed in the text of an email. The answers I am looking for are to the following questions: Is there anyway that I can create some sort of mail merge that will personalize a greeting for a recipient list? How can I set the newsletter to appear in the center of the email body instead of flush to the left? Publisher has some mail merge ability, look to www.publishermvps.com/general for mail merge info. Pub 2003 does not support centering html content. -- David Bartosik - MS MVP for Publisher help: www.davidbartosik.com en...

problem with the CDialogBar class of VC7
hi, I am getting problem with the CDialogBar class of VC7. There seems to be bug exits with the below function, this always return FALSE. This code is supplied with the following versions 7.1.3088( MS Dev Environment 2003) and 1.1.4322( >NET Framework 1.1). The below code exists with Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\src\mfc\bardlg.cpp file Here is the function created problem while doing my work using mfc71d.dll. LRESULT CDialogBar::HandleInitDialog(WPARAM, LPARAM Default(); // allow default to initialize first (common dialogs/etc // create OLE control...

Querys based on Querys
I have querys based on querys in access, for example when I click a button final query runs which is based on A Query , and because A query is based on a B query and so on, I can get desired results in the final query (for example in a report or form) My question is, can this be done in code builder ? how to reference all those queries at run time , like for example first the A query needs to be resolved and then B query and C query and then finally the result is displayed in the final query, Thanks the query or queries that the final query is based on, will run automatically regardless...

Conditional Formatting based on Text within Text
I need to create a conditional format based on a text string that will be contained in a larger text string within the active cell. I know I can use either the SEARCH or FIND function to determine if a text string is contained within a larger string, but those functions require a cell address and I don't know how to apply them to the current cell address, whatever it might be. So, for example, if the text string is "needs training", and the text in cell A5 is "George has had some exposure to the app, but he needs training", then I would want that cell to apply ...

Outlining based on level numbers in most left column
Hi, I have a table, which is downloaded from SAP and has no formulas. The identifier of the rows is a project item number like "PRD. 00133.07-03-04" and I count the number of "." and "-" with a formula to get the level of the project item. My goal is now to make an outline by vba using the level numbers, e.g. 4 in the case described above. The first row of the table is poulate with these level numbers like 1 2 2 3 3 2 1 2 and so on. Does anyone have a vba procedure to solve this problem. Thanks. Excel XP SP3 Windows XP SP3 Best Regard...