Govt. Exams
Entrance Exams
Advertisement
Topics in C++ Programming
What is the output of operator overloading in the following context?
class Complex {
public:
int real, imag;
Complex operator+(const Complex &c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
};
Complex c1, c2, c3;
c1 = {1, 2}; c2 = {3, 4};
c3 = c1 + c2;
class Complex {
public:
int real, imag;
Complex operator+(const Complex &c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
};
Complex c1, c2, c3;
c1 = {1, 2}; c2 = {3, 4};
c3 = c1 + c2;
Correct Answer:
A. c3 has real=4, imag=6
EXPLANATION
The + operator is overloaded to add two Complex numbers. c1 + c2 calls the overloaded operator+, resulting in real=1+3=4 and imag=2+4=6.
Consider the following code:
class Base {
protected:
int x = 10;
};
class Derived : private Base {
public:
void display() { cout
class Base {
protected:
int x = 10;
};
class Derived : private Base {
public:
void display() { cout
Correct Answer:
A. Prints 10
EXPLANATION
Even with private inheritance, protected members of Base are accessible within Derived class methods. The display() function can access x and will print 10.
What is the output of the following code?
class A {
public:
A() { cout
class A {
public:
A() { cout
Correct Answer:
A. A B ~B ~A
EXPLANATION
Constructors are called from base to derived (A then B), while destructors are called from derived to base (~B then ~A).