This creates an object of type
Base
. You cannot change the type of this object -- it will always be of type base.
Therefore:
1 2
|
Base foo;
cout << foo.GetName();
|
This will print "Base" because foo is a Base.
Note that foo is
ALWAYS a base. Even if you assign something else to it, you can never change the fact that it is a base:
1 2 3 4 5 6 7 8
|
Derived d;
Base foo;
cout << foo.GetName(); // <- outputs "Base" because foo is a Base
foo = d;
cout << foo.GetName(); // <- still outputs "Base" because foo is *ALWAYS* a Base!
|
This is what is happening when you leave off the '&' symbol. Without the &, 'rBase' will always be a Base object.
With the & symbol, rBase
is not an object, but rather it is a reference, which refers to an existing object. In your case, that object is 'cDerived', which is not a Base, but rather is a Derived:
1 2 3 4
|
Derived d;
Base& foo = d; // <- foo is not a Base object, but is a reference, referring to the 'd' object
cout << foo.GetName();
|
This time it will output "Derived", because foo
refers to 'd'... and d is of type Derived, and not of type Base.