I'm trying to define a 2D Point struct and then derive a Point3D struct from it. Initializing Point works with braces, but initializing Point3D with three values produces an error: "no instance of constructor Point3D::Point3D matches the argument list." The error points to the opening brace in `Point3D p3D = { 1, 2, 3 };`. Is struct inheritance allowed here, or do I need to initialize the base part differently?
```cpp
struct Point {
int x;
int y;
};
struct Point3D : public Point {
int z;
};
class Test {
Point p = { 1, 2 };
Point3D p3D = { 1, 2, 3 };
};
```
3 Answers
Inheritance between structs is allowed. The problem is aggregate initialization: the base `Point` is a separate subobject, so the initializer needs to group the base members explicitly. Depending on your C++ standard and compiler, this can work:
```cpp
Point3D p3D = { { 1, 2 }, 3 };
```
A constructor is often clearer and avoids relying on aggregate-initialization rules.
The direct `{1, 2, 3}` form does not automatically flatten the base class members into `x`, `y`, and `z`. In older language standards, a derived class with a base class was not treated as the kind of aggregate you might expect. If you do not need inheritance, two separate structs or composition could also make the data layout and initialization simpler.
You can define a constructor that initializes both the base class and `z`:
```cpp
struct Point3D : Point {
int z;
Point3D(int xValue, int yValue, int zValue)
: Point{ xValue, yValue }, z{ zValue } {}
};
Point3D p3D{ 1, 2, 3 };
```
This makes the intended argument order explicit and works consistently without needing nested braces.

Thanks! Adding a constructor for `Point3D` fixed the issue for me.