I have the following class called DATA.
enum DATATYPE{DATATYPE_CONSTANT=0, DATATYPE_NUMBER,DATATYPE_STRING, DATATYPE_MATRIX, DATATYPE_OBJECT};
struct DATA //A Data container for the variable
{
DATA(DATATYPE type,int row=0,int col=0)
{
m_str=0;m_number=0;
m_DataType=type;
if(type==DATATYPE_NUMBER) m_number=new double;
if(type==DATATYPE_STRING) m_str=new string("");
cout<<"In constructor"<<endl;
//if(type==DATATYPE_MATRIX) m_matrix= new MatrixXd(row,col);
}
~DATA()
{
if(m_str) m_str->clear();
if(m_number) {delete m_number; m_number=0;}
std::cout<<"In Destructor"<<std::endl;
//if(m_matrix) {delete m_matrix; m_matrix=0;}
}
DATA(const DATA& other)
{
m_number=other.m_number;
m_str=other.m_str;
m_DataType=other.m_DataType;
cout<<"In copy constructor"<<endl;
}
DATA& operator=(const DATA& other)
{
m_number=other.m_number;
m_str=other.m_str;
m_DataType=other.m_DataType;
cout<<"In operator="<<endl;
return *this;
}
DATATYPE GetType()
{
return m_DataType;
}
double* GetNumber()
{
return m_number;
}
void SetNumber(const double& val){*m_number=val;}
string* GetString()
{
return m_str;
}
private:
DATATYPE m_DataType;
string* m_str;
//MatrixXd* m_matrix;
double* m_number;
};
And I have the following test:
DATA GetData();
int main()
{
cout<<"Before GetData call"<<endl;
DATA dat=GetData();
//DATA dat2=dat;
cout<<*(dat.GetNumber())<<endl;
cout<<"After Get Data call"<<endl;
cout << "Exiting main" << endl;
return 0;
}
DATA GetData()
{
cout<<"In Get Data"<<endl;
DATA ret(DATATYPE_NUMBER);
double d=5;
ret.SetNumber(d);
cout<<"Exiting GetData"<<endl;
return ret;
}
After running the test the output is:
Before GetData call
In Get Data
In constructor
Exiting GetData
5
After Get Data call
Exiting main
In Destructor
I have the following questions:
When I call
DATA dat=GetData();
it neither calls constructor, copy constructor nor equal operator. How is dat object constructed. Also what exactly compiler do when returning fromGetData
?For the
DATA
structure, or in general aggregate data types, is it always a good idea to initialize member variables withnew
? What happens to member variables when I initialize sayDATA *d=new DATA(DATATYPE_NUMBER)
? Is it getting more error prone for memory leaks?