Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size limit for a class?

Tags:

c++

oop

class

I was wondering what the size limit for a class is. I did a simple test:

#define CLS(name,other) \
class name\
{\
public: \
name() {};\
   other a;\
   other b;\
   other c;\
   other d;\
   other e;\
   other f;\
   other g;\
   other h;\
   other i;\
   other j;\
   other k;\
};

class A{
   int k;
public:
   A(){};
};

CLS(B,A);
CLS(C,B);
CLS(D,C);
CLS(E,D);
CLS(F,E);
CLS(G,F);
CLS(H,G);
CLS(I,H);
CLS(J,I);

It fails to compile with

"'J' : class is too large"

If I remove the final declaration - CLS(J,I);, it all compiles fine.

Is this a compiler-imposed restriction, or is it somewhere in the standard?

like image 410
Luchian Grigore Avatar asked Dec 15 '11 12:12

Luchian Grigore


1 Answers

In C++11 this is Annex B. Implementations can impose limits, but they should be at least:

  • Size of an object [262 144].
  • Data members in a single class [16 384].
  • Members declared in a single class [4 096].

The third one isn't directly relevant to the kind of construction you're using, I mention it just because it indicates that the second one is indeed the total members, presumably including those in bases and I'm not sure about members-of-members. But it's not just about the members listed in a single class definition.

Your implementation appears to have given up either 2^31 data members, or at size 2^32, since it accepts I but not J. It's fairly obviously reasonable for a compiler to refuse to consider classes with size greater than SIZE_MAX, even if the program happens not to instantiate it or use sizeof on the type. So even with the best possible effort on the part of the compiler I wouldn't ever expect this to work on a 32 bit implementation.

Note that "these quantities are only guidelines and do not determine compliance", so a conforming implication can impose an arbitrary smaller limit even where it has sufficient resources to compile a program that uses larger numbers. There's no minimum limit for conformance.

There are various opportunities in the C++ standard for a conforming implementation to be useless due to ridiculously small resource limits, so there's no additional harm done if this is another one.

C++03 is more-or-less the same:

  • Size of an object [262 144].
  • Data members in a single class, structure, or union [16 384].
  • Members declared in a single class [4 096].
like image 160
Steve Jessop Avatar answered Oct 15 '22 09:10

Steve Jessop