tags:

views:

80

answers:

5

I have a class called Movie with the following private data members:

private:
    string       title_ ;  
    string       director_ ;  
    Movie_Rating rating_ ;  
    unsigned int year_ ;  
    string       url_ ;  
    vector<string> actor_;

It also contains the following copy constructor:

Movie::Movie(Movie& myMovie)  
{  
    title_ = myMovie.title_;  
    director_ = myMovie.director_;  
    rating_ = myMovie.rating_;  
    year_ = myMovie.year_;  
    url_ = myMovie.url_;  
    actor_ = myMovie.actor_;  
}

When I try to create a vector of this class,

vector<Movie> myMovies;

and then accept all the info from a user into a temp Movie object (myMovie1), and then use push back:

myMovies.push_back(myMovie1);

I get the following error:

1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\vector(1233) : error C2558: class 'Movie' : no copy constructor available or copy constructor is declared 'explicit'

Where am I going wrong? It seems it wants a copy constructor but I do have one defined.

A: 

The elements that go in a vector must meet the "copy constructible" requirement; that is, they must have a copy constructor available. Now, is your copy constructor private or protected?

Etienne de Martel
The Standard allows copy constructors to either take const or non-const references, although the former is far more common in practice. A function that takes a non-const reference can't take temporaries or const objects as arguments.
David Thornley
Yes, I realized that after posting, so I edited.
Etienne de Martel
+4  A: 

My guess is that it's protesting against binding a temporary to a non-const reference. Try Movie::Movie(const Movie & myMovie) as the signature to your copy constructor.

David Thornley
Thanks. this worked.
xbonez
A: 

Change copy constructor to

Movie::Movie(Movie const& myMovie)

or remove it completely - it seems that default(shallow copy) is ok in this case.

a1ex07
It would not be shallow here (no pointer/reference)
Matthieu M.
Yeah, I missed the point that there is a couple of members that are objects. Surely, a default constructor performs a deep copy and respects object semantics.
a1ex07
It makes a member-wise copy, where the members automatically take care of deep copying. The user-defined constructor is not necessary here.
UncleBens
A: 

You copy constructor needs to be like this:

Movie::Movie(const Movie& myMovie)

The const is needed for the compiler to find it.

Space_C0wb0y
+1  A: 

Code should read:

Movie::Movie(const Movie& myMovie)
{
title_ = myMovie.title_;
director_ = myMovie.director_;
rating_ = myMovie.rating_;
year_ = myMovie.year_;
url_ = myMovie.url_;
actor_ = myMovie.actor_;
}
Brian R. Bondy