I am very new to OOP and am still trying to comprehend all the concepts of the constructors. I have a class with some data and I have to make a Copy Constructor
and Assignment Operator
, however, since this is the first time I am doing something like this, I am not sure if what I have written makes sense. So, I am asking if what I have written are valid Copy Constructor and Assignment Operator. The class is saved in a file called BKS.h
Thank you!
Here is the class :
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
template <class T>
class BKS final
{
public:
struct Item
{
T identifier;
int weight;
int benefit;
};
BKS() {}
BKS(const BKS<T> ©);
BKS(const vector<Item> &items) : itemlist_{items} {}
BKS(const vector<pair<int, int>> &weight_benefit_list);
BKS<T> &operator=(const BKS<T> ©);
// some methods ....
private:
vector<Item> itemlist_;
vector<int> current_selection_;
int current_capacity_ {0};
int maximal_benefit_ {0};
};
Copy Constructor and Assigment Operator :
#include "bks.h"
template <class T>
BKS<T>::BKS(const BKS<T> ©) // copy constructor
{
std::vector<Item> itemlist_ = copy.itemlist_;
std::vector<int> current_selection_ = copy.current_selection_;
int current_capacity_ = copy.current_capacity_;
int maximal_benefit_ = copy.maximal_benefit_;
}
template <class T>
BKS<T> &BKS<T>::operator=(const BKS<T> ©)
{
if (© != this)
{ // check for self-assignment
this->itemlist_ = copy.itemlist_;
this->current_selection_ = copy.current_selection_;
this->current_capacity_ = copy.current_capacity_;
this->maximal_benefit_ = copy.maximal_benefit_;
}
return *this;
}
Also any general recommendations concerning constructors are welcome :)