class Window
{
public:
Window() {}
virtual ~Window() {}
virtual void Print() { cout << "Window" << endl; }
};
class Control : public Window
{
public:
Control() {}
virtual ~Control() {}
virtual void Print() { cout << "Control" << endl; }
};
class Button : public Control
{
public:
Button() {}
virtual ~Button() {}
void Print() { cout << "Button" << endl; }
};
class TextBox : public Control
{
public:
TextBox() {}
virtual ~TextBox() {}
void Print() { cout << "TextBox" << endl; }
};
vector<Control*> m_aControls;
int main()
{
// Create a new Button control
Button* pButton = new Button;
m_aControls.push_back(pButton);
// Create a new textbox control
TextBox* pTextBox = new TextBox;
m_aControls.push_back(pTextBox);
for(int x=0; x<m_aControls.size(); x++)
{
// I want to test if(m_aControls[x] == Button)
m_aControls[x]->Print();
}
return 0;
}
How can I know in advance if the vector object m_aControls[x] is a Button or a TextBox?
Edited by - while1 on February 23, 2002 3:59:22 PM
Edited by - while1 on February 23, 2002 4:00:17 PM
std::vector and OOP
Please look at this code:
Button* b = dynamic_cast(m_aControls[x]);
if(b){
// isButton
}
You can do the same with the text box, and do not forget to
enable RTTI.
if(b){
// isButton
}
You can do the same with the text box, and do not forget to
enable RTTI.
A quick note: RTTI must be explicitly enabled in VC++ or it'll throw up on you (I think Borland has it enabled by default). If you're using VC++ then have a browse around the project settings for an "Enable RTTI" option (or similar).
EDIT - oops! The previous poster said that.
Alimonster
There are no stupid questions, but there are a lot of inquisitive idiots.
Edited by - Alimonster on February 23, 2002 4:57:40 PM
EDIT - oops! The previous poster said that.
Alimonster
There are no stupid questions, but there are a lot of inquisitive idiots.
Edited by - Alimonster on February 23, 2002 4:57:40 PM
If you are REALLY using Object-Oriented Programming, then,
you would **NOT** need to know if a Control * points to
a button or a text box. That is the WHOLE point of
using polymorphism... afterall.
Premature optimizations can only slow down your project even more.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement