C++ Programming - Functions - Discussion

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

Harsh Mehta said:   8 years ago
Derived objDev;

objDev.Display(-1);
//here Display function of a derived class is called because it is taking an int parameter.
so the value - 1 goes to n.
& in if condition it is true because - 1 is a non zero value.

So now
Base::Display();
This line will execute.
The function 'Base' with three parameters in Base class got called.
Here int Y='A' i.e 65
int Z='B' i.e 66

If it is written like this
char Y='A'
then it will be A.

So,
S=y // S=65,
A=y+1-1 //A=65+1-1,
M=z-1// M=66-1,

Now, display function of Base class got called and it will print all these values.

Harsh said:   8 years ago
I think the answer to this should be compile time error as character value is being put into int variable at BASE constructor.

Mayank said:   8 years ago
Base class display is called as -1 is given as input.

Amit said:   8 years ago
I am not getting this, Please explain this.

Saurav said:   10 years ago
Any body explain?

Post your comments here:

Your comments will be displayed after verification.