4 Answers
4

Dog() creates a Dog object. If you were to call Dog().makeSound(), it would print "bark" as you expect it to.

The problem is that you are initializing the badDog, which is an object of type Animal, with this Dog. Since the Animal can only contain an Animal and not anything derived from Animal, it takes the Animal part of the Dog and initializes itself with that.

The type of badDog is always Animal; it can never be anything else.

The only way you can get polymorphic behavior in C++ is using pointers (as you have demonstrated with your goodDog example) or using references.

A reference (e.g., Animal&) can refer to an object of any type derived from Animal and a pointer (e.g., Animal*) can point to an object of any type derived from Animal. A plain Animal, however, is always an Animal, nothing else.

Some languages like Java and C# have reference semantics, where variables are (in most cases) just references to objects, so given an Animal rex;, rex is really just a reference to some Animal, and rex = new Dog() makes rex refer to a new Dog object.

C++ doesn't work that way: variables don't refer to objects in C++, variables are objects. If you say rex = Dog() in C++, it copies a new Dog object into rex, and since rex is actually of type Animal, it gets sliced and just the Animal parts get copied. These are called value semantics, which are the default in C++. If you want reference semantics in C++, you need to explicitly use references or pointers (neither of these are the same as references in C# or Java, but they are more similar).

Even though "someone" was unhappy with this answer (SO people seem to like everything handed to them and get pissy when it isn't) this is the best way to go about fixing your problem. You seriously need to understand this term in its full if your object is to actually learn wtf you're doing. It's the topic of numerous online articles and a chapter in Myers's first book.
–
Crazy EddieDec 9 '10 at 22:30

9

I didn't downvote you, but I can understand those who did -- "google something" doesn't fit as an answer on SO, post it as a comment if you want to.
–
casablancaDec 9 '10 at 22:36

I didn't say "google something", I told them to google the exact term they need to get the results they need in order to learn what they did wrong.
–
Crazy EddieDec 9 '10 at 22:39

2

Did you try "Googling for 'slicing'"? It's not as straightforward as you might expect. Hint: non-programmers slice things, too. But @casablanca, I think it does fit when a specific link is provided and the first few hits have been verified to answer the question reasonably well.
–
Karl KnechtelDec 9 '10 at 22:59