Let's say I have C++ code like this:
//main.cpp
#include "p3.h"
#include "tri3.h"
int main()
{
p3 point1(0.0f, 0.0f, 0.0f);
p3 point2(1.0f, 0.0f, 0.0f);
p3 point3(2.0f, 0.0f, 0.0f);
tri3 triangle(point1, point2, point3);
}
//p3.h
#pragma once
class p3
{
public:
float _x;
float _y;
float _z;
p3(float x, float y, float z)
{
_x = x;
_y = y;
_z = z;
}
};
//tri3.h
#pragma once
#include "p3.h"
class tri3
{
public:
p3 _p1;
p3 _p2;
p3 _p3;
tri3(p3 p1, p3 p2, p3 p3)
{
_p1 = p1;
_p2 = p2;
_p3 = p3;
}
};
The compilation fails with the following error in Visual Studio 2022: error C2512: 'p3': no appropriate default constructor available
When I edit "p3.h" like this, the compilation is succesfull with no errors:
//p3.h
#pragma once
class p3
{
public:
float _x;
float _y;
float _z;
p3(float x, float y, float z)
{
_x = x;
_y = y;
_z = z;
}
p3() = default; // <-- Adding this makes the program compile just fine
};
In the Microsoft documentation about error C2512, there is an example of an object being created with no arguments and because it has no default constructor, this error occurs. However, in this example, I create my objects by passing all necessary arguments. Why do I still need a default constructor?