warning: offset of on non-standard-layout type 'DerivedClass'

时间:2018-12-19 11:16:14

标签: c++ c++11 memory-layout

I need to get rid of this warning. As far as I understand, it appears because DerivedClass is not considered as Plain Old Data. I read cppreference about POD and Standard Layout Type but I still do not understand why DerivedClass is not a POD. If I put members of BaseClass into DerivedClass and do not use inheritance - then everything is OK. I use C++11

Here is an example:

#include <iostream>

using namespace std;

class BaseClass
{
public:
    int a;
};

class DerivedClass : public BaseClass
{
public:
    int b;
};

int main(int argc, char *argv[])
{
    // warning: offset of on non-standard-layout type 'DerivedClass'
    int offset = offsetof(DerivedClass, b);

    cout << offset;
}

I appreciate any help.

1 个答案:

答案 0 :(得分:4)

These are the requirements for standard layout type:

All non-static data members have the same access control

Has no virtual functions or virtual base classes

Has no non-static data members of reference type

All non-static data members and base classes are themselves standard layout types

Until C++14:

Either

has no base classes with non-static data members, or

has no non-static data members in the most derived class and at most one base class with non-static data members

Has no base classes of the same type as the first non-static data member (see empty base optimization)

This part applies to this example:

has no base classes with non-static data members,

In your case you have a base class with non static data members. Removing a removes the warning.

After C++14, there are similar constraints, you cannot have members in the two classes, only one:

Has all non-static data members and bit-fields declared in the same class (either all in the derived or all in some base)