Is it possible to create an object of an empty class type such as: If so, what is the size...
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Is it possible to create an object of an empty class type such as:
class xyz
{
};
If so, what is the size of such an object?
Pick ONE option
Show answer & explanation
In C++, you can create objects of empty classes without compiler or runtime errors. However, the C++ standard guarantees that every object has a non-zero size to ensure distinct memory addresses for different object instances. The minimum size is typically 1 byte (implementation-dependent), enforced by the "empty base optimization" rules and object identity requirements.
Step-by-step Derivation:
Step 1: Verify syntactic validity — the empty class definition is valid C++ syntax.
Step 2: Instantiation — objects can be created: xyz obj; compiles without errors.
Step 3: Size determination — use sizeof(xyz) in C++. Even though the class has no members, the standard mandates that sizeof(object) > 0 to guarantee each object occupies distinct memory addresses. This is not ambiguous like option A suggests.
Step 4: Typical result — sizeof(xyz) evaluates to 1 byte on most implementations, confirming option B.
Option C and D are incorrect because empty classes are legal and cause neither compiler nor runtime errors. Option A is incorrect because the size is never zero due to the C++ object identity requirement.