Search code examples
c++visual-studioconstructorcompiler-errorsheader-files

Problem with constructors and including headers


I guess this can be a conceptual problem, but I couldn't find anything to solve it. I'm new to C++, and I'm having troubles with the includes (i'm working in Visual Studio 2017 on Windows 10). I've created these classes:

  • Shader
  • Material
  • Mesh

Each one of them with their .h and .cpp files respectively. The .h of each one of them looks like this:

Shader.h

#pragma once
class Shader
{
public:
    //Default constructor
private:
    //Some stuff
}

Material.h

#pragma once
#include "Shader.h"

class Material
{
public:
    Material(Shader s);
private:
    //Some stuff
}

Mesh.h

#pragma once
#include "Material.h"

class Mesh
{
public:
    Mesh(Material m);
private:
    //Some stuff
}

The problem appears in Mesh.cpp, when I write this:

Mesh.cpp

#include "stdafx.h"
#include "Mesh.h"

Mesh::Mesh(Material mat)
{

}

If I write that, Visual Studio gives me this error (marking in red the first bracket of the constructor):

No default constructor exists for class "Material"

Why is it assuming that I'm defining Material class constructor only by including Material.h in the header of Mesh class? Another problem appears if I just remove the constructor and try to create an object of type Mesh in, for example, Main.cpp. If I do this (letting Mesh with default constructor):

Mesh m = Mesh();

The compiler says:

The default constructor of Mesh::Mesh cannot be referenced - - it is a deleted function

I don't know what to do or what to search for. Hope I gave you the necessary information to help me, thanks in advance!


Solution

  • It sounds like you’ve left something out of your sample code. The class Mesh has a data member of type Material, doesn’t it? Material doesn’t have a default constructor, so every constructor for Mesh has to explicitly initialize the Material member.

    Mesh::Mesh(Material mat)
    { // no initializer for Material data member
    )
    

    Add an initializer list. Assuming the data member is named m, the constructor should look like this:

    Mesh::Mesh(Material mat)
    : m(mat) // initializes m
    {
    }