How to get the runtime class?

I've created a Doc/View architecture application using MFC. I have a number of view class types derived from a parent view class, which itself is derived from CView. During the program execution I get the currently active view using line 1 below.  I want to then call a function on that view, but at the child class level not the parent, or CView, level. Is there a way to do that without repeating lines 3-5 below for each class?
CView* testview = ((CFrameWnd*) AfxGetApp()->m_pMainWnd))->GetActiveView();
 
if(testview->IsKindOf(RUNTIME_CLASS(CMyChildView))){
 ((CMyChildView*)testview)->DoSomething();
}

Open in new window

LVL 4
markgoodingAsked:
Who is Participating?
 
AndyAinscowConnect With a Mentor Freelance programmer / ConsultantCommented:
Use a virtual function.

CMyBaseClass..
{
virtual void DoSomething() { ASSERT(FALSE); };
};




COneClass : public CBaseClass
{
virtual void DoSomething() ;
};

CTwoClass : public CBaseClass
 {
 virtual void DoSomething() ;
 };


Then elsewhere
pView->DoSomething();   //compiler will 'know' which DoSomething to call.
0
 
alb66Connect With a Mentor Commented:
Derivae all the views from a common base class (derived from CView). Add a virtual method in that class and override it in the derived classes.


class CBaseView : public CView 
{
   virtual void DoSomething() {}
}
 
class CMyChildView1: public CBaseView 
{
  virtual void DoSomething();
}
class CMyChildView2 public CBaseView 
{
  virtual void DoSomething();
}
 
 
CView* testview = ((CFrameWnd*) AfxGetApp()->m_pMainWnd))->GetActiveView();
 
if(testview->IsKindOf(RUNTIME_CLASS(CBaseView ))){
 ((CBaseView *)testview)->DoSomething();
}

Open in new window

0
 
markgoodingAuthor Commented:
I'd always wondered what virtual did. Never got around to looking that up. Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.