Saturday, May 22, 2010

How do a method of a class understands the data type of an argument in C++?

I want a method of a class to work with two different data types passed as an argument.


eg: Class::foo(int) and Class::foo(char)


*Polymorphism will create code redundancy.


*Tempaltizing the class would not be possible because the class declaration and definition are in separate files.


*The argument of the class can not be pointers.

How do a method of a class understands the data type of an argument in C++?
You cannot make a function that will work with two diff. data types as argument. In that case you'll need to do either


* Use polymorphism (don't consider this as code redundancy, It actually makes your code cleaner and easier to use.)


or


*Make the function with two arguments like foo(int, char). Then if you need int use the int argument and char otherwise.
Reply:you have closed almost all the ways to do that job, atleast pointers should have been allowed.





Anyways, try using RTTI or Run-Time Type Identification





To obtain an object's type (including the built-in types and class types that you create), use 'typeid'. You must include the header %26lt;typeinfo%26gt; in order to use typeid





the prototype of typeid is:





type_info typeid(object)





you can use the following public members of type_info class to determine the type:


i) bool operator==(const type_info %26amp;obj);


ii) bool operator!=(const type_info %26amp;obj);


iii) const char *name();
Reply:If you follow Arc's suggestion and use Polymorphism, you can minimize code redundancy by creating an additional function to contain the redundant code. For example, if conversion is called for, you could call foo(char), convert the char to int, then call foo(int). Or if conversion is not called for, you could have foo(char) and foo(int), then have each function call a third function which executes the code which would be common to both. It's hard to tell you exactly the best approach without knowing the code to be executed, but I hope that helps.
Reply:screw programming it's too confusing

strawberry

No comments:

Post a Comment