Open In App

POD Type in C++

Last Updated : 05 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In C++, POD is short for Plain Old Data. It is a class or a struct that is defined using a class or struct keyword that has a very simple structure without any constructor, destructor or virtual functions, it only has int, char, double, bool, etc. as its data members. In this article, we will learn about POD Type in C++.

Plain Old Data Types in C++

In C++, POD types are built-in data types (class, structures) but unlike other classes and structs they lack custom constructors, destructors, or virtual functions, and their members are public. The C++ POD class layout will be same as that of same struct in C language.

PODs can contains only PODs as data members that offer benefits such as well-defined memory layout and compatibility, making them suitable for low-level operations and external data interchange.

Following are the generally used PODs in C++:

  • Fundamental Types: int, char, float, double, etc.
  • Pointers: int*, char*, void*, etc.
  • Enums: Enumerated types.
  • Structs, Unions: With some restrictions (e.g., no virtual functions, no reference members).

How to Define POD Type in C++?

In C++ we have two main approaches for defining POD types i.e. structs and classes that can be defined using the below syntax:

struct structName
{
//POD members
};
//or
class className
{
public:
//POD members
};

C++ Program to Demonstrate POD Types

The below example demonstrates how we can define and use POD type in C++.

C++
// C++ program to demonstrate the use of POD Type

#include <iostream>
using namespace std;

// Define a POD type
struct POD {
    int x;
    double y;
};

int main()
{
    // Define a variable p of POD type
    POD p = { 10, 20.5 };

    // Print the members of p
    cout << "x = " << p.x << ", y = " << p.y << endl;

    return 0;
}

Output
x = 10, y = 20.5

Explanation: In the above example we have a structure named POD that has only integer member x and double member y , no custom constructor, destructor, virtual function is used therefore it is a POD type.

Characteristics of POD Types

  • PODs can be initialized using static initialization and do not necessitate user-defined constructors or destructors.
  • It follows standard memory layout which is straightforward, with members stored sequentially in which they are declared as in C structure. It enables compatibility with C-style memory management.
  • POD types do not have user-defined special member functions.
  • POD types do not have virtual functions or non-POD members. This means that there are no hidden pointers to vtables or offsets that get applied to the address when it is cast to other types.
  • POD types do not have any base classes.
  • All non-static data members of a POD type are public.

Next Article
Practice Tags :

Similar Reads