473,772 Members | 3,712 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to judge if two objects have the same type?

Dear All,

Assume I have a class named Obj.

class Obj
{ };

And a class named Shape which is derived from Obj.

class Shape: public Obj
{ };

And a class named Color which is also derived form Obj.

class Color: public Obj
{ };

I have two objects.

Obj *pA = new Shape or Color;
Obj *pB = new Shape or Color;

How can I know if they have the same type?

I appreciate your help.

Shuisheng

Nov 30 '06
15 7626

Grizlyk wrote:
Salt_Peter wrote:
Unlike Java, Obj base is not needed since C++ has
a much more resilient and powerful system called templates<>.

I want to notice, that code, written with templates<>, is _compile time
template_ and can not replace (must just works together), of course,
any _runtime templates_.
Yes, thats right. templates<is a system created to help a coder use
code.
Specially when the coder did *not* write the code.
Templates also lets a creator write rules for the benefit of the user.
In other words: the compiler can help you code if you do it with
templates.
Dynamic casts is a system that has your code thrown out the door by
your client.
Nobody has the time to read 10,000 lines of code to use your program.
Why don't you take up the issue with a professional Java programmer?
Because even the Java programmer will agree.
Dynamic casting is a nightmare for you - imagine the poor client.
>
In order to write class for _runtime template_ you must define a class
with the help of base class interface inheritance (public inheritance).
In order to use any function as _runtime template_, you must use for
all its runtime objects (variables) only pointers or references of its
public base class.

Of course, you must use inheritance _only_ for oo design necessity.
Using typeid? Thats downright wrong, unsafe and complicated.

One can do like this:
void foo(Obj& obj)
{
Shape* sh=dynamic_cast <Shape*>(&obj );
if(sh){ /* Shape-specific code */ }

Color* co=dynamic_cast <Color*>(&obj );
if(co){ /* Color-specific code */ }
}
C++ needs not detect what type a given instance "belongs to". Thats
because an instance is an object. Its self aware. It already knows what
it can and cannot do. Thats the basis of OO design. making everything
an Obj defeats the purpose.

