Initializing vector reference member

K

Kram

I was having some trouble that I have now "solved" but not in a good
way, I'm really confused as to why and how this works.

Here is a mock-up of the problem:

myclass.h
class MyClass
{
private:
int mydata_;
public:
MyClass(int mydata):mydata_(mydata){};

};

anotherclass.h
class AnotherClass
{
private:
vector<MyClass>& mydata_;
public:
AnotherClass(vector<MyClass>& mydata);

};

anotherclass.cpp
AnotherClass::AnotherClass(vector<MyClass>& mydata):mydata_(mydata){};

When I compile I get the following error: no matching function for
call to ‘MyClass::MyClass()’
I see no reason for a reference to a vector to need to call the
default
(compiler generated) constructor
of the containing object. I can not have a default constructor of
"MyClass" because it actually needs all the data it is being given. I
don't want to have a copy of the vector either, all I want is to have
a local reference to this list of "MyClass" objects. Why is it calling
the default constructor of the contained object for a reference?

My "solution", which for unexplained reasons works is to make the
reference a const reference:

myclass.h
class MyClass
{
private:
int mydata_;
public:
MyClass(int mydata):mydata_(mydata){};

};

anotherclass.h
class AnotherClass
{
private:
const vector<MyClass>& mydata_;
public:
AnotherClass(const vector<MyClass>& mydata);

};

anotherclass.cpp
AnotherClass::AnotherClass(const vector<MyClass>& mydata):mydata_
(mydata){};

Why does making the reference const avoid my problem, and is their a
more elegant(non const!) way of doing this?

Thanks!
 
K

Kram

Kram said:
I was having some trouble that I have now "solved" but not in a good
way, I'm really confused as to why and how this works.
Here is a mock-up of the problem:

Could you please post the *exact* code that produces the error (not a
mock-up), and what compiler you're using?

V

Looks like I figured out my problem before I could get back here to
post it. The long and the short of it was that I was using QVectors
from QT not std::vector. I think it has something to do with the way
they handle references as copy on write. I switched to a std::vector
and now everything works great.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top