I have some doubts about copy constructor and assignment operator. I know that when I define a constructor, the default constructor is not synthetized by the compiler. My doubt is if it is ok to define just the copy constructor. I would say no since if I define the copy constructor the default constructor is not synthetized so I cannot initialize objects, because I would need an object of that class, which I don't have. I don't know if this is right. My second doubt is about value-like implementation of a class containing a pointer. Every code I've seen until now use the new operator inside both copy and assignment operator. For instance:
#include <string>
#include <vector>
#include "book.hh"
class Student
{
std::string name;
unsigned int id;
unsigned int age;
char gender;
std::vector<Book> * books;
/*Copy-constructor*/
Student (const Student & other)
{
name = other.name;
id = other.id;
age = other.age;
gender = other.gender;
books = new std::vector<Book> (*other.books);
}
/*Assignment operator*/
Student & operator = (const Student & other)
{
if (this != &other)
{
name = other.name;
id = other.id;
age = other.age;
gender = other.gender;
delete books;
books = new std::vector<book> (*other.books);
}
return *this;
}
}
The document says that a constructor should be implemented. What bout the constructor? How can I instantiate a class without having a constructor(which is not the copy constructor), in this case? Morover, I don't understand why it uses new in the copy constructor and in the assignment operator. I would do for instance, in the assignment operator body, *books = *(other.books); is this also correct?
books
needs a memory slot for*books = *(other.books);
to work. Thus, you need to allocate memory for your vector. Of course the use of a dynamically allocated vector is questionable, but I'm not sure your question is here – Adrien Givryvector
to holdBook
s -new
seems like a bad idea. – Ted Lyngmostd::vector<Book> books;
and in the copy ctor and copy assignment operator:books = other.books;
– Ted Lyngmostd::vector<Book> * books;
tostd::vector<Book> books;
and you don't need to define any of the special member functions. – NathanOliver