Upper casting problems

Hi, I do not understand the upper casting on the code below. Can you explain me why static_cast(a_cat) -> MakeSound(); and static_cast(a_dog) -> MakeSound();
are both pointing at the Makesound of the class Pet? ( as far as I have learned so far, static cast is supposed to point at the class cat and dog, why is that not happening here?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
using namespace std;
class Pet {
protected:
	string Name;
public:
	Pet(string n) { Name = n; }
	void MakeSound(void) { cout << Name << " the Pet says: Shh! Shh!" << endl; }
};
class Cat : public Pet {
public:
	Cat(string n) : Pet(n) { }
	void MakeSound(void) { cout << Name << " the Cat says: Meow! Meow!" << endl; }
};
class Dog : public Pet {
public:
	Dog(string n) : Pet(n) { }
	void MakeSound(void) { cout << Name << " the Dog says: Woof! Woof!" << endl; }
};
int main(void) {
	Cat *a_cat;
	Dog *a_dog;
	
	a_cat = new Cat("Kitty");
	a_dog = new Dog("Doggie");
	a_cat -> MakeSound();
	static_cast(a_cat) -> MakeSound();        /// I don't know why the "Makesound" is from class Pet, instead of from Cat.
	a_dog -> MakeSound();
	static_cast(a_dog) -> MakeSound();      /// I don't know why the "Makesound" is from class Pet, instead of from Dog.
	return 0;
}
You need to make MakeSound virtual in your definition of Pet.
You should probably also give Pet a virtual destructor, too, since you're inheriting from it.
Then you'll get the output you think you should be getting.

And static_cast(a_cat) is a syntax error; did you mean static_cast<Pet*>(a_cat)?
yes i meant static_cast<Pet*>(a_cat) and static_cast<Pet*>(a_dog).
So if i make Makesound "virtual" in my definition of Pet, then it will be overridden hence, static casts I have made in the main function will refer to the Makesound functions of the classes Cat and Dog. tell me if I understood this wrong.
Topic archived. No new replies allowed.