Public data member in non-POD class type

Use of public data members in object-type classes is discouraged.

C++ class data members can be declared with different levels of visibility. Public data members are visible anywhere, protected data members are visible to member functions of derived classes, and private data members are visible only within the class members themselves. This warning identifies a class that has public data members. Public data members are discouraged because they violate the principle of encapsulation.

Encapsulation means that objects should hide information about their implementation. This allows the object to change its implementation without affecting clients. Making a data member public prevents the class from imposing any control over how that variable is accessed. This makes it impossible for the class to ensure that invariant properties of that variable are respected. It also makes it impossible to change the implementation in certain ways. For example, it is sometimes desirable to replace a variable with a computed value.

Protected visibility is better than public visibility, but it suffers from the same basic problems. The general consensus is that data members are best declared private. Access to the variables can be provided by get/set member functions as needed. These simple functions are normally expanded inline, so there is no actual performance penalty.

This diagnostic is not emitted for every class. This diagnostic is not produced for POD or "Plain old data" classes or unions. PODS are data structures that are represented only as passive collections of field values, without using encapsulation or other object-oriented features. The formal definition of a POD class type is somewhat technical. A POD may not have user-declared constructors, destructors or assignment operators, base classes, virtual functions, or non-static data members that are private, protected, reference types, non-PODs, pointers to non-PODs, or arrays of non-PODs.

ID

Observation

Description

1

Definition

The place where the class was defined

Example


#include <stdio.h>

// This is an obvious Plain Old Data (POD) datatype so no warning here
struct pod1 {
    int f1;
    int f2;
};

// Same thing using "class" instead of "struct"; it's still a POD
class pod2 {
public:
    int f1;
    int f2;
};

// Non-POD because it has a base class
class nonpod1 : pod2 {
public:
    int public_field;
};

// Non-POD because it has constructor/destructor
class nonpod2 {
public:
    int public_field;
    explicit nonpod2(int x) : public_field(x)
    {
        printf("created nonpod2(%d)\n", public_field);
    }
    ~nonpod2()
    {
        printf("destroyed nonpod2(%d)\n", public_field);
    }
};

int main(int argc, char **argv)
{
    nonpod2 *me = new nonpod2(argc);
    delete me;
    return 0;
}
        

Copyright © 2010, Intel Corporation. All rights reserved.