0

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

Da Artagnan
  • 1,109
  • 3
  • 17
  • 26

2 Answers2

3

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?

Community
  • 1
  • 1
Anon Mail
  • 4,660
  • 1
  • 18
  • 21
0

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;
}
Aron Wolf
  • 58
  • 1
  • 8