Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using pointers to access virtual functions in derived classes

Status
Not open for further replies.

jhumphreys

Programmer
Oct 1, 2007
1
US
I have taken over the development of some GUI code in C++, and I'm having trouble accomplishing what I want. The GUI has a class derived from CPropertySheet that has 5 property page classes all derived from CPropertyPage. The CPropertySheet class uses the pages in its functions. One function (SetActivePage) calls the base class SetActivePage function, and then it asks the page to load it's data. The way it is written, it checks what page is selected (by the index passed in to the SetActivePage function when the user switches pages. If the page is 1, then it calls the load data function for the class pertaining to page 1. etc. for each page. This seems like a lot of code. I wanted to use virtual functions, and in the CPropertySheet function, I wanted to replace all those conditionals with just two lines of code:
CMyPage * myPage = GetActivePage(); //get the right page
myPage->LoadData() //where loaddata is a virtual function
//for all the pages derived from MyPage
//which is derived from CPropertyPage
So I created a class CMyPage (Name changed to protect project confidentiality). CMyPage is derived from CPropertyPage. CMyPage is now the base class of the 5 property page classes that used to be derived from CPropertyPage. I wrote a virtual LoadData() member function on each of the derived classes and wrote a pure virtual function LoadData on CMyPage class. Ideally, the above code would work if GetActivePage returned a pointer to the actual class or to the CMyPage class.

However, GetActivePage() (which is a member function of CPropertySheet) returns a pointer to CPropertyPage, which cannot be converted to a pointer of the derived class CMyPage. I somehow need to be able to get a pointer to the derived class or the class of the actual object.

Does anyone have a better architecture solution or a way to make this solution work?

Thanks!
 
I had that problem. I can't remember the exact details but here is the gist.

The way I got around it was by creating a vector of CMyPage pointers. As the pages are created, they are added to the vector. Instead of using GetActivePage, get the index of the page. I can't remember how this was done.

Anyway, use the index into the vector and you'll get the correct class + virtual function every time.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top