C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 24)
24.
What will be the output of the program given below?
#include<iostream.h> 
class BixBase
{
    int x;
    public:
    BixBase(int xx = 0)
    {
        x = xx; 
    }
    void Display()
    {
        cout<< x ;
    }
};
class BixDerived : public BixBase
{
    int y; 
    public:
    BixDerived(int yy = 0)
    {
        y = yy;
    }
    void Display()
    {
        cout<< y ;
    }
};
int main()
{
    BixBase objBase(10); 
    BixBase &objRef = objBase;

    BixDerived objDev(20); 
    objRef = objDev;

    objDev.Display(); 
    return 0; 
}
0
10
20
Garbage-value
It will result in a compile-time/run-time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
5 comments Page 1 of 1.

Mohit gupta said:   1 decade ago
As we are calling the display function with the object of derived class (objDev) so it calls derived class function.

Therefore answer is 20.

Shiksha said:   1 decade ago
But how are we able to assign a variable to reference. It should have been an error.

Aparna said:   1 decade ago
It should give error.

We can't assign reference of one object to other.

Demented_hedgehog said:   10 years ago
In the same way that you can do this:

int x = 10;
int &y = x;
y = 42;

You can also set:

objBase = objDev; which implies that,

objRef = objDev is also ok.

The reason this is so is that the compiler provides an implicitly declared (by the compiler) copy assignment operator.

Vasista said:   6 years ago
I executed the code and it gives output as 20.

Reference of base class object can point to derived class object and hence derived class function is called and hence 20 is obtained.

Post your comments here:

Your comments will be displayed after verification.