Re: Hmm... inheritence... hmmm
From: Siemel Naran (SiemelNaran_at_REMOVE.att.net)
Date: 10/19/04
- Next message: Old Wolf: "Re: No Macros, No for loops, Pure C++"
- Previous message: Alf P. Steinbach: "Re: contradiction in TC++PL?"
- In reply to: JKop: "Hmm... inheritence... hmmm"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 19 Oct 2004 03:15:40 GMT
"JKop" <NULL@NULL.NULL> wrote in message news:4AMcd.37317
> I know the following would work, but it seems a bit inefficent to me:
>
> #include <typeinfo>
>
> virtual void Mate(Mammal &mammal)
> {
> //Wait a minute, I'm not mating unless
> //it's with another dog!
>
> try
> {
> Dog& doggy = dynamic_cast<Dog&>(mammal);
>
> //Now perform mating
> }
> catch( std::bad_cast )
> {
>
> }
> }
>
>
> Any thoughts on this?
Why do you think the above is inefficient? You can implement double
dispatch, but it would probably be slower than the use of dynamic_cast.
> Dog& doggy = dynamic_cast<Dog&>(mammal);
The above is not symmetric. The line does not throw an exception if mammal
is a class Dog or any derived from it. This allows a dog to mate with
another class that is derived from dog. Thus
dog.mate(deriveddog);
would work without throwing a bad_cast exception. Yet deriveddog.mate(dog)
would throw a bad_cast exception.
Maybe the correct thing is to use typeid.
As a matter of style, I'd make Mate a non-member function that checks if the
types are compatible, then calls the virtual function of the class, which
should be private or protected. These virtual functions may assume that the
types are compatible, and can use static_cast to convert a Mammal& to a
Dog&.
void mate(const Mammal& lhs, const Mammal& rhs) {
assert(typeid(lhs) != typeid(rhs));
return lhs.mate(rhs);
}
void Dog::mate(const Mammal& rhs) {
const Dog& that = static_cast<const Dog&>(rhs);
}
- Next message: Old Wolf: "Re: No Macros, No for loops, Pure C++"
- Previous message: Alf P. Steinbach: "Re: contradiction in TC++PL?"
- In reply to: JKop: "Hmm... inheritence... hmmm"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|