Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain Old Data types with private members?

Tags:

c++

c++11

Is Demo a POD type in C++03?

struct Demo
{
     private:
       int x;
       int y;
};

C++03, §9p4:

A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor.

After reading Steve Jessop's post, I believe Demo is a non-POD because the members are private. However the Standard doesn't say anything about the relation between POD types and access modifiers.

In C++0x Demo is POD because §9p9 (n3126) says:

A POD struct is a class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).

Demo is trivial1 as well as a standard-layout class so it is a POD. Is my interpretation correct?

1 A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable. [9p5, n3126]

like image 353
Prasoon Saurav Avatar asked Oct 17 '10 04:10

Prasoon Saurav


2 Answers

In C++03, it's definitely not a POD. According to §9/4, "A POD-struct is an aggregate class ...", and according to §8.5.1/1:

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3)."

Under C++0x, at least as of N3090/3092, I believe it is a POD. These require only that all non-static members have the same access, not that the access is necessarily public. This is to fix a problem that I believe I was the first to point out -- in C++98/03, a vacuous access specifier leads to a problem:

struct x { 
    int a;
public:
    int b;
public:
   int c;
};

This fits the requirements of a POD struct -- but the standard still gives permission for the relative positions of b and c to be swapped because of the intervening access specifier. As a result, being a POD struct doesn't provide the layout guarantees that were intended to ensure compatibility with C structs (for the obvious example).

like image 67
Jerry Coffin Avatar answered Sep 21 '22 14:09

Jerry Coffin


From C++11 on, the easiest by far is to ask the compiler with std::is_pod:

#include <iostream>
#include <type_traits>

struct Demo
{
     private:
       int x;
       int y;
};

int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_pod<Demo>::value << std::endl;
}

true

like image 29
FrankS101 Avatar answered Sep 19 '22 14:09

FrankS101