I'm trying to understand how polymorphism, object slicing and pointers work in this block of code. I'm working in Visual Studio.
#include <iostream>
class Man {
public:
virtual void speak() { std::cout << "I'm a man." << "\n"; }
private:
};
class Soldier : public Man {
public:
virtual void speak() { std::cout << "I'm a soldier." << "\n"; }
private:
};
int main() {
Man man1;
Soldier soldier1;
man1 = soldier1;
std::cout << "Man1: "; man1.speak();
Man *man2 = new Man;
Man *soldier2 = new Soldier;
man2 = soldier2;
std::cout << "Man2: "; (*man2).speak();
Man *man3 = new Man;
Soldier *soldier3 = new Soldier; // "Man *soldier3 = new Soldier;" will give the same output.
*man3 = *soldier3;
std::cout << "Man3: "; man3->speak();
return 0;
}
The output is:
Man1: I'm a man.
Man2: I'm a soldier.
Man3: I'm a man.
I did some searching and learned about the concept "object slicing". I guess that is what has happened to man1 and man3. But wait, didn't we use the keyword "virtual" in all of those classes? Shouldn't man1 and *man3 first find out what class of object they each are, and call the specific overriding speak()?
Or is it because slicing has already happened at the = operator, at the line:
man1 = soldier1;
And the line:
*man3 = *soldier3;
And man1 and *man3 are really just Man objects now?
A fellow coder guessed it is because the = operator is only assigning the right-hand-side value to a copy of the left-hand-side variable. It needs to be confirmed still.
Aside from those, the goal I want to achieve is to copy that Soldier object to a different memory address, unlike how I point two pointers at one same memory address, in the case of man2 and soldier2.
Finally, I wonder why slicing doesn't happen in part2, and what really happens at syntax like this:
Man *soldier2 = new Soldier;
Seriously what does it do..?
I appreciate any insight on this. I'm a basic C++ programmer :) <