Click here to Skip to main content
15,844,602 members
Articles / Programming Languages / C++
Tip/Trick

C++ Empty Class and Function

Rate me:
Please Sign up or sign in to vote.
3.05/5 (7 votes)
3 May 2020CPOL2 min read 9.4K   46   2   9
Demonstration of how empty class and function is used in C++
In this tip, I use a simple endian swap example to demonstrate the use of empty class and function in templates.

Introduction

More than 10 years ago, when I first debugged my Boost code, I stepped into empty class and empty function. At that time, I was wondering what empty class and function devoid of any code is good for. In this tip, I am going to use a simple endian swap example to demonstrate the use of empty class and function in templates.

First, we define two classes, Same and Different to indicate same or different endianness. Why can't we use true or false? You ask. true and false are of the same boolean type. As a template type, they are the same, as far as the C++ compiler is concerned.

C++
class Same
{};

class Different
{};

What is the size of an empty class?

C++
std::cout << "sizeof(Same) is " << sizeof(Same) << std::endl;
std::cout << "sizeof(Different) is " << sizeof(Different) << std::endl;

Visual C++, G++ and Clang all give the size of one. Why size of one? Because C++ memory allocator has trouble instantiating zero-sized object.

sizeof(Same) is 1
sizeof(Different) is 1

Next, we have our dummy PacketWriter which takes in one template type, SameEndianType and has one Write function that takes a short integer and swap it if the SameEndianType is Different. We have 2 Swap functions where there is nothing to be done for same endianness. C++ compiler will optimize away the call to empty Swap() in release build. There is no need to give a name to the second parameter of Swap() because it is not going to be used inside Swap() anyway.

C++
// Dummy PacketWriter
template<typename SameEndianType>
class PacketWriter
{
    typedef SameEndianType endian_type;
public:
    void Write(short n)
    {
        std::cout << "Before swapping, n=" << n << std::endl;
        Swap(n, endian_type());
        std::cout << "After swapping, n=" << n << std::endl;
    }
private:
    void Swap(short& n, Same)
    {
    }
    void Swap(short& n, Different)
    {
        short upper = (n & 0xff) << 8;
        short lower = (n & 0xff00) >> 8;
        n = upper | lower;
    }
};

The code below tests two PacketWriter objects of Same and Different endian.

C++
std::cout << "Create PacketWriter<Same> to write a short int" << std::endl;
PacketWriter<Same> w;
w.Write(256);

std::cout << "Create PacketWriter<Different> to write a short int" << std::endl;
PacketWriter<Different> w2;
w2.Write(256);

The output of the test program is as expected: PacketWriter<Same> do not swap the short integer whereas PacketWriter<Different> do actually swap it. The upside of this templated endianness is endianness check before swap is eliminated at runtime but the downside is that you cannot change the behaviour dynamically during runtime.

Create PacketWriter<Same> to write a short int
Before swapping, n=256
After swapping, n=256

Create PacketWriter<Different> to write a short int
Before swapping, n=256
After swapping, n=1

That's all for today! Hope you like this tip!

The demo code is hosted on Github.

History

  • 4th May, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Singapore Singapore
Shao Voon is from Singapore. His interest lies primarily in computer graphics, software optimization, concurrency, security, and Agile methodologies.

In recent years, he shifted focus to software safety research. His hobby is writing a free C++ DirectX photo slideshow application which can be viewed here.

Comments and Discussions

 
Generalvery good Pin
Southmountain16-May-20 9:44
Southmountain16-May-20 9:44 
QuestionTemplate with bool Pin
geoyar5-May-20 10:40
professionalgeoyar5-May-20 10:40 
QuestionNot an article Pin
Michael Haephrati4-May-20 10:52
professionalMichael Haephrati4-May-20 10:52 
AnswerRe: Not an article Pin
Shao Voon Wong4-May-20 16:58
mvaShao Voon Wong4-May-20 16:58 
SuggestionThe size of the object must be one bytes because the C++ memory allocator has trouble... Pin
codevisio4-May-20 2:54
codevisio4-May-20 2:54 
GeneralRe: The size of the object must be one bytes because the C++ memory allocator has trouble... Pin
feanorgem4-May-20 6:34
feanorgem4-May-20 6:34 
GeneralRe: The size of the object must be one bytes because the C++ memory allocator has trouble... Pin
steveb4-May-20 7:01
mvesteveb4-May-20 7:01 
GeneralRe: The size of the object must be one bytes because the C++ memory allocator has trouble... Pin
codevisio4-May-20 7:17
codevisio4-May-20 7:17 
Quote:
Because its in the memory it can't be 0 bytes for the sake of pointer memory arithmetic.


The premise is wrong. It's not because the arithmetic would be problematic but because the addresses of two memory objects must be different. I think He(1) is more authoritative than me on this respect.

Quote:
. Also there technically are no empty classes ever because the C++ compiler will always generate five default methods: Constructor; Copy Constructor; Destructor; Address of operator; Assignment operator. You can double check in the disassembly all the code that was automatically generated
Quote Selected Text


I don't need to check, I know already.
That is technically wrong. Quite the contrary I'd say. Indeed I can declare a C++ class with tons of methods but without any data member, integral ones or not and still have a class with one byte(sizeof). It doesn't matter how many methods a class has, what counts for its size (sizeof) is the data members.
Classes with at least one virtual methods are different cause the pointer to the internal virtual table and classes deriving from classes with at least virtual methods (but not classes resembling POD).


(1)Why is the size of an empty class not zero?
GeneralRe: The size of the object must be one bytes because the C++ memory allocator has trouble... Pin
Southmountain16-May-20 9:40
Southmountain16-May-20 9:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.