Polymorphism

If you take a look at line 22, there is a bit of code, "Base &rBase = cDerived;". When I leave out the "&" sign, the program behaves differently and I'm not sure why. A more detailed explanation of my question is under the "Base &rBase = cDerived;" code as comments. Please help!!! T_T

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
#include <iostream>
#include <string>
using namespace std; 

class Base
{
protected:
 
public:
    virtual const char* GetName() { return "Base"; }
};
 
class Derived: public Base
{
public:
    virtual const char* GetName() { return "Derived"; }
};
 
int main()
{
    Derived cDerived;
    Base &rBase = cDerived;
    // With respect to "Base &rBase = cDerived", the output currently will be "rBase is a Derived". 
    // However, when I change the syntax to Base rBase = cDerived (taking out the "&"), the output changes to "rBase is a Base". 
    // I'm not exactly sure why and how the reference is changing the output.
    cout << "rBase is a " << rBase.GetName() << endl;
 
    return 0;
}
Last edited on
 
Base rBase;


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.
@Disch

Awesome. Thank you so much for your response. It makes much more sense :)
Topic archived. No new replies allowed.