0

Due to some legacy C code, I have the following POD struct defining 2D coordinates; and a C++ class inheriting from it in order to provide various operations:

struct coord
{
  double x;
  double y;
};

class CoordClass : public coord
{
  // Contains functions like...
  const CoordClass& operator+=(const CoordClass& rhs)
  {
    x += rhs.x;
    y += rhs.y;
    return *this;
  }

  double Magnitude() const { return std::sqrt(x*x + y*y); }
};

At present, CoordClass defines a constructor:

CoordClass(double xx, double yy) { x = xx; y = yy; }

Given x and y are members of the POD base struct coord, is it possible to write that constructor as an initialiser list and empty body instead? Answers considering both C++03 and C++11 interest me.

Chowlett
  • 45,935
  • 20
  • 116
  • 150

3 Answers3

3

In C++11 you can provide this constructor:

 CoordClass(double x, double y) : coord{x, y} {}

In C++03 is also possible to get an empty constructor body but I don't think it's worth doing:

CoordClass(double x, double y) : coord(make_coord(x, y)) {}

where make_coord is:

coord make_coord(double x, double y) {
    coord c = { x, y };
    return c;
}

It can be a private static method of CoordClass. Alternatively, it can be a free function which is static and/or a member of an anonymous namespace of CoordClass.cpp.

Cassio Neri
  • 19,583
  • 7
  • 46
  • 68
1

In C++11, if you define a defaulted default constructor to a struct, it can still be a POD in C++11. (See Is this struct POD in C++11? )

struct coord
{
  double x;
  double y;

  coord() = default;
  coord(double xx, double yy) : x(xx), y(yy) {}
};

Now the CoordClass constructor becomes easy:

CoordClass(double x, double y) : coord(x, y) {}
Community
  • 1
  • 1
Sjoerd
  • 6,837
  • 31
  • 44
  • Ah! And, while I can't use `= default;` (MSVC), I think a similar struct with user-defined default constructor is still _standard-layout_? And thus, so long as the constructors are `#ifdef __cplusplus` guarded, it should interoperate fine? – Chowlett Mar 07 '14 at 17:12
0

Try the following

CoordClass(double xx, double yy) : coord { xx, yy } {}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335