A
Angus
I have a class with a member variable which can be of varying types.
For now, I only need to support int and char*.
My first idea was to use a union. So I used:
union{
int nWidget;
char* szWidget;
} m_widget;
void setWidget(int widget)
{
m_widget.nWidget = widget;
}
But I had a problem setting the char*
The ctor for the class set m_widget.szWidget=0
The setter for the char* was like this:
void setWidget(const char* widget, int len = 16)
{
if(m_Widget.szWidget)
delete [] m_Widget.szWidget;
if(len != 0){
m_Widget.szWidget = new char[len];
if(widget)
strcpy(m_Widget.szWidget, widget);
}
}
This is in a class eg class containingwidget.
If I do this:
containingwidget wid;
wid.setWidget(65); //or anything
string strWID("123");
wid.setWidget(strWID.c_str(), strWID.length());
When setWidget is called setting the int, it seems to set szWidget to
65. well in debugger it shows as 0x00000041 (and a blank string -
""). Which seems odd. But problem is the check if(m_Widget.szWidget)
is true and so delete is called when szWidget has not been new'd.
My first question is why am I getting the union problem? And can I
fix it?
Is a union the best way to do this? Any alternative approach? Any
help would be most appreciated.
Angus
For now, I only need to support int and char*.
My first idea was to use a union. So I used:
union{
int nWidget;
char* szWidget;
} m_widget;
void setWidget(int widget)
{
m_widget.nWidget = widget;
}
But I had a problem setting the char*
The ctor for the class set m_widget.szWidget=0
The setter for the char* was like this:
void setWidget(const char* widget, int len = 16)
{
if(m_Widget.szWidget)
delete [] m_Widget.szWidget;
if(len != 0){
m_Widget.szWidget = new char[len];
if(widget)
strcpy(m_Widget.szWidget, widget);
}
}
This is in a class eg class containingwidget.
If I do this:
containingwidget wid;
wid.setWidget(65); //or anything
string strWID("123");
wid.setWidget(strWID.c_str(), strWID.length());
When setWidget is called setting the int, it seems to set szWidget to
65. well in debugger it shows as 0x00000041 (and a blank string -
""). Which seems odd. But problem is the check if(m_Widget.szWidget)
is true and so delete is called when szWidget has not been new'd.
My first question is why am I getting the union problem? And can I
fix it?
Is a union the best way to do this? Any alternative approach? Any
help would be most appreciated.
Angus