This should call the assignment operator, but how? - c++

I am a C++ newbie here. My assignment is to create a Vector class without using the Vector class that already exists. I am not sure if I have implemented the assignment operator correctly. If so, how can I use it in the main function?
# include <iostream>
# include <string.h>
using namespace std;
class Vector{
public:
unsigned int * p;
size_t size;
Vector(){ // Default contructor
cout << "The default contructor" << endl;
this -> size = 20; // initial value
this -> p = new unsigned int [size];
// trying to set every elements value to 0.
for(int i = 0; i < size; i++){
*(p+i) = 0;
}
}
Vector (const Vector & v){ // The copy contructor
cout << "The copy constructor" << endl;
this -> size = v.size;
p = new unsigned int[size];
for(int i = 0; i < size; i++){
*(p+i) = *(v.p + i);
}
}
Vector& operator = (const Vector & v){
cout << "The assignment operator" << endl;
this -> size = v.size;
p = new unsigned int[size];
for(int i = 0; i < size; i++){
*(p + i) = *(v.p + i);
}
//p = p - size; // placing back the pointer to the first element
//return *this; // not sure here
}
void print_values(){
for(int i = 0; i< size; i++){
cout << *(p + i) << " ";
}
cout << endl;
}
};
int main(){
Vector * v1 = new Vector();
(*v1).print_values();
Vector * v2; // this should call the assignment operator but......... how?
v2 = v1;
(*v2).print_values();
Vector v3(*v1);
v3.print_values();
}

Your line:
v2 = v1;
Won't call your assignment operator. It just assigns one pointer to another pointer. You need to make an assignment between objects for your operator to be used.
You want something like:
Vector v1;
v1.print_values();
Vector v2;
v2 = v1;
And so on. Your program has some memory leaks, too - watch out!
Editorial note: Why *(p+i) instead of p[i]? The latter is a lot easier to read.

You are assigning one pointer to another, not one class instance to another. In order to invoke your assignment operator, you need to have two class instances (you only have one) and then deference the pointers so you access those instances, eg:
int main(){
Vector * v1 = new Vector();
v1->print_values();
Vector * v2 = new Vector();
*v2 = *v1;
v2->print_values();
Vector v3(*v1);
v3.print_values();
delete v1;
delete v2;
}
Alternatively:
int main(){
Vector v1;
v1.print_values();
Vector v2;
v2 = v1;
v2.print_values();
Vector v3(v1);
v3.print_values();
}

Related

print an array after deep copying in c++ classes

