C++ Programming - Functions - Discussion

Discussion Forum : Functions - Programs (Q.No. 45)
45.
What will be the output of the following program?
#include<iostream.h> 
class Base
{
    public:
    char S, A, M; 
    Base(char x, char y)
    {
        S = y - y;
        A = x + x; 
        M = x * x;
    }
    Base(char, char y = 'A', char z = 'B')
    {
        S = y;
        A = y + 1 - 1; 
        M = z - 1;
    }
    void Display(void)
    {
        cout<< S << " " << A << " " << M << endl;
    }
};
class Derived : public Base
{
    char x, y, z; 
    public:
    Derived(char xx = 65, char yy = 66, char zz = 65): Base(x)
    {
        x = xx; 
        y = yy;
        z = zz;
    }
    void Display(int n)
    {
        if(n)
            Base::Display(); 
        else
            cout<< x << " " << y << " " << z << endl; 
    }
};
int main()
{
    Derived objDev; 
    objDev.Display(0-1); 
    return 0;
}
A A A
A B A
A B C
Garbage Garbage Garbage
The program will report compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
2 comments Page 1 of 1.

Divya Nesana said:   5 years ago
How this can be Option (A)? Please explain.

Apoorva Aggarwal said:   4 years ago
objDev.Display(0-1);

In the line above, -1 is being passed to the function Display of Derived class.

if(n) ---> This statement is equivalent to if(-1), and since it is not equal to 0, therefore if statement will be executed (since, it is not false i.e. not 0).

Base::Display();
This statement will get executed.

And, S = A, A = A, M = A:
because of this block of code in Base's constructor:
S = y;
A = y + 1 - 1;
M = z - 1;

So, cout<< S << " " << A << " " << M << endl; will print:
A A A.

Post your comments here:

Your comments will be displayed after verification.