+ 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???

6th Jan 2020, 4:47 PM
Kamil Kasperek
3 Antworten
+ 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! )
6th Jan 2020, 4:59 PM
Dennis
Dennis - avatar
+ 3
write obj. somefunc() after switch case... swich() { ... } obj. somfunc() ; Make sure obj exist by one of switch case..
6th Jan 2020, 4:59 PM
Jayakrishna 🇮🇳