One part of program can create object (and know _real_ object's class),
all other parts of program can use the created object (and know only
object's _base_ class), but some units of the others can use real
object's class again and are forced to cast base class reference to
derived class, and it can be done with dynamic_cast<>.

For instance, there is the design pattern named "decorator" . In order
to get special interface of "decorated" object we are forced to cast to
derived class.

Also there is the design pattern using "pointer to indefinite class"
(for store objects and reorder them in storage (sorting etc)). In order
to get true interface of "stored" object we are forced to cast to
derived class.
Dec 1 '06 #11
I think there're many solutions to implement type recognition
and it depends on the support state of your compiler, platform(s)
and its third party libraries.

- are you able/allowed to use RTTI?
- are you able/allowed to use Exceptions?

If you've problems as listed you can not use typeid nor dynamic_cast!
Proving a base class and an additional header with an enum of types you
can define in you base a
"virtual const eType typeId() const = 0;"

All classes derived from the base have to implement returning/adding
another enum value. Its's very simple solution!
(I don't say it's the best)

Dec 1 '06 #12

Grizlyk wrote:
Salt_Peter wrote:
Unlike Java, Obj base is not needed since C++ has
a much more resilient and powerful system called templates<>.

I want to notice, that code, written with templates<>, is _compile time
template_ and can not replace (must just works together), of course,
any _runtime templates_.

In order to write class for _runtime template_ you must define a class
with the help of base class interface inheritance (public inheritance).
In order to use any function as _runtime template_, you must use for
all its runtime objects (variables) only pointers or references of its
public base class.
And how do you think the typeid is determined?

Yes, thats right. templates<is a system created to help a coder use
code. Specially when the coder did *not* write the code.
Templates also lets a creator write rules for the benefit of the user.
In other words: the compiler can help you code if you do it with
templates.
Dynamic casts is a system that has your code thrown out the door by
your client.
Nobody has the time to read 10,000 lines of code to use your program.

Why don't you take up the issue with a professional Java programmer?
Because even the Java programmer will agree.
Dynamic casting is a nightmare for you - imagine the poor client.
>
Of course, you must use inheritance _only_ for oo design necessity.
Using typeid? Thats downright wrong, unsafe and complicated.

One can do like this:
void foo(Obj& obj)
{
Shape* sh=dynamic_cast <Shape*>(&obj );
if(sh){ /* Shape-specific code */ }

Color* co=dynamic_cast <Color*>(&obj );
if(co){ /* Color-specific code */ }
}
really, one can do this instead:

struct Shape {
Color color;
Shape() : color() { } // whatever the default color is
Shape(const Color& col) : color(col) { }
};

Triangle : public Shape
{
Triangle() { }
Triangle(const Color& col) : Shape(col) { }
};

int main()
{
std::vector< Triangle vt(1000000); // done - 1 million triangles
}

Thats one million Triangles, all initialized and valid, default color
and ready for action.
Care to try to reproduce that with your code? Oh yes, and i've got 100
more shapes for you and 1000 different colours. Very easy for a
template. You need what: 10,000 lines of code? 1 million lines of code?
How much?

Here, now i need 1 million more triangles and they must all be Color
black:

Color black(...); // where ... is whatever color black requires
std::vector< Triangle blktriangles(10 00000, black); // done

How many more lines of code do *you* need now? Note: i didn't change a
single line of the above classes to make that work. Beats the hell out
of using a dynamic cast, doesn't it?
>
C++ needs not detect what type a given instance "belongs to". Thats
because an instance is an object. Its self aware. It already knows what
it can and cannot do. Thats the basis of OO design. making everything
an Obj defeats the purpose.

One part of program can create object (and know _real_ object's class),
all other parts of program can use the created object (and know only
object's _base_ class), but some units of the others can use real
object's class again and are forced to cast base class reference to
derived class, and it can be done with dynamic_cast<>.

For instance, there is the design pattern named "decorator" . In order
to get special interface of "decorated" object we are forced to cast to
derived class.

Also there is the design pattern using "pointer to indefinite class"
(for store objects and reorder them in storage (sorting etc)). In order
to get true interface of "stored" object we are forced to cast to
derived class.
Dec 1 '06 #13
BobR wrote:
>
Default User wrote in message ...
mv*******@gmail .com wrote:
if( typeof(pA) == typeof(pB ) { /* the same */ }

Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or the group FAQ list:
<http://www.parashift.c om/c++-faq-lite/how-to-post.html>

I was just thinking about a reply for such people:

" YOU IDIOT!! Do you realise you just screwed up a perfectly good
thread!! Now we'll have to reformat it and start over!! FAQ YOU!!"

"Please don't top-post" just isn't working since Google screwed up in
a Gates way.
I've had reasonably good results with the above message, and a similar
one on clc. Whenever I post just this information, I add "- TPA" to the
subject. That way regulars can filter the messages if they choose.

Brian
Dec 1 '06 #14
Noah Roberts wrote:
but some units of the others can use real
object's class again and are forced to cast base class reference to
derived class, and it can be done with dynamic_cast<>.
They have no business accepting the base class interface then.
There are cases of program design necessity. For instance, it can be
pair of classes developed together: "creater"-"user". They improve
integrated base functionality of existing program, so no one unit of
existing (and may be compiled) program do not know about new derived
classes and "creater"-"user" must communicate "over" pointer to base
class.
Huh? Decorator is a way to extend functionality through *composition*.
It implements the interface of the decorated object and becomes a
mediator, performing extra functionality as needed.
It is true, the "implementa ion" of the pattern goal can be done by
"compositio n of the decorated object", but "compositio n" can be not
enough.

You have written "implements the interface of the decorated object".
Not only "implement" , it is better to say "inherit the interface of the
decorated object or its base class". It is good if you can limit
decorator interface by interface of its decorated object.

But sometimes it is really imposible - we need to adjust own decorator
properties (they have no sense and they do not exist for decorated
object) _after_ decorator have created, so we need extra "decorator"
interface and a way to get the interface from pointer to the class of
"decorated" object.
Also there is the design pattern using "pointer to indefinite class"
(for store objects and reorder them in storage (sorting etc)).
There is an any object container in boost. I don't see a whole lot of
use in that object per se. I have used the constructs it uses to do
its job in some stuff I worked on wrt units and dimensional
analysis.... to allow an object of any unit type to exist (when units
are separate static types) and I didn't use any of the casting or type
identification stuff.
"object per se"? "wrt"? What use what? Sorry, I do no know english well
and do not understand what do you speak about :)
Besides stuff like that I don't see how it has
much use in well designed software....
I do not understand the goal of the special "stuff", you have spoken
about, but i can describe the design pattern "pointer to indefinite
class". In order to describe any design pattern, you need to define at
least three things:
1. context to apply the pattern
2. the goal of the pattern
3. the way of the pattern implementation

For design pattern "pointer to indefinite class":
1. not shared ot local-shared libraris of program with many quantity
(for example 100)
of different types and classes, which must be placed in lists, arrays
etc

2. decrease code size :) (do not want to create 100 equal copies of
lists, arrays etc) by making single class for each type of container
(list, array etc) to keep "object of indefinite class", by allowing
single copy for each type of "algorithm" methods, based on "interface
of indefinite class".

3. i think it is out of "comp.lang. c++" topic and "How to judge if two
objects have the same type" too, but say some words:
a)"interface of indefinite class" depends from concrete program (so we
get "local-shared" pattern context), for example, the easy interface
are virtuals: create/copy/clone constructors and destructor.

b)we inherite all "containera ble" types of the program from
program-global base class "indefinite class"

c)type check and type-dependent interdace for "remove/insert_correct
type_object" we make with template<(templ ate<inherit
"concrete_conta iner" from "container_of_i ndefinit_class" ), so we can't
get "runtime bad_cast" and each template<copy of code do chiefly only
dynamic_cast (so can not be optimized more).