I want to achieve the following behaviour:
The class DataSequence has a pointer that points to an array in the main function.
print the array when an object in initialised of the class DataSequence
create a deep-copy of the same object (via a copy constructor) and print it when the object is formed.
The code I have written is as follows:
#include<bits/stdc++.h>
using namespace std;
class DataSequence{
float *ptr;
int _size;
public:
DataSequence(float input[] , int size){
_size = size;
ptr = new float; ptr = input;
//print the array
cout << "Main constructor" << endl;
for(int i=0 ; i<_size; ++i){
cout << *(ptr+i) << " ";
// ++ptr;
}
}
//copy constructor
DataSequence(DataSequence &d){
_size = d._size;
ptr = new float; *ptr = *(d.ptr);
//print the array
cout << "copy constrructor" << endl;
for(int i=0 ; i<_size ; ++i){
cout << *(ptr+i) <<" ";
// ++ptr;
}
}
};
int32_t main(){
int size=4;
float input[size];
int bins;
input[0] = 3.4;
input[1] = 1.3;
input[2] = 2.51;
input[3] = 3.24;
DataSequence d(input , size);
cout << endl;
DataSequence d1 = d;
return 0;
}
The output is as follows
Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041
I am unable to figure out why I am getting garbage from the copy constructor, can someone help.
This statement:
ptr = new float;
only allocates a single float. That means in this loop:
for(int i=0 ; i<_size; ++i){
cout << *(ptr+i)
as soon as i is greater than 0, you dereference invalid memory, which is undefined behavior. This results in a program that can do anything, including producing the "garbage" output you see.
If you want to allocate an array, you need to do:
ptr = new float[_size];
and to delete it, you need to do:
delete [] ptr;
Note that even if you allocate memory correctly as shown above, you are not actually copying the data from the argument. Just setting pointers would do a shallow copy which is not what you want.
You can do a deep copy like this:
std::copy(d.ptr, d.ptr + _size, ptr);

how to copy Int array to int pointer using constructor in C++

I am trying to insert int array x to int *v. here is my code . please provide me with optimal solutions and the reason behind it.
there is an error in this line. Instead of copying array value its taking garbage value. line v1=x;
class vector
{
int *v;
int size;
public:
vector(int m)
{
v = new int[size = m];
for (int i = 0; i < size; i++)
v[i] = 0;
}
vector(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
}
int operator *(vector &y)
{
int sum = 0;
for (int i = 0; i < size; i++)
sum += v[i] * y.v[i];
return sum;
}
void disp()
{
for (int i = 0; i < size; i++)
cout << v[i] << " ";
cout << "\n";
}
};
int main()
{
clrscr();
int x[3] = { 1,2,3 };
int y[3] = { 4,5,6 };
vector v1(3);
//v1.disp();
vector v2(3);
v2.disp();
v1 = x;
v1.disp();
//v2=y;
v2.disp();
int r = v1 * v2;
cout << "R = " << r;
getch();
return 0;
}
You forgot to add the assignment operator in your vector class:
vector & operator=(int *a)
{
for (int i = 0; i < size; i++)
v[i] = a[i];
return *this;
}
In the the line
v1=x;
May be, you are expecting it to invoke the second constructor which takes int* as argument. But it won't happen.
It can be seen as Type Conversion from Basic type to Class type. where we expect appropriate constructor will get invoked.
see http://www.hexainclude.com/basic-to-class-type-conversion/
But remember, Constructor will be invoked only once after the creation of object.
Here, in the line
vector v1(3);
the first constructor was already invoked. Then the line
v1=x;
won't invoke the second constructor now.
For every class, = operator is default overloaded . That is the reason why we can easily assign objects to one another.
Therefore, the line v1=x invokes default overloaded assignment = operator.
Here, it treats address of array x i.e., &x[0] as address of class object. As it is not address of vector class object
=> it results a Segmentation fault.
YOUR ANSWER
To assign int array to int pointer i.e., to the member variable int* v of the vector class,
overload assignment operator = inside the class .
or
Initialize the class object to array in first line itself. i.e.,
vector v1=x; // modify the class constructor to have size as a constant.

A heap has been corrupted when trying to run code

When ever I run my program it breaks and has the error "A heap has been corrupted" when debugging the program, it actually will go through the whole thing just fine and break on the system("PAUSE") which seems like an odd place to have an error. I am clueless where the issue is. The program worked just fine, until I added the operator overload for + and OS
Below is my code:
MAIN.CPP
#include "stdafx.h"
#include "vector.h"
// the printV function
// used to test the copy constructor
// parameter: a MyVector object
void printV(Vector);
int main()
{
cout << "\nCreating a vector Sam of size 4.";
Vector sam(4);
cout << "\nPush 12 values into the vector.";
for (int i = 0; i < 12; i++)
sam.push_back(i);
cout << "\nHere is sam: ";
cout << sam;
cout << "\n---------------\n";
cout << "\nCreating a vector Joe of size 4.";
Vector joe(4);
cout << "\nPush 6 values into the vector.";
for (int i = 0; i < 6; i++)
joe.push_back(i * 3);
cout << "\nHere is joe: ";
cout << joe;
cout << "\n---------------\n";
cout << "\nTest the overloaded assignment operator \"joe = sam\": ";
joe = sam;
cout << "\nHere is sam: ";
cout << sam;
cout << "\n---------------\n";
cout << "\nHere is joe: ";
cout << joe;
cout << "\n---------------\n";
// pass a copy of sam by value
printV(sam);
system("PAUSE");
return 0;
}
void printV(Vector v)
{
cout << "\n--------------------\n";
cout << "Printing a copy of a vector\n";
cout << v;
}
VECTOR.H
#pragma once
#include <iostream>
#include "stdafx.h"
using namespace std;
class Vector
{
private:
int vectorSize;
int vectorCapacity;
int *vectorArray;
public:
//A default constructor that creates an vector with a default capacity of 2
Vector();
//A parameterized constructor that creates a vector of capacity n
Vector(int n);
// A function, size(), that returns the size of your vector.
int size();
// A function, capacity(), that returns the capacity of the vector.
int capacity();
// A function, clear(), that deletes all of the elements from the vector and resets its size to zero and its capacity to two.
void clear();
// A function push_back(int n) that adds the integer value n to the end of the vector.If the vector is not large enough to hold this additional value, you must make the vector grow.Your grow algorithm should double the current capacity of the vector.Don't forget to consider the case where the initial capacity of the vector is zero.
void push_back(int n);
// A function at(int n) that returns the value of the element at position n in the vector.If the index n is greater than the size() of the vector, this function should throw an exception.
int at(int n);
friend ostream& operator<<(ostream& os, Vector vt);
Vector operator=(Vector&);
VECTOR.CPP
#include "stdafx.h"
#include "vector.h"
Vector::Vector()
{
vectorSize = 0;
vectorCapacity = 0;
vectorArray = 0;
}
// Create new array with given capacity
Vector::Vector(int n)
{
vectorCapacity = n;
vectorArray = new int[vectorCapacity];
}
//Return array size
int Vector::size()
{
return vectorSize;
}
// Return array capacity
int Vector::capacity()
{
return vectorCapacity;
}
// clear array values
void Vector::clear()
{
for (int i = 0; i < sizeof(vectorArray); i++)
{
vectorArray[i] = '\0';
}
vectorSize = 0;
vectorCapacity = 2;
}
// Add number to array and double array size if needed
void Vector::push_back(int n)
{
int test = 100;
if (vectorCapacity > vectorSize)
{
vectorArray[vectorSize] = n;
vectorSize++;
}
else {
if (vectorCapacity == 0) {
vectorArray = new int[4];
vectorArray[0] = n;
vectorCapacity = 4;
vectorSize++;
}
else {
int newCapacity = vectorCapacity * 2;
// Dynamically allocate a new array of integers what is somewhat larger than the existing array.An algorithm that is often used is to double the size of the array.
int *tempArray = new int[newCapacity];
// Change capacity to be the capacity of the new array.
vectorCapacity = newCapacity;
// Copy all of the numbers from the first array into the second, in sequence.
for (int i = 0; i < Vector::size(); i++)
{
tempArray[i] = vectorArray[i];
}
delete[] vectorArray;
vectorArray = new int[newCapacity];
for (int i = 0; i < Vector::size(); i++)
{
vectorArray[i] = tempArray[i];
}
delete[] tempArray;
// Add the new element at the next open slot in the new array.
vectorArray[vectorSize] = n;
// Increment the size;
vectorSize++;
}
}
}
// Return Value and given point in array
int Vector::at(int n)
{
return vectorArray[n];
}
// Cout Vector
ostream& operator<<(ostream& os, Vector vt)
{
int size = vt.size();
for (int i = 0; i < size; i++) {
os << "index " << i << " is " << vt.at(i) << endl;
}
return os;
}
// Set one vector to equil another
Vector Vector::operator=(Vector& right) {
// Clear array on left
for (int i = 0; i < sizeof(vectorArray); i++)
{
vectorArray[i] = '\0';
}
vectorSize = right.size();
vectorCapacity = right.size() * 2;
// Assign values from left to right
for (int i = 0; i < vectorSize; i++)
{
vectorArray[i] = right.at(i);
}
return vectorArray[0];
}
The problem is operator=()
Why ?
You start with sam having a capacity of 4. You push back 12 items in it. When you reach the 5th element, the capacity is doubled from 4 to 8. Then you then reach the 9th element, the capacity is increased to 24.
You then have joe with an initial capacity of 4. You push back 6 items in it. When you reach the 5th element, its capacity is increased to 8.
When you then do joe = sam, your operator overwrites joe's size and capacity but without verifying that the capacity matches, and without allocating missing capacity. As you then try to copy 12 elements in a vector having in reality only a capacity of 8, you do some collateral damage in memory and corrupt the heap.
Solution
Do not overwrite blindly the capacity. Keep the capacity if it's sufficient. If not, align the capacity and reallocate.
// Set one vector to equal another
Vector Vector::operator=(Vector& right) {
//...
if (vectorCapacity < right.vectorCapacity) {
delete[] vectorArray; // assuming pointer is either nullptr or valid array
vectorArray = new int[right.vectorCapacity];
vectorCapacity = right.vectorCapacity;
}
vectorSize = right.size();
// Assign values from left to right
//...
return *this;
}
Note that it would be better to return the vector by reference !
There are lots of errors, but the one that causes the described symptoms is the operator= never allocates a new array of int for vectorArray
Each use of sizeof(vectorArray) is also wrong. That is just the size of a pointer, not the allocation of the area pointed to.
Each place that does vectorArray[i] = '\0'; is at best pointless, and whatever was intended, that is the wrong way to do it. Enough so I can't even guess the intent.
In the clear function the only necessary step was vectorSize = 0; The rest was at best pointless. Setting capacity to 2 there is bizarre, though it does no major harm.
operator= ought to have return type Vector& and not Vector and should return *this not construct a Vector whose capacity is a value from the old one. In general, almost any operator= member of a class should return *this. Exceptions to that rule are way beyond the level where you are currently trying to learn.
Given all of the answers so far, the other issue is that you failed to implement a user-defined copy constructor:
Vector(const Vector& n);
This function has to be implemented correctly since you have functions returning Vector by value. Since you didn't implement it, copying will not work correctly.
Second issue is that you should be returning the Vector by reference, not by value in the operator= function.
My first suggestion is to take whatever code you have now in your operator= and do the work of the "real" copying in the copy constructor. Here is a streamlined version of what the copy constructor should look like:
#include <algorithm>
//..
Vector::Vector(const Vector& rhs) : vectorCapacity(rhs.vectorCapacity),
vectorArray(new int[rhs.vectorCapacity]),
vectorSize(rhs.size())
{
std::copy(rhs.vectorArray, rhs.vectorArray + rhs.vectorCapacity, vectorArray);
}
Note the usage of the member initialization list, and the call to the function std::copy (you could also have written a loop, but just to show you that there are functions that do the copy without hand-written loops).
The second thing is that your destructor should simply do this:
Vector::~Vector()
{ delete [] vectorArray; }
Then operator= becomes very simple using copy / swap.
#include <algorithm>
//...
Vector& operator=(const Vector& v)
{
Vector temp = v;
swap(this.vectorCapacity, temp.vectorCapacity);
swap(this.vectorArray, temp.vectorArray);
swap(this.vectorSize, temp.vectorSize);
return *this;
}
This works only if the copy constructor and destructor work correctly, since operator= takes advantage of these functions.
Read more about the Rule of 3 and the copy / swap idiom.

second Constructor called in c++ ( wrong output)

I am trying to do a simple thing but suddenly stuck in between .
Here in my code I am trying to call a constructor in which i would only pass the length, my first constructor initializes an array of size = length with all elements 0.
Then i am passing the array to the constructor to give the previously defined array its values
here is the sample :
class myvector
{
int *arr;
int length;
public :
myvector(int);
myvector(int *);
};
myvector :: myvector (int len)
{
arr = new int [length = len];
for ( int i=0;i< length;i++)
{
arr[i] = 0;
}
}
myvector :: myvector ( int *ex)
{
for ( int i=0;i< length;i++)
{
cout << ex[i] << " " << length <<" ";
arr[i] = ex[i];
cout << arr[i]<< " ";
}
}
int main()
{
myvector v1(5);
int x[5] = {2,3,4,45,6};
v1 = x;
}
Here in my second constructor length which was defined in first constrcutor lost its values , also array arr loses its values
Did I do something ?
Please elaborate me on this
I don't think you quite get what the circumstances are in which constructors are invoked. The line v1 = x doesn't put the values into the memory allocated during the first constructor call. Rather, it constructs a new myvector (using the second constructor) and copies it into v1. The stuff you do during the first constructor call is lost.
It sounds like you want to define an assignment operator, not a constructor taking an int* argument. Also, in general you should declare single-argument constructors as explicit to prevent this sort of thing from happening accidentally.
First of all, when specifying a size of array like this, you should provide a constant value. See here. And I really encourage you to use std::vector<> for such tasks.
But anyway, like Sneftel mentioned, seems like you want to define an assignment operator (see here for more information about overloading operators in tasks like yours).
Here how I'd implemented it(NOT and ideal solution, but it works, and gives a basic idea):
#include <iostream>
using namespace std;
class myvector
{
int *arr;
int length;
public :
//I completely removed second constructor
myvector(int);
~myvector();
void operator=(const int* otherArray);
void printArray();
};
myvector::myvector (int len)
{
length = len;
arr = new int[length]; // This is the way, how you can handle a non constant array sizes
for ( int i=0;i< length;i++)
{
arr[i] = 0;
}
}
void myvector::printArray()
{
for(unsigned i = 0; i < length; ++i)
cout<<"arr["<<i<<"] = "<<arr[i]<<endl;
}
//Here's an overloaded '=' operator.
//int x[5] = {2,3,4,45,6};
//myvector v;
//v = x; - here this function is called
void myvector::operator=(const int* otherArray)
{
for(unsigned i = 0; i < length; ++i)
arr[i] = otherArray[i];
}
myvector::~myvector()
{
delete []arr; // You should ALWAYS delete what you allocated with new
}
int main()
{
myvector v1(5);
int x[5] = {2,3,4,45,6};
v1 = x;
v1.printArray();
}

Operator Overloading

I'm new to C++, this is my first week since the upgrade from fortran. Sorry if this is a simple question, but could someone help me with operator overloading. I have written a program which has two classes. One object contains a vector and two scalars, the other class simply contains the first object. In a test implementation of this code I suspect the operator overloading to be at fault. The program tries to accomplish the following goals:
1) Initialize first structure.
2) Initialize a second structure containing the initialized first structure. After this is imported, the value val0 = 10 is added to every element of the vector in the enclosing structure, structure2.structure1 .
3) Output structure1 and structure2 variables to compare.
For this simple program my output is:
100
100
0
0
0 0 10
1 1 11
2 2 12
3 3 13
...
I was expecting:
100
100
0
10
0 0 10
1 1 11
2 2 12
3 3 13
...
Clearly my overloaded = operator is copying my vector properly, but one of the scalars? Could someone help?
#include <iostream>
using namespace std;
typedef double* doublevec;
// This first class contains a vector, a scalar N representing the size of the vector, and another scalar used for intializing the vector.
typedef class Structure1
{
int N, vec0;
doublevec vec;
public:
// Constructor and copy constructor.
Structure1(int Nin, int vecin) : N(Nin), vec0(vecin) { vec = new double [N]; for(int i = 0; i < N; i++) { vec[i] = i + vec0; } }
Structure1(const Structure1& structurein);
// Accessor functions:
int get_vec0() { return vec0; }
int get_N() { return N; }
doublevec get_vec() { return vec; }
// Overide equivalence operator:
Structure1& operator=(const Structure1& right)
{
//Handle Self-Assignment
if (this == &right) return *this;
N = right.N;
vec0 = right.vec0;
for (int i = 0; i < N; i++)
{
vec[i] = right.vec[i];
}
return *this;
}
// Destructor:
~Structure1() { delete []vec; }
} Structure1;
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for(int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
}
// This class just contains the first structure.
typedef class Structure2
{
Structure1 structure;
// Mutator Function:
void mutate_structure();
public:
// Constructor:
Structure2(const Structure1& structurein) : structure(structurein) { mutate_structure(); }
// Accessor Function:
Structure1 get_structure() { return structure; }
// Destructor:
~Structure2() {}
} Structure2;
void Structure2::mutate_structure()
{
int N = structure.get_N();
Structure1 tempstruct(N,10);
structure = tempstruct;
}
int main (int argc, char * const argv[])
{
const int N = 100;
Structure1 structure1(N,0);
Structure2 structure2(structure1);
cout << structure1.get_N() << endl;
cout << structure2.get_structure().get_N() << endl;
cout << structure1.get_vec0() << endl;
cout << structure2.get_structure().get_vec0() << endl;
for(int i = 0; i < N; i++)
{
cout << i << " " << structure1.get_vec()[i] << " " << structure2.get_structure().get_vec()[i] << endl;
}
return 0;
}
it looks like vec0 isn't initialized by your copy constructor...
Try modifying your copy constructor to:
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for (int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
// ADD THIS LINE
vec0 = structurein.vec0;
}
Your copy-constructor Structure1::Structure1(const Structure1 &) doesn't copy vec0. It's not getting initialised at all, so gets whatever is in memory.
Also, you might want to check Structure1's operator=. If you assign a large vector to a small vector, then you'll potentially overflow the array in the destination. You might need to reallocate memory in operator=.