[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppTypeSwitching

(C++) Type switching

Type switching means that in a class there is an internal variable stored to embody the type of the class. The a switch-statement is used to conclude its behaviour.

'Avoid type switching; prefer polymorphism' [1]

An example is the code below, followed by the equivalent classes using polymorphism.

  1. include <iostream>
  2. include <vector>
enum MyClassType { happy, sad, angry }; class MyClass { private: const MyClassType mType; public: MyClass(const MyClassType& state) : mType(state) { ; } void sayHello() const { switch (mType) { case happy : std::cout << "Hello!!!" << std::endl; break; case sad : std::cout << "... hello ..." << std::endl; break; case angry : std::cout << "HELLO!!!" << std::endl; break; default: assert(!"Unknown value of mType"); std::exit(1); } } }; int main() { std::vector<MyBaseClass* > myVector(3); myVector[0] = new MyClass(happy); myVector[1] = new MyClass(sad); myVector[2] = new MyClass(angry); const int size = myVector.size(); for (int i=0; i!=size; ++i) myVector[i]->sayHello(); //Clean up for (int i=0; i!=size; ++i) delete myVector[i]; }


The correct equivalent:

  1. include <iostream>
  2. include <vector>
struct MyBaseClass { virtual void sayHello() const = 0; }; struct MyHappyClass : public MyBaseClass { void sayHello() const { std::cout << "Hello!!!" << std::endl; } }; struct MySadClass : public MyBaseClass { void sayHello() const { std::cout << "... hello ..." << std::endl; } }; struct MyAngryClass : public MyBaseClass { void sayHello() const { std::cout << "HELLO!!!" << std::endl; } }; int main() { std::vector<MyBaseClass* > myVector(3); myVector[0] = new MyHappyClass; myVector[1] = new MySadClass; myVector[2] = new MyAngryClass; const int size = myVector.size(); for (int i=0; i!=size; ++i) myVector[i]->sayHello(); //Clean up for (int i=0; i!=size; ++i) delete myVector[i]; }


Code links

Reference



last edited (November 18, 2006) by bilderbikkel, Number of views: 3528, Current Rev: 9 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.