What is the output of the following main()? Suppose the code segments will be as
ID: 3717694 • Letter: W
Question
What is the output of the following main()? Suppose the code segments will be assembled and embedded correctly in a C++ program.
CODE:
class small
{
public:
void print() const { std::cout << "small: x " << x << ", y " << y << " "; }
int add() { return x + y; }
small(int a = 0, int b = 0) : x(a), y(b) {}
private:
int x;
int y;
};
class notSmall : public small
{
public:
void print() const { small::print(); std::cout << "notSmall: z " << z << " "; }
int add() { return small::add() + z; }
notSmall(int a = 0, int b = 0, int c = 0) : small(a, b), z(c) {}
private:
int z;
};
int main()
{
small * ptrSmall;
small objSmall(2, 3);
notSmall objBig(3, 5, 7);
ptrSmall = &objSmall;
std::cout << ptrSmall->add() << " ";
ptrSmall->print();
ptrSmall = &objBig;
std::cout << ptrSmall->add() << " ";
ptrSmall->print();
return 0;
} // end main
What would be the output of the main()in a, if the print() and add() of class small are virtual functions?
Explanation / Answer
Part I:
output:
5
small: x 2, y 3
8
small: x 3, y 5
Part II: if the print() and add() of class small are virtual functions
Output:
5
small: x 2, y 3
15
small: x 3, y 5
notSmall: z 7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.