Why do we need a default constructor to pass an object by reference in C++?

3k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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 type Foo. If it isn't default-constructible, then it needs to be initialised in its declaration, or in the constructor's initialiser list:

MyClass::MyClass(const Foo& foo) : foo(foo) { ... }
                                   ^^^^^^^^
                                   initialiser list

This assumes that the member is called foo, and that it's supposed to be initalised by copying the function parameter.

2
On

It would be helpful to know what compiler you are using, which standard of c++ it complies to and if you have other constructors for MyClass.

What I can imagine is that the compiler does not generate a default constructor MyClass() because you have defined another constructor. Should the compiler ever want to generate a default object of class MyClass like in

class MyClass mc;

The only way to accomplish this in the absence of MyClass::MyClass() is to think the code line above as

class MyClass mc( Foo() );

This requires class Foo to have a default constructor.

I would have made this a comment, but I'm not yet allowed to.