How do I don't write the function 3 times? | SoloLearn: Learn to code for FREE!

+1

How do I don't write the function 3 times?

Code: switch(x) { case 1: Class1 obj; obj.somefunc(); break; case 2: Class2 obj; obj.somefunc(); break; case 3: Class3 obj; obj.somefun(); break; } All the classes are derived from: class Base { public: somefunc() {} } ; How do I write the function somefunc() only once and not three times? Because if I declare the object in the switch statment and then write obj.somefunc() (out of the switch statment) then I get an Error. Could someone Please tell me how I do it???

1/6/2020 4:47:41 PM

Kamil Kasperek

3 Answers

New Answer

+4

Looks like a case for polymorphism. It goes something like this: #include <memory> std::unique_ptr<Base> obj; switch( x ) case 1: obj.reset( new Class1 ); break; case 2: obj.reset( new Class2 ); break; ... etc if( obj ) obj->somefunc(); ( Don't forget to define a virtual destructor in your Base class! )

+2

write obj. somefunc() after switch case... swich() { ... } obj. somfunc() ; Make sure obj exist by one of switch case..

+2

First thing whenever you are posting some code snippet ensure it is exactly what you want to post. You have written class1 obj, class2 obj, class3 obj. Is that really 3 classes? What exactly you want to do? If it is just one object and you want to call it 3 times, then you can declare the object before switch statement. If they are indeed 3 different objects of different classes or otherwise also if you must create 3 different objects then wrap your cases in brackets, as C++ does not allow declaring new variables in switch-case without brackets. So do case 1: { class1 obj; some code obj.somefunc(); break; }