David Yachnis
David Yachnis

Reputation: 504

Interview questions?

Hey everyone I went to the interview to a well known global firm for position of C++ developer. I had a multiple choice test of 30 questions which I answered most of them correctly but some of them were tricky and badly worded . I had a lot of time so I wrote down one of the questions which in my opinion was badly worded so there is the exact copy of the question . I just want to know if it is me or the question is intentionally badly worded. I believe that every point is count because of competition for a position.

question :

What shall the flowing call return ?

sizeof(obj1);  

A. size of member functions of obj1 in bytes
B. size of the data in obj1.
C. size of member functions and the data of obj1.
D. none of the answers are correct.

I knew the answer should be size of object in bytes and I chose option C . In my opinion object contain the member functions (code segment) and data (static and dynamic allocation). The tester marked it as wrong answer .

Upvotes: 3

Views: 1013

Answers (3)

edwinc
edwinc

Reputation: 1676

The answer is D. It returns the size the object occupies in memory, which should be at least 1 by definition. This size includes data, virtual function tables, and padding bytes. Member functions don't occupy space, they are just functions that take 'this' as the first argument. A 'new' operator actually uses malloc with sizeof.

Upvotes: 1

user5106417
user5106417

Reputation:

The answer is D because non of the above is correct. Padding is not part of the data. Consider the following two examples:

#include <iostream>

struct test
{
    int x;
    int y;
    double d;
    test(){}
};

int main()
{
    test t;
    std::cout << sizeof(t) << std::endl;

    std::cin.get();
    return 0;
}

will return 16 bytes of the data types + padding while:

#include <iostream>

struct test
{
    int x;
    double d;
    int y;
    test(){}
};

int main()
{
    test t;
    std::cout << sizeof(t) << std::endl;

    std::cin.get();
    return 0;
}

return 24 bytes for the data types + padding. So an int is not larger just because the data alignment is different. so its not B nor the other answers, ergo D is the closest.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49813

The tester was correct; the member functions would not be considered part of the size of the object, as they are shared across all instances of that class.

Upvotes: 3

Related Questions