After i create an object can i call the constructor again to reinitialize that objects variables? I know i can create a function to do this, but i was wonder if i can just call the constructor again. If i can call the constructor again is this a good practice or should i avoid such a use of the constructor. Here is some test code.
[CODE=cpp]
//code created and tested in VS 2003
#include <iostream>
using namespace std;
class TestClass
{
public:
TestClass();
~TestClass();
void ModifyVariables (int, int);
void PrintVariables( );
private:
int Variable1;
int Variable2;
};
TestClass::Test Class()
{
Variable1 = 100;
Variable2 = 100;
}
TestClass::~Tes tClass()
{
Variable1 = 0;
Variable2 = 0;
}
void TestClass::Modi fyVariables(int Mod1, int Mod2)
{
Variable1 += Mod1;
Variable2 += Mod2;
}
void TestClass::Prin tVariables()
{
cout<<Variable1 <<" "<<Variable2<<e ndl;
}
int main()
{
TestClass TestObject;
TestObject.Prin tVariables();
TestObject.Modi fyVariables(20, 45);
TestObject.Prin tVariables();
//TestObject.Test Class(); //can't do
TestObject.~Tes tClass(); //works just fine.
TestObject.Prin tVariables();
TestObject.Modi fyVariables(120 , 145);
TestObject.Prin tVariables();
return 0;
/* OUPUT:
100 100
120 145
0 0
120 145
*/
}
[/CODE]
why am i able to call the destructor like that and not the constructor?
How can i call the constructor to reinit the variables to 100? or do i have to write a separate function?
[CODE=cpp]
//code created and tested in VS 2003
#include <iostream>
using namespace std;
class TestClass
{
public:
TestClass();
~TestClass();
void ModifyVariables (int, int);
void PrintVariables( );
private:
int Variable1;
int Variable2;
};
TestClass::Test Class()
{
Variable1 = 100;
Variable2 = 100;
}
TestClass::~Tes tClass()
{
Variable1 = 0;
Variable2 = 0;
}
void TestClass::Modi fyVariables(int Mod1, int Mod2)
{
Variable1 += Mod1;
Variable2 += Mod2;
}
void TestClass::Prin tVariables()
{
cout<<Variable1 <<" "<<Variable2<<e ndl;
}
int main()
{
TestClass TestObject;
TestObject.Prin tVariables();
TestObject.Modi fyVariables(20, 45);
TestObject.Prin tVariables();
//TestObject.Test Class(); //can't do
TestObject.~Tes tClass(); //works just fine.
TestObject.Prin tVariables();
TestObject.Modi fyVariables(120 , 145);
TestObject.Prin tVariables();
return 0;
/* OUPUT:
100 100
120 145
0 0
120 145
*/
}
[/CODE]
why am i able to call the destructor like that and not the constructor?
How can i call the constructor to reinit the variables to 100? or do i have to write a separate function?
Comment