Typecasting to a SubClass

I have a parent class and subclass partially declared here:
1
2
3
4
5
class Object {
public:
	Object();
	virtual Object clone() const;
};


1
2
3
4
5
6
7
8
9
10
11
12
class Card : public Object {
public:
	Card();
	virtual Object clone() const;
	virtual int getValue() const;
};

Object Card::clone() const {
	Card card;
	card.copy(*this);
	return card;
}


I was wondering how to typecast the return value of Card::clone() into a Card so I can do something like this:

1
2
	Card o;
	((Card) o.clone()).getValue()
You will need to use pointers to achieve this, have clone return an object* instead of an object:

1
2
3
4
Card* o = new Card;
Object* obj = NULL;
obj = dynamic_cast <Object*> (o.clone());
obj->/*...*/
Make clone() return a pointer, not an object.
1
2
3
Card *c=(Card *)obj.clone();
/*...*/=c->getValue();
delete c;

Although the logical thing would be for obj to be a pointer from the beginning:
/*...*/=((Card *)obj)->getValue();
Last edited on
When should a function return a pointer to a new object and when should it just be a referece?
If you're going to use polymorphism, you need to use pointers.
@SMuzzlim4:

You have to be careful about object slicing.

Card::clone() is useless to users because it slices the Card object by effectively discarding
the "Card" portion of the object and leaving just the "Object" portion.

For this reason, the clone pattern always returns pointers.
Topic archived. No new replies allowed.