Reputation: 3109
I have written a program that has a class with a constructor and destructor written with couts and cins.
The class contains a run() function which I am using as my menu. From the menu, I want to have the user select the option to 1. Test the constructor (creates an instance from the class) and 2. Test the destructor (exits the menu and destructs at the end of main).
Here is my dilemma.
In main() in order for me to use the run() function, I have to create and instance of the class. However, I am using templates. ie. Class<classType> classTypeRun
.
In order for me to create an instance to be able to use run() I have to specify a classType, and this will call the constructor, which I do not want. I only want the constructor to run when the user selects it from the menu.
What is the most efficient way to go about this?
Should I create an inheritaned class just for the run() function?
Upvotes: 1
Views: 839
Reputation: 19042
Make run()
a free function, like this:
template <class T>
class MyT
{
public:
MyT(const T& v) : val_(v) {}
const T& get() const {return val_;}
private:
T val_;
};
int run()
{
int opt;
cout << " 1) Create\n 2)Destroy\n";
cin >> opt;
cin.ignore();
return opt;
}
int main()
{
int opt = 0;
std::auto_ptr<MyT<int>> t;
do
{
// call the menu...
opt = run();
// if the user selected option 1, and we haven't
// already constructed our object, do so now.
// (Calls MyT<int>())
if(opt == 1 && !t.get())
t.reset(new MyT<int>(10));
// if the user selected option 2 and we have
// already constructed our object, delete it now
// (Calls ~MyT<int>())
if(opt == 2 && t.get())
t.reset(0);
}
while(2 != opt);
}
Upvotes: 2