defining copy constructor and assignment operator

100 views Asked by At

It's my first time dealing with classes in C++. I was wondering if somebody could help me to properly design a copy constructor and an assignment operator for the following class.

The following post talks about the rule of threes,

What is The Rule of Three?

Although, it was not very clear how to implement it for my code.

INFO.h

#ifndef INFO_H
#define INFO_H

class INFO{
public:
        std::string label, type;
        unsigned int num;
        double x, y, z, velx, vely, velz;
        void print(std::ostream& stream);
        void mod_print(std::ostream& stream);
        void read(std::istream& stream);
        void mod_read(std::istream& stream);
        double distance(INFO *i,double L);
        INFO(std::istream& stream);
        INFO(){};
};

#endif

INFO.cpp

#include "INFO.h"

void INFO::print(std::ostream& stream)
{
        stream << label <<'\t'<< type <<'\t'<< num <<'\t'<< x<<'\t'<<y<<'\t'<< z << '\n';
}
void INFO::mod_print(std::ostream& stream)
{
        stream << label <<'\t'<< type <<'\t'<< x<<'\t'<<y<<'\t'<< z << '\n';
}
void INFO::read(std::istream& stream)
{
        stream >> label >> type >> num >> x >> y >> z;
}
void INFO::mod_read(std::istream& stream)
{
        stream >> label >> type >> x >> y >> z;
}
double INFO::distance(INFO *i,double L)
{
        double delx = i->x - x - std::floor((i->x-x)/L + 0.5)*L;
        double dely = i->y - y - std::floor((i->y-y)/L + 0.5)*L;
        double delz = i->z - z - std::floor((i->z-z)/L + 0.5)*L;
        return delx*delx + dely*dely + delz*delz;
}
INFO::INFO(std::istream& stream)
{
        stream >> label >> type >> num >> x >> y >> z;
}
1

There are 1 answers

4
Bharadwaj On

Since your class contains these member variables

std::string label, type;
unsigned int num;
double x, y, z, velx, vely, velz;

In the copy constructor you copy the values present in the reference object. So, define the constructor as below

INFO::INFO(const INFO &Ref)
{
    // copy the attributes
    this->label = Ref.label;
    this->type = Ref.type;
    this->num = Ref.num;
    this->x = Ref.x;
    this->y = Ref.y;
    this->z = Ref.z;
    this->velx = Ref.velx;
    this->vely = Ref.vely;
    this->velz = Ref.velz;
}

For the assignment operator you need to write a function like this

INFO& INFO::operator= (const INFO &Ref)
{
    // copy the attributes
        this->label = Ref.label;
        this->type = Ref.type;
        this->num = Ref.num;
        this->x = Ref.x;
        this->y = Ref.y;
        this->z = Ref.z;
        this->velx = Ref.velx;
        this->vely = Ref.vely;
        this->velz = Ref.velz;

    // return the existing object
    return *this;
}

Hope this works, let me know