Re: C++ class confusion
On Dec 21, 10:57 am, Juha Nieminen <nos...@thanks.invalid> wrote:
Bart C wrote:
Animal X
X=new Cat
I would have thought X was an Animal and not a Cat.
But a Cat *is* an Animal, and thus can be used anywhere an Animal is
expected. That's basic OOP.
Yes and no. In his example, X is an object of Animal type. A
given object can never, ever change its (most-derived) type.
Of course, the next line, with new, suggests that what he really
wanted was a pointer. A pointer to an Animal can in fact point
to a Cat, and (providing that the functions are virtual) will
act like a cat.
For the rest, there's a lot, lot more to it than that, and I
fear that Bart will have to get some books, because it's really
a lot more than one can explain in an answer here. The
important C++ relevant parts are, however, that in C++,
polymorphism (using something that is really a Cat where the
original program only knows about Animal) only works through
pointers and references, that C++ (like the other OO languages I
know) doesn't allow an actual object to ever change its type,
once it has been constructed, and the C++, unlike most "pure" OO
languages, supports and uses value semantics by default; if you
don't say otherwise, a declaration declares an actual object,
not a reference to an object.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34