3

Consider this:

class Vec3
{
    private:
        float n[3];
    public:
        float& x;
        float& y;
        float& z;
        Vec3(float x_, float y_, float z_) : x(n[0]), y(n[1]), z(n[2])
        {
            x = x_;
            y = y_;
            z = z_;
        }
}

can I be sure that doing this:

Vec3 v(1,2,3);
cout<<reinterpret_cast<float*>(&v)[0]<<"\t";
cout<<reinterpret_cast<float*>(&v)[1]<<"\t";
cout<<reinterpret_cast<float*>(&v)[2]<<"\t";

will give me 1 2 3 by every compiler/OS that follows the standard?

Luke B.
  • 1,258
  • 1
  • 17
  • 28

3 Answers3

5

No. For that to work, you'd need (at least) a standard-layout type. float& isn't, and therefore Vec3 isn't either. (9/7, first bullet).

MSalters
  • 173,980
  • 10
  • 155
  • 350
3

As said in other answers, this won't work, because of the float&. See Standard Layout Classes and Trivially Copyable Types for a long explanation about standard layout.

You could consider a slightly different approach:

class Vec3
{
    private:
        float n[3];
    public:
        float& x() { return n[0]; }
        float& y() { return n[1]; }
        float& z() { return n[2]; }
        Vec3(float x_, float y_, float z_)
        {
            x() = x_;
            y() = y_;
            z() = z_;
        }
};

Thus,

Vec3 v(1,2,3);
cout<<reinterpret_cast<float*>(&v)[0]<<"\t";
cout<<reinterpret_cast<float*>(&v)[1]<<"\t";
cout<<reinterpret_cast<float*>(&v)[2]<<"\t";

Will print 1 2 3 for all compilers

Edit

You might also want to see What are Aggregates and PODs (1st answer) and What are Aggregates and PODs (2nd answer) for more precise information.

Community
  • 1
  • 1
Synxis
  • 9,236
  • 2
  • 42
  • 64
  • can I define a ctor on a POD type? – Luke B. May 07 '12 at 17:53
  • @Luke C++03: No, by definition POD types can't have user defined constructor. C++11: You can define a constructor for a POD type if you specify a non-user default constructor (ie, `MyClass() = default;`) See my edited post – Synxis May 07 '12 at 21:31
1

Nope. Your class is not POD, so there are no guarantees whatsoever, AFAIK.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    It is the standard-layout property that is most important here (which is in cluded in the PODness) – PlasmaHH May 07 '12 at 14:26
  • 1
    @PlasmaHH: But this isn't standard-layout either (standard layout requires that all non-static members have the same access specifier, but this has both public and private members). – Jerry Coffin May 07 '12 at 14:50
  • @JerryCofin: as I said, "which is included in PODness". – PlasmaHH May 07 '12 at 14:52