0

Let's say we have two classes Employee and Manager where Manager is derived from Employee. What is the difference between e2 and e3 (aside from one being a pointer)

Manager m;
Employee e2 = m;
Employee* e3 = &m;

I have noticed that if Manager overrides a virtual method print in Employee, then e2.print() invokes Employee::print whereas e3->print() invokes Manager::print() (i.e. polymorphism does not work without the pointer). But I'm not sure what exactly is happening here.

user798275
  • 441
  • 6
  • 14
  • If Manager is derived from Employee, your class design is broken if Employee isn't abstract. Non-leaf classes in a polymorphic hierarchy should be abstract. – Kerrek SB Jul 27 '15 at 15:05
  • 1
    Perhaps read this: [What is Object Slicing?](https://stackoverflow.com/questions/274626/what-is-object-slicing). Your `e2` is only a fragment of his former-self (literally). – WhozCraig Jul 27 '15 at 15:05
  • 2
    Neither is a "casting method". – Kerrek SB Jul 27 '15 at 15:06
  • I do not believe this is a duplicate of 274626. That questions asks, "what is object slicing". This one asks the difference between two syntactical constructs (one of which results in object slicing, but that is not explicit in the question). – davmac Jul 28 '15 at 09:48

1 Answers1

3

The first:

Employee e2 = m;

... is a copy initialisation. It creates a new Employee object, and calls the copy constructor to initialise it from the other object m. (In general this kind of construction - where you intialise an object from an object of derived type - is prone to some loss of information; this may or may not matter, depending on the design and the purpose of taking the copy).

The second:

Employee* e3 = &m;

... does not create a seperate object. Instead, it creates a pointer to the original object.

Invoking the print method (which I assume is a virtual method) on either will have different results because the two objects are of different type. In the first case, the object is an Employee and so the Employee::print method is called. In the second case, you are calling the method on the original object, so it is the Manager::print method.

davmac
  • 20,150
  • 1
  • 40
  • 68