#include <iostream>
usingnamespace std;
//class
class Firstclass
{
private:
Firstclass(); //constructor
~Firstclass(); //destructor
public:
int singleton;
void output();
static Firstclass & instance();
};
//newfunc
Firstclass & Firstclass::instance()
{
static Firstclass thing;
return thing;
}
//func for class
void Firstclass::output()
{
cout << singleton << endl;
singleton ++;
}
void static_test()
{
staticint a = 1;
cout << a << endl;
a++;
}
//func for construc
Firstclass::Firstclass(void)
{
singleton = 0;
cout << "Object has been constructed!" << endl;
}
//func for destruct
Firstclass::~Firstclass(void)
{
cout << "Object has been destructed!" << endl;
}
int main(int argc, char * argv[])
{
//Counter
for(int i = 0; i < 3; i++)
{
static_test();
}
for (int j = 0; j < 3; j++)
{
Firstclass::instance().output();
}
cout << "Main function is about to exit.. " << endl;
return 0;
}
Doesn't it allocate the class static variable to the heap, thus executing its algorithm then destroying it when the program ends - or. What exactly does it tell me? When the static variable is initialized, it takes place first before any of my other functions? I'm so confused.
this is initialized the first time the function is called (in your case, when main() reaches line 65), and destroyed at the end of the program (after main() exits, like all other statics)
Same for
1 2 3
void static_test()
{
staticint a = 1;
which is a function-local static, set to 1 the first time static_test() is called. The line that sets it to 1 is then skipped the next two times static_test() is called.
Awesome thank you so much. What about when they are asking me, "Does your object get deallocated in a reasonable way?" They are asking me "Has your object been reasonable destroyed?" correct? Wouldn't my answer be of course it gets reasonably destroyed, that's what the destructor does...How would it not be reasonable?
Because I noticed the object is not being destructed until after the main function exits. Would this be unreasonable? Should it be deconstructing before the main function exits?
How would the output of the program be different if the return type of my instance method was not pass-by-reference? Why?
How would I make my instance method not "pass-by-pass"? doesn't that just mean that I have &reference variables being passed in my argument in the instance method? Like how could I test this by changing something in my class?