[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

downcasting in c++ I couldnt success

emre esirik(hacettepe computer science and engineering)

10/5/2008 7:27:00 AM

class Animal {


};

class Dog : public Animal {

};

int main ( )
{
stack<Animal> mystack;
Animal *x = new Dog( );
mystack.push(*x);


Animal y = mystack.top( );

Dog z = ( Dog ) y ; // this line doesnt work, how could I fix it?

return 0;
}
2 Answers

Kai-Uwe Bux

10/5/2008 7:36:00 AM

0

eMRe wrote:

> class Animal {
>
>
> };
>
> class Dog : public Animal {
>
> };
>
> int main ( )
> {
> stack<Animal> mystack;
> Animal *x = new Dog( );
> mystack.push(*x);

Containers in C++ have value semantics, i.e., the line above only copies the
Animal part of the Dog object. What the stack contains is an honest to God
Animal and no Dog.

>
> Animal y = mystack.top( );

That way, you retrieve the Animal you stored.

> Dog z = ( Dog ) y ; // this line doesnt work, how could I fix it?

You should get rid of the C-style cast. But anyway, the line above should
not succeed. The Dog part of the object has been lost when you stored it in
the stack.

> return 0;
> }


If you need a polymorphic stack, you might try

stack< Animal * >


Technically, if D is derived from T, there are two natural maps:

a) a projection from values of type D to values of type T. This map is
called "slicing".

b) an injection from values of type D* to values of type T*. This map is
what people usually call the is-a-relation. It is important to see that it
holds on the level of pointers (or references, but that does not matter in
the context of containers).


Best

Kai-Uwe Bux

James Kanze

10/6/2008 9:29:00 AM

0

On Oct 5, 9:36 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> eMRe wrote:
> > class Animal {
> > };

> > class Dog : public Animal {
> > };

> > int main ( )
> > {
> > stack<Animal> mystack;
> > Animal *x = new Dog( );
> > mystack.push(*x);

> Containers in C++ have value semantics, i.e., the line above
> only copies the Animal part of the Dog object. What the stack
> contains is an honest to God Animal and no Dog.

> > Animal y = mystack.top( );

> That way, you retrieve the Animal you stored.

He retrieves a copy of the Animal he stored. Not the Animal
itself. Even if mystack had type stack<Dog>, all he'd get is a
copy of the Animal part of the Dog in the stack, because his
variable is of type Animal.

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34