My C++ compiler give me an error "no default constructor exists for class Foo" when I try the following.
MyClass::MyClass(const Foo& foo) { ... }
If I'm passing a reference, the object should already be initialized, correct? And it's not a problem with copy constructors, because I defined one explicitly. So why would one need a default constructor to pass a reference?
The only thing I've been able to think of is that it might not know how much memory to allocate for it. If that's the problem, is there a way to tell the compiler that I only ever intend to allocate this object dynamically? I haven't been able to find any answers online for this, and I would really appreciate some help.
EDIT: I'm just going to edit in my actual code.
MemberManager.cpp:
#include "MemberManager.h"
MemberManager::MemberManager(const NodeManager& nodeSet, std::vector<int> cctMat, int n)
{
for(int i = 0; i < n; i++)
{
memSet[i] = Member();
}
}
NodeManager.h
#include "Node.h"
class NodeManager
{
public:
//constructors
NodeManager(std::vector<double> crdMat, std::vector<Constraint> cstMat, int n):
nodeSet(n) {};
//copy
NodeManager(const NodeManager& src):
nodeSet(src.nodeSet) {};
}
My precise error message is a red underline under the first body bracket of MemberManager::MemberManager(...) and it says no default constructor exists for NodeManager. This is my intent, but I don't understand WHY it would need a default constructor.
You don't need a default constructor to pass an object by reference. Your code must be doing something else that requires such a thing.
My guess is that
MyClass
has a member of typeFoo
. If it isn't default-constructible, then it needs to be initialised in its declaration, or in the constructor's initialiser list:This assumes that the member is called
foo
, and that it's supposed to be initalised by copying the function parameter.