veda-s4dhak
veda-s4dhak

Reputation: 15

If a C++ class has dynamic allocation within a class method but has no constructor/destructor or any non-static members, is it still a POD type?

Suppose I have the following class:

class A
{
    public:
        int index;
        int init(int type);
}

int A::init(int type)
{
    Interface* interface = SelectInterface(type);
    int index = interface->get_index(type);
    delete interface;
}

And then I have the following interface:

// ----------- INTERFACES -------------- //

class Interface
{
    virtual int get_index() = 0;
}

// This is the interface factory
Interface* SelectInterface(int type)
{
    if (type == 0)
    { 
        return new InterfaceA();
    }
    else if (type == 1)
    {
        return new InterfaceB();
    }

    return null;
}

class InterfaceA :: public Interface
{
    InterfaceA();
    int get_index();
} 

int InterfaceA::get_index()
{
    return 5;
}

class InterfaceB :: public Interface
{
    InterfaceB();
    int get_index();
} 

int InterfaceB::get_index()
{
    return 6;
}

Class A does not have any constructors or destructors, or any non-static data members. However Class A does dynamically allocate an object and then delete it within a class method.

Is Class A still a POD (plain old data) type?

Upvotes: 0

Views: 68

Answers (1)

Werner Henze
Werner Henze

Reputation: 16761

It is not relevant what the member function init is doing or not. That does not affect whether A is a POD type or not (in your example it is).

POD is an old thing and deprecated in C++20, you probably want to check for standard layout.

You can check that in your code writing

#include <type_traits>
static_assert(std::is_pod<A>::value, "");
static_assert(std::is_standard_layout<A>::value, "");

or C++17 upwards

#include <type_traits>
static_assert(std::is_pod_v<A>);
static_assert(std::is_standard_layout_v<A>);

Upvotes: 1

Related Questions