std::vector and OOP

Started by
6 comments, last by while1 22 years, 2 months ago
Please look at this code:
      

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
Advertisement
You can use RTTI (run-time type information).
---visit #directxdev on afternet <- not just for directx, despite the name
Sorry but I don´t know what that is.
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.
Thank you very much!
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
Thanks Alimonster, I have found that setting now (under the C/C++ tab in Settings).

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