Re: Special Case: Creating a variable in a function?
On Apr 17, 4:42 pm, tragomaskhalos <dave.du.verg...@logicacmg.com>
wrote:
On Apr 17, 9:46 am, patelvij...@gmail.com wrote:
union varValue{
string strValue;
int intValue;
}
No, you can't do this: (think: when a instance of varValue goes out of
scope, what destructor if any should be called?).
Yes, thank you for pointing out union & Class object. So it must use
pointer now.
I tried to write whole code, here is working copy. Still it need extra
code to follow standard practice, i.e. auto_ptr, providing getValue
function.
#include <iostream>
#include <string>
#include <map>
using namespace std;
union varValue{
string* strValue;
int* intValue;
};
enum varType {STRING, INT}; //Again enum, i was advised yesterday
that, enum is part of fully OO.
struct variable {
varType type;
varValue value;
};
int main() {
map<string, variable> variableTable;
variable var1, var2;
var1.type = STRING;
string tmpStr = string("my string variable value");
var1.value.strValue = &tmpStr;
variableTable["myVar1"] = var1;
var2.type = INT;
int temp = 10;
var2.value.intValue = &temp;
variableTable["myVar2"] = var2;
cout << *variableTable["myVar2"].value.intValue << endl;
cout << *variableTable["myVar1"].value.strValue << endl;
}
Vijay.