Da Artagnan
Da Artagnan

Reputation: 1199

Adding two vectors using operator overloading

I got a class Vectors which has private dynamic array. All I wanted to do is to add two Vectors objects like A = A + B, but the program keeps crashing.

This is declaration of my class:

class Vectors
    {
    private:
        int* vector;
    public:
        Vectors(int);
        Vectors(Vectors&);
        ~Vectors();

        Vectors operator+(Vectors&);

    };

This is my implementation:

#include "Vectors.h"
#include "iostream"
using namespace std;

Vectors::Vectors(int value)
{
    this->vector = new int[3];
    for (auto i = 0; i < 3; i++)
    {
        vector[i] = 3;
    }
}

Vectors::Vectors(Vectorsy& copy)
{
    this->vector = new int[3];
    for (auto i = 0; i < 3; i++)
    {
        vector[i] = copy.vector[i];
    }
}

Vectors::~Vectors()
{
    delete[] vector;
}

Vectors Vectors::operator+(Vectors& obj) // There is sth wrong here.
{
    for (auto i = 0; i < 3; i++)
        this->vector[i] += obj.vector[i];

    return *this;
}

This is the error I get:

enter image description here

Upvotes: 1

Views: 7266

Answers (2)

Aron Wolf
Aron Wolf

Reputation: 58

The problem was the copy Constructor (Vectors::Vectors(const Vectors& copy) Hear a working code.

#include "iostream"
using namespace std;

class Vectors
    {
    private:
        int* vector;
    public:
        Vectors(int);
        Vectors(const Vectors&);
        ~Vectors();

        Vectors operator+(Vectors&);

    };


Vectors::Vectors(int value)
{
    this->vector = new int[3];
    for (auto i = 0; i < 3; i++)
    {
        vector[i] = 3;
    }
}

Vectors::Vectors(const Vectors& copy)
{
    this->vector = new int[3];
    for (auto i = 0; i < 3; i++)
    {
        vector[i] = copy.vector[i];
    }
}

Vectors::~Vectors()
{
    delete[] vector;
}

Vectors Vectors::operator+(Vectors& obj) // There is sth wrong here.
{
    for (auto i = 0; i < 3; i++)
        this->vector[i] += obj.vector[i];

    return *this;
}

int main()
{
        Vectors A(3), B(3);
        Vectors C = A+B;
}

Upvotes: 0

Anon Mail
Anon Mail

Reputation: 4770

I believe you need an operator= function. You haven't implemented it so the compiler writes a default one which does the wrong thing (due to the fact that the class has a pointer). Most likely the crash is occurring while deleting the same memory twice.

See What is The Rule of Three?

Upvotes: 3

Related Questions