0

(I realized that it was a copy-paste-mistake in my program. But the reason, why I get exactly that error message could still be interesting for somebody else, therefore, I updated the question.)

I have the following code snippet which copies the elements of one vector into another vector. Maybe this could be solved more elegantly, but that shall not be the question here (except if it's absolutely stupid what I'm trying to do, of course.)

void DomainClass::addMembers(vector<DomainMember*>& d){
    for(int i = 0; i < d.size(); i ++){
        this->domains.push_back(d[i]);
    }
}

The vector this->domains is a member with definition:

vector<Domain*> domains;

The compiler tells me: error:

reference to type 'const value_type' (aka 'Domain *const') could not bind to an lvalue of type 'value_type' (aka 'DomainMember *')

I basically understand the problem when I'd like to handle objects BY REFERENCE, BUT in that case, I'd like to insert the elements of d BY VALUE into domains. How can I tell the compiler that he should just make a copy instead of passing references?

Michael
  • 7,407
  • 8
  • 41
  • 84
  • 1
    Where is your MCVE? Vectors _do_ make copies so you're misunderstanding something. – Lightness Races in Orbit Mar 04 '15 at 12:01
  • 3
    Is it possible that your member variable `domains` contains elements of type `DomainMember*` but the argument vector contains elements of type `Domain*`? Btw. `std::vector::push_back()` pushes elements by value, so that's not the problem. – bweber Mar 04 '15 at 12:05
  • Please edit question by adding declaration of member vector "domains". – CreativeMind Mar 04 '15 at 12:55

1 Answers1

1

What the error tells you is that you try to put an object of type DomainMember* (in d) in an object of class Domain* (in domains). The compiler does not know how to cast from DomainMember to Domain.

The problem is not with the copy, it is with the fact that the type of domains should be be vector<DomainMember*> (or d should be a vector<Domain*>, your call) for your push_back to work.

Math
  • 2,399
  • 2
  • 20
  • 22