Bloomberg Interview Questions/Q 7

From Software Engineers Wiki
Jump to: navigation, search

Find out the output. Or Correct it if something is wrong.

#include <iostream>
#include<typeinfo>
using namespace std;

class base{
public:
	int a;
	base():a(0)
	{}
	int getA(){return a;}
};
class der:public base
{
public:
	int b;
	der():b(1)
	{}
	int getB(){return b;}
};
void display(base *obj, int ele)
{
	for(int i = 0; i < ele; i++)
	{
        cout << (obj+i)->getA() <<endl;
	}
}

int main()
{
    int i = 3;
    base arrb[i];
    display(arrb, 3);
    der arrd[i];
    display(arrd, 3);
    return 0;
}

Answer

The output will be

0 0 0 0 1 0

Both base and derived classes polymorphic (no virtual function). They are treated like C structures. Both classes won't have a pointer to virtual table, or RTTI. That is, for 32-bit systems,

sizeof(base) = 4
sizeof(der) = 8

For display() function, it thinks that it gets an array of class base; an array of 4 byte "a".

When the function is provided an array of B, which is an array of a structure { int a; int b; }, it treats the array as 4 byte array of { int a }.

Thus it prints arrd[0].a, arrd[0].b, arrd[1].a. That is 0 1 0

Reference

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox