views:

180

answers:

7

How can I find the size of an abstract class?

class A
{
    virtual void PureVirtualFunction() = 0;
};

Since this is an abstract class, I can't create objects of this class. How will I be able to find the size of the abstract class A using the 'sizeof' operator?

+8  A: 

You can use the sizeof operator:

int a_size = sizeof(A);
Marcelo Cantos
But you can't create any object, since this is an abstract class. What will be the parameter for sizeof()?
webgenius
the name of the type -> Athe same as you use sizeof(int) etc.
Axarydax
@webgenius: `sizeof` also works on _types_. Marcelo used it that way.
sbi
@webgenius: You don't need to instantiate a class to know it's size. `sizeof` does not evaluate anything. You could do `sizeof(*(A*(0)))`. @Marcelo: Store the result in `size_t`. An `int` is doubly bad because a size is never going to be less than 1 (ergo never negative), so at least use an unsigned type.
GMan
Thanks GMan, Your comment really helped.
webgenius
A: 

'sizeof(A)' works just fine, you don't actually need an instance of the class.

Shiroko
A: 

There is no need to create object to find the sizeof the class. You can simply do sizeof(A).

Naveen
+2  A: 

The direct answer is that the sizeof operator can take either an object or a type:

sizeof (A)

But really, why would you want to do this? The fact that you're asking this seems like cause for concern.

jamesdlin
A: 

In addition to other answers, which suggested using the name of the class as argument of sizeof, you can also declare a pointer to abstract class

A *p = NULL;

and then use *p as argument in sizeof

size_t size = sizeof *p;

This is perfrctly fine, since argument of sizeof is not evaluated.

AndreyT
+2  A: 

As stated, the question doesn't really make sense -- an instance has a size, but a class really doesn't. Since you can't create an instance, "the size" is mostly a meaningless concept. You can use sizeof(A), but the result doesn't mean much -- thanks to the empty base class optimization (for one obvious example), sizeof(A) does not necessarily tell you how much using A as a base class will contribute to the size of a derived class.

For example:

#include <iostream>

class A {};
class B {};
class C {};
class D {};

class Z : public A, public B, public C, public D {};

int main() { 
     std::cout << "sizeof(A) = " << sizeof(A);
     std::cout << "sizeof(Z) = " << sizeof(Z);
     return 0;
}

If I run this on my computer, sizeof(A) shows up as 1. The obvious conclusion would be that sizeof(Z) must be at least four -- but in reality with the compilers I have handy (VC++, g++), it shows up as three and one respectively.

Jerry Coffin
A: 

As far as I know, by default size of an abstract class is equivalent to the size of int. so on 32-bit machine size of above class is 4bytes.

Ashish T