Dec 2 '06 #15

Salt_Peter wrote:
And how do you think the typeid is determined?
I think nothing about typeid and its implementaion :) I want only to
notice, that template<can not replace inheritance.
Templates also lets a creator write rules for the benefit of the user.
In other words: the compiler can help you code if you do it with
templates.
I think "can help you code" is very magical and vague definition. Any
improper use of teplate<will give your in better case many
unnecessary copies of code. You can or must use teplate<at least:

1. due to C++ strict type control
There are object-oriented languges, which no need template<for type
conversion, due to runtime type identification and message posting. For
C++ you can not declare interface of base class, if class members of
the interface have return's or parameter's type of unknown or derived
class. Template<for type conversion must be as easy, as you can do,
so ideal case is only casting to proper class. Template<for type
conversion will be instanced for each class as class's own copy of
code.

2. for "general programming"
That is good, to declare any type ("general goal") of code templates
with the help of template<>, but you must not instance each "general
goal" template<direct ly "as is". It is much better ro prefer _runtime
remplate_, so you must do instance only for one or two copyies of
"general goal" code with template<as base clases for all other
classes in your program.
Dynamic casts is a system that has your code thrown out the door by
your client.
Nobody has the time to read 10,000 lines of code to use your program.
Dynamic casting is a nightmare for you - imagine the poor client.
Dynamic casting is quite low-level feature of C++, it is absolutely
necessary for interface implementaion but no one force anybody do
dynamic casting in each line of you program. In good system of classes
dynamic casting can be hidden and incapsulated by interface of each
class.
really, one can do this instead:
You are right, but the man asked not his classes desing way, but
runtime class type identyfication (Is it maybe FAQ question? I do not
know). No one can guess his real class hierarhy.

Dec 2 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1436
by: Esmeralda Weatherwax | last post by:
For 10 days now, a new online judge (a system for the verification of the correctness of submitted programs, which solve problems selected from a repository) has been available to the public. The Sphere Online Judge (SPOJ) is available at spoj.sphere.pl, and supports solutions written in 18 different programming languages including Haskell, Ocaml, Prolog, Icon and Ruby. At present, well over half the problems can be solved in...
0
1809
by: Esmeralda Weatherwax | last post by:
For 10 days now, a new online judge (a system for the verification of the correctness of submitted programs, which solve problems selected from a repository) has been available to the public. The Sphere Online Judge (SPOJ) is available at spoj.sphere.pl, and supports solutions written in different programming languages including Python.
49
2898
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
58
4696
by: Jeff_Relf | last post by:
Hi Tom, You showed: << private const string PHONE_LIST = "495.1000__424.1111___(206)564-5555_1.800.325.3333"; static void Main( string args ) { foreach (string phoneNumber in Regex.Split (PHONE_LIST, "_+")) { Console.WriteLine (phoneNumber); } } Output: 495.1000
161
7882
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.. (After reading that
6
2273
by: Morgan Cheng | last post by:
I know that HttpWebRequest.GetResponse() generates a HttpWebResonse. The response has one ContentType property. But the property is just decided by http response header. It is possible that the content is actually HTML, while the ContentType is "image/jpeg". Is there any effective way to judge whether the response type is truly "text"? I have a idea to read the first several bytes of the response stream; and check whether they are real...
26
1837
by: momobear | last post by:
hi, I am puzzled about how to determine whether an object is initilized in one class, anyone could give me any instructions? here is an example code: class coffee: def boil(self): self.temp = 80 a = coffer() if a.temp 60:
27
2568
by: SasQ | last post by:
Hello. I wonder if literal constants are objects, or they're only "naked" values not contained in any object? I have read that literal constants may not to be allocated by the compiler. If the Standard is saying that "object is a region of storage", I deduce from that that literal constants aren't objects because they may not be alocated as regions of storage in the memory.
19
10763
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is there an existing adapter? Thanks, Daniel.
0
9620
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9912
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.