Suppose you were defining a string in the default constructor. Now, suppose you wish to append something to that string in the parametric constructor. Does the parametric constructor automatically erase whatever was defined in the default constructor? It seems to be doing this for me. Now, I would like to know why it would be doing this.
If you are calling the parametric constructor, the default constructor is never called. Therefore the string you assigned in the default constructor never was assigned.
I believe C++11 changes this, allowing you to chain multiple constructors together, but I don't know how widely that is supported.
Also, I was wondering if, once a parametric constructor is called (this constructor is only setting one private variable, mind you), if the better way to set that variable again would be:
a.) From a friend class, directly setting it or
b.) Calling the parametric constructor again with the new value
?
I am resetting the private value to call some of the class's functions again.
Something similar in the C++ standard library is opening files with fstream. You can open the file from the constructor: std::ofstream fout("Myfile.txt");
or you can open the file later with the .open() function fout.open("Myfile.txt");
#include <iostream>
usingnamespace std;
class myclass
{
private:
string str;
//other private declarations
public:
myclass();
myclass (string);
//other public declarations
}; //end myclass
myclass::myclass()
{
//initialize everything
} //end default constructor
myclass::myclass(string thestring)
{
str = thestring;
} //end parametric constructor
int main()
{
//some stuff
myclass m;
string parameters[] = {"param1", "param2", "param3"};
for (int x = 0; x < 3; x++)
{
m = myclass(parameters[x]);
//some other stuff
} //end for
return 0;
} //end main
?
EDIT: I do this in my program, and it doesn't throw errors on this, but it consumes memory so fast that it threatens to crash the whole system. I guess I answered my question....