CuriousKrish
CuriousKrish

Reputation: 21

Size of an object without using sizeof in C++

This was an interview question:

Say there is a class having only an int member. You do not know how many bytes the int will occupy. And you cannot view the class implementation (say it's an API). But you can create an object of it. How would you find the size needed for int without using sizeof.

He wouldn't accept using bitset, either.

Can you please suggest the most efficient way to find this out?

Upvotes: 0

Views: 1426

Answers (4)

A.S.H
A.S.H

Reputation: 29332

Yet another alternative without using pointers. You can use it if in the next interview they also forbid pointers. Your comment "The interviewer was leading me to think on lines of overflow and underflow" might also be pointing at this method or similar.

#include <iostream>
int main() {
    unsigned int x = 0, numOfBits = 0;
    for(x--; x; x /= 2) numOfBits++;
    std::cout << "number of bits in an int is: " << numOfBits;
    return 0;
}

It gets the maximum value of an unsigned int (decrementing zero in unsigned mode) then subsequently divides by 2 until it reaches zero. To get the number of bytes, divide by CHAR_BIT.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596111

Pointer arithmetic can be used without actually creating any objects:

class c {
    int member;
};

c *ptr = 0;
++ptr;
int size = reinterpret_cast<int>(ptr);

Alternatively:

int size = reinterpret_cast<int>( static_cast<c*>(0) + 1 );

Upvotes: -1

Rama
Rama

Reputation: 3305

Using pointer algebra:

#include <iostream>

class A
{
    int a;
};

int main() {
    A a1;
    A * n1 = &a1;
    A * n2 = n1+1;
    std::cout << int((char *)n2 - (char *)n1) << std::endl;
    return 0;
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

The following program demonstrates a valid technique to compute the size of an object.

#include <iostream>

struct Foo
{
   int f;
};

int main()
{
   // Create an object of the class.
   Foo foo;

   // Create a pointer to it.
   Foo* p1 = &foo;

   // Create another pointer, offset by 1 object from p1
   // It is legal to compute (p1+1) but it is not legal
   // to dereference (p1+1)
   Foo* p2 = p1+1;

   // Cast both pointers to char*.
   char* cp1 = reinterpret_cast<char*>(p1);
   char* cp2 = reinterpret_cast<char*>(p2);

   // Compute the size of the object.
   size_t size = (cp2-cp1);

   std::cout << "Size of Foo: " << size << std::endl;
}

Upvotes: 4

Related Questions