Hi
Quick questions abour overload constructors. Lets say I have two overload constructors:
class MyFileExtractor{
MyfileExtractor(string);
MyfileExtractor(string, int);
~MyfileExtractor();
private:
string name;
int columns;
}
/*Class implementation*/
MyFileExtractor::MyFileExtractor(string fname,int c):columns(c)
{
name=fname;
}
MyFileExtractor::MyFileExtractor(string fname)
{
#define STD_NUMBER_OF_COLMS 1 //standard number of columns
MyFileExtractor::MyFileExtractor(fname, STD_NUMBER_OF_COLMS);
}
MyFileExtractor::~MyFileExtractor()
{
cout << "This file removed:" << name << endl;
}
int main()
{
MyFileExtractor cobalt("co60.txt")
MyFileExtractor zinck("zn65.dat",3)
return 0;
}
When I run this code I notice that despite I instantiated 2 objects of type myFileExtractor but the destructor gets call 3 times. I am sure the problem comes from the way I created my second overloaded constructor which calls the first overloaded constructor. Why do I do that? Because the second overload constructor is the same as the first one except it has a default value for the columns parameter. I tried the following whcih i though it was going to solve my problem:
class MyFileExtractor{
MyfileExtractor(string, int);
~MyfileExtractor();
private:
string name;
int columns;
}
/*Class implementation*/
MyFileExtractor::MyFileExtractor(string fname,int c=1):columns(c)
{
name=fname;
}
MyFileExtractor::~MyFileExtractor()
{
cout << "This file removed:" << name << endl;
}
(...)
However I couldn't instantiated objects in main in the following way:
MyFileExtractor cobalt("co60.txt")
I suppose my problem comes from calling the constructor inside another constructor. It seems c++ instantiates a second object inside the first object and that is the reason it calls thedestructor three times...
:~~~ My question here is: is it legal to call a constructor inside another constructor?
What would happen if I have 10 private members in my class and I have one constructor that initializes teh value of the ten memebers and then I have a second constructor that does the same thing except for one element which is initialized by an user parameter. Do i have to write the code for both construtors apart despite their body is the same except for the assignment of one parameter?
class MyFileExtractor{
MyfileExtractor(void);
MyfileExtractor(int);
~MyfileExtractor();
private:
string name;
int columns;
(... 8 parameters more)
}
//class implementation
MyFileExtractor::MyFileExtractor(){
//initialized all 10 parameters
(...)
}
MyFileExtractor::MyFileExtractor(int a){
//initialized 9 parameters
(Lots of repeated lines which exist already in the default constructor)
MyFileExtractor::a=a;
}
What is the most efficient way to do this?
Thanks,
C.