operator overloading for Array class - c++

i am trying to overload operators << >> != == = and [] for Array class.
The app crashes on run, though no compilation errors are shown.
what could possibly be wrong? IDE used dev c++
Here's array.h
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
using namespace std;
class Array{
friend ostream & operator << ( ostream &, const Array & );
friend istream & operator >> ( istream &, Array &);
private:
int size;
int * ptr;
public:
Array ( int = 10 );
Array ( const Array & ); //copy constructor
~Array ();
const Array &operator=( const Array & );
bool operator == ( const Array & ) const;
bool operator != ( const Array & ) const;
const int operator [] (int) const;
int getSize() const;
};
#endif
and now array.cpp
#include <iostream>
using namespace std;
#include "array.h"
Array::Array (int sze ){ //default constructor edited
size = (sze > 0 ? sze : 10);
ptr = new int [ size ];
for (int i = 0; i < size; i++)
ptr[ i ] = 0; //initial values
}
Array::Array (const Array & arr ): size(arr.size){
ptr = new int [size];
for ( int i = 0; i< size; i++)
ptr [ i ] = arr.ptr [ i ];
}
Array::~Array(){
delete [] ptr;
}
const Array &Array :: operator= ( const Array & right){//IMPO
if(&right != this){ //edited self assignment test
if(size != right.size){//diff sized arrays
delete [] ptr; //reclaim space
size = right.size;
ptr = new int [ size ]; //space created
}
}
for(int i=0; i<size; i++)
ptr[ i ] = right.ptr[ i ];
return *this; //enables cascading a=b=c
}
bool Array::operator == ( const Array & right) const{
if ( size != right.size )
return false;
for ( int i =0; i < size; i++ ){
if ( ptr [ i ] != right.ptr[ i ] )
return false;
}
return true;
}
bool Array::operator != ( const Array & right ) const{ //edited
return ! (*this == right);
}
const int Array::operator [] (int subscript) const{
if(subscript >=0 && subscript < size)
return ptr[ subscript ];
}
int Array::getSize() const{ return size; }
//friend functions not in .h
ostream & operator << ( ostream & output, const Array & array){
for (int i = 0; i < array.size; i++)
output << array.ptr[i] ;
}
istream & operator >> ( istream & input, Array & array){
for (int i = 0; i < array.size; i++)
input >> array.ptr[i];
}
now main.cpp
#include <cstdlib>
#include <iostream>
#include "array.h" // " " not <>
using namespace std;
int main(int argc, char *argv[])
{
Array a1(7),a2 (-1),a4; //changed a2
cout<<"Input "<<a1.getSize()<<" integers for Array object a1 and "<<a2.getSize()<<" integers for Array objecta2\n";
cin>>a1>>a2;
cout<<"a1 and a2 are\n";
cout<<a1<<endl<<a2;
cout<<"a1!=a2 : "<<(a1!=a2)<<endl;
cout<<"a1 ==a2: "<<(a1==a2)<<endl;
cout<<"Printing a1[5] : "<<a1[5]<<endl;
Array a3(a1);
a4 = a3;
system("PAUSE");
return EXIT_SUCCESS;
}

You have to reserve memory for ptr in the constructor.
Array::Array (int size ){ //default constructor
size = (size > 0 ? size : 10);
ptr = new int [size]; // ADD THIS LINE
for (int i = 0; i < size; i++)
ptr[ i ] = 0; //initial values
}
There are some other problems with your code that are not the direct source of the crash but are worth noting:
Array::operator != is defined in terms of itself. It should be similar to operator==, or you can re-use it with
if( *this == right )
return false;
return true;
Array::operator [] should probably throw an exception if the index is out of bounds. Currently it just returns garbage memory.
Inside Array::Array (int size ) the assignment to size assigns to the parameter, not to the member. Change the first line to:
this->size = (size > 0 ? size : 10);
operator<< and operator>> should return output and input, respectively.
ostream & operator << ( ostream & output, const Array & array){
for (int i = 0; i < array.size; i++)
output << array.ptr[i] ;
return output;
}

Also, you have en error in your implementation of operator != at line:
if ( *this != right ) - recursive definition, so, stack overflow.

You have 2 errors in your default constructor:
1) You do not allocate memory for ptr and you try to initialize it, this is certainly an error and cause an undefined behavior, so if you have some invalid value in ptr you may get a segmentation fault or worse you may overwrite value of some of your internal variables!
2) Name of variable of the default constructor is size and size = (size > 0 ? size : 10); change value of local variable size not the size member of your class, and because of that your size member will remain uninitialized and any use of that is illegal and you may still get exceptions like segmentation fault(for example size may be 7476327436 that certainly is far beyond end of your array.
and beside that you have 1 error in your operator !=, since you have if ( *this != right ) and that will use operator != for comparison, and this is a recursive function in all cases and you will get a stack overflow exception, so if you want to check for exact pointers use if ( this != right ) instead of that.
I don't fully check your code first time that I see it, but you have some other errors in your code and I don't know how you even compile it, In multiple places you do not provide return value for your function. Please remember Never ignore compiler warnings there exist to help you correct your programming errors:
const int Array::operator [] (int subscript) const{
if(subscript >=0 && subscript < size)
return ptr[ subscript ];
// If not what should I do?? add a return value here, this is a warning
// since compiler think somehow you know that your code never reach here
// but do you really know??
return 0;
}
ostream & operator << ( ostream & output, const Array & array){
for (int i = 0; i < array.size; i++)
output << array.ptr[i] ;
// You say that your function return an ostream& but where is it??
// this is an error so compiler have nothing to return instead of you!
// And if your compiler does not generate an error possibly it return
// junk value that will cause an error!!
return output;
}
istream & operator >> ( istream & input, Array & array){
for (int i = 0; i < array.size; i++)
input >> array.ptr[i];
// again you forget to return an istream& and again this is an error
return input;
}
but beside that I see no error in your code and it should run with no error

Related

Why am i getting this error: could not convert '0' from 'long int' to 'Sparse'

I am creating a code for a sparse matrix, basically for adding two sparse matrices.
And now it's not working. showing some error with return NULL.
When checking for the condition that if the dimensions of the matrix are not the same, it will not execute the program as the condition will be false and it will return NULL but it's showing an error there.
#include<iostream>
using namespace std;
class Element{
public:
int i;
int j;
int x;
};
class Sparse{
private:
int m;
int n;
int num;
Element *ele;
public: // constructor
Sparse(int n ,int m , int num){
this->n = n;
this->m = m;
this->num = num;
ele = new Element[this->num];
}
~Sparse(){ // destructor
delete []ele;
}
//Global functions for insertion and extraction
Sparse operator+(Sparse &s);
friend istream & operator>>(istream &is , Sparse &s); // Insertion operator
friend ostream & operator<<(ostream &os , Sparse &s); // Extraction operator
};
Sparse Sparse::operator+(Sparse &s)
{
int i , j , k;
if(m!=s.m || n!=s.n)
return NULL;
Sparse *sum = new Sparse(m,n,num+s.num);
i=j=k=0;
while(i<num && j<s.num){
if(ele[i].i < s.ele[j].i){
sum->ele[k++] = ele[i++];
}else if(ele[i].i > s.ele[j].i){
sum->ele[k++] = s.ele[j++];
}else{
if(ele[i].j < s.ele[j].j){
sum->ele[k++] = ele[i++];
}else if(ele[i].j > s.ele[j].j){
sum->ele[k++] = s.ele[j++];
}else{
sum->ele[k]=ele[i];
sum->ele[k++].x = ele[i++].x +s.ele[j++].x;
}
}
}
for(;i<num;i++)sum->ele[k++] = ele[i];
for(;j<s.num;j++)sum->ele[k++] = s.ele[j];
sum->num = k;
return *sum;
}
// void read()
istream & operator>>(istream &is , Sparse &s)
{
cout<<"Enter non zero elements:";
for(int i=0;i<s.num;i++){
cin>>s.ele[i].i>>s.ele[i].j>>s.ele[i].x;
}
return is;
}
// void Display()
ostream & operator<<(ostream &os , Sparse &s)
{
int k = 0;
for(int i= 0; i<s.m;i++){
for(int j=0 ; j<s.n; j++){
if(s.ele[k].i ==i && s.ele[k].j ==j){
cout<<s.ele[k++].x<<" ";
}else{
cout<< "0 ";
}
}
cout<<endl;
}
return os;
}
int main(){
Sparse s1{5,5,5};
Sparse s2{5,5,5};
// s1.read();
// s1.Display();
cin>>s1;
cin>>s2;
Sparse sum=s1+s2;
cout<<"Enter First Matrix:"<<endl<<s1;
cout<<"Enter Second Matrix"<<endl<<s2;
cout<<"Sum Matrix"<<endl<<sum;
return 0;
}
If you go and see the definition of NULL, you will notice that
#define NULL 0
The NULL is replaced by a 0, which is a long int.
In some programming languages, like Java and C#, objects are passed around as pointers, and therefore you can just assign them to null. C++, however, somehow works similar to a struct -- it is passed by value.
Sparse Sparse::operator+(Sparse &s) means that the operator will return a Sparse type. As classes are passed by value, it will return the object's data, a series of bytes. That means you can't just return a NULL to indicate that the concatenation had failed.
An alternative would be to throw an exception. You can also rewrite the operator to a method that returns a Sparse*, a pointer to a Sparse.
Sparse* addSparse(Sparse s1, Sparse s2) {
if(s1.m != s2.m || s1.n != s2.n)
return NULL;
// add them together
}
That way, the caller can check if the concatenation is successful by checking the returned value.
Sparse* result = addSparse(s1, s2);
if(result != NULL) {
// Consume the result
}
// Handle it

Cstring class in C++: Error in +operator?

I'm currently in the second sequence of a C++ course. I'm building my own string class using c-strings & dynamic memory.
I have a majority of my code working. I'm reading in a file and putting each word in a vector of my class type "ATString". We are supposed to combine 5 of the words read in, into a jumbo word, and putting that into another vector. When I use the debugger to step through my code, I see the words combining and it is copying the words over to the new ATString variable "tempJumbo". After a few lines run, the program crashes and tells me my program has triggered a breakpoint, leaving me on line 96 of the addition operator function.
Here the operator+ definition:
ATString ATString::operator+ (ATString& string1) {
int newSize = length() + string1.length();
ATString newString;
if (newSize > 20) { // increase capacity if size is greater than 20 characters
newString.increase_cap();
}
else {
cap = 20;
}
newString.strPtr = new char[newString.cap];
newString.end = newSize;
for (int i = 0; i < length(); i++) {
newString[i] = strPtr[i];
for (int j = length(); j < newSize; j++) {
newString[j] = string1.strPtr[j-end];
}
return newString;
}
And here is main, reading in the file and attempting to combine the words into a jumbo word.
int main() {
vector<ATString> words(100);
vector<ATString> lines(100); // calls default constructor 100 times
ifstream fin("infile3.txt");
int index = 0;
int wordCount = 0;
//READ
if (fin.fail()) {
cout << "Couldn't open infile2.txt" << endl;
system("pause");
exit(1);
}
while (!fin.eof()) {
fin >> words[index];
index++;
}
wordCount = index;
words.resize(wordCount);
//COMBINE 5 WORDS INTO ONE JUMBO
ATString tempJumbo;
int j = 0;
for (int i = 0;i < wordCount; i++) {
tempJumbo = words[i] + words[i+1] + words[i+2] + words[i+3] + words[i+4];
lines[j] = tempJumbo; // putting big word into lines vector
tempJumbo = " "; //resetting variable to hold jumbo word?
i = i + 4;
j++;
if (i == wordCount) {
break;
}
}
return 0;
}
I am also have issues with the destructor I wrote.. it's pretty simple and when I have this activated, it triggers an error as well and crashes the program. Not sure what is going here.
ATString::~ATString() {
delete strPtr;
}
Below is my header file:
#ifndef ATSTRING_H
#define ATSTRING_H
#include <istream>
using namespace std;
class ATString {
public:
ATString();// default constructor
ATString(const char* cstr); // cstring constructor
ATString(const ATString& argstr); // copy constructor
~ATString(); // destructor
ATString& operator = (const ATString& objToCopy); // assignment operator =
ATString operator + (ATString& string1); // addition operator +
int length() const;
int capacity() const;
void increase_cap();
char& operator [] (int index); // indexing operator
const char& operator [] (int index) const; // const indexing operator
bool operator <(const ATString& argstr) ;
bool operator > (const ATString& argstr) ;
bool operator ==(const ATString& argstr);
friend istream& operator >> (istream& inStrm, ATString& argstr); // extraction operator
friend const ostream& operator << (ostream& outStrm, const ATString& argstr); // insertion opertator
private:
char* strPtr;
int end;
int cap;
int compareTo(const ATString& argStr);
};
#endif
THANK YOU!
How big is your input file? If it is 100 words or more, then your index runs out of bounds on the line, when i = 96, i.e. trying to get words[100] element.
tempJumbo = words[i] + words[i+1] + words[i+2] + words[i+3] + words[i+4];

I have a problem with reading & printing my class

I have a problem with printing my class. I want this class to read a binary number and then print it. I am a Beginner, so here can be a really dumb mistake.
This code has a wrong output, but a correct input.
I tried to fix this, but I couldn't. I hope you will find the mistake.
Please help. Thanks!
Here is the code:
#include <iostream>
using namespace std;
class Binary
{
int len;
bool* arr;
public:
Binary();
Binary(const Binary&);
friend istream& operator >> (istream&, Binary&);
friend ostream& operator << (ostream&, const Binary&);
};
Binary::Binary()
{
len = 0;
arr = new bool[0];
}
Binary::Binary(const Binary& b)
{
len = b.len;
arr = new bool[len];
for (int i = 0; i < len; i++) {
arr[i] = b.arr[i];
}
}
istream& operator>>(istream& in, Binary& b)
{
char line[101];
in.getline(line, 100);
b.len = strlen(line);
b.arr = new bool[b.len];
for (int i = 0; i < b.len; i++) {
b.arr[i] = (line[i] == '0' ? 0 : 1);
}
return in;
}
ostream& operator<<(ostream& out, const Binary& b)
{
for (int i = 0; i < b.len; i++) {
out << b.arr;
}
return out;
}
int main() {
Binary a;
cin >> a;
cout << a;
return 0;
}
The problem is with this line of code:
out << b.arr;
You are printing the array pointer, b.arr, instead of a value in the array.
This will work:
out << b.arr[i] ? '1' : '0';
You should also consider writing a destructor to free your previously allocated memory, and also free the previous array before overwriting it's pointer on this line:
b.arr = new bool[b.len];

Creating Union of Sets using Dynamic Memory Allocation

Ok, so I have been thinking about this for days and I am really unsure how to approach these problems. So I need to do the following:
create a union method (i.e. union(set)) that creates a union for two sets. This method should somehow invoke the element method, a method whose specifications are mentioned below
create an operator overloaded method (+) that represents the union of sets (not sure why they are different, but that's what the specifications ask for). This method must also invoke the union method
element (int) that checks if the elements are a part of the set, I have a method below, but I am not sure if it's right
operator overload method that adds an element to a new set
If you could address at least one of these, i would greatly appreciate it, I am really struggling to understand how to address these specifications. Thanks so much for your help!
#ifndef SET_H
#define SET_H
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
class Set{
friend ostream &operator<< ( ostream &, const Set &);
friend istream &operator>> ( istream &, Set &);
public:
Set ( int = DEFAULTSIZE ); //default constructor
Set ( const Set & ); //copy constructor
Set ( int [], int, char ); //constructor passing array of integers, size, name of set
~Set(); //destructor
//assignment operator
const Set &operator= ( const Set &);
//equality operator
bool operator== ( const Set & ) const;
//inequality operator
bool operator!= ( const Set &s1) const{
return !(*this == s1);
}
//subscript operators
int &operator[] ( int );
int operator[] ( int ) const;
//methods to find union, intersection, and difference of sets
Set Union ( Set & );
Set Intersect ( Set & );
Set Difference ( Set & );
Set operator+ ( Set & ); //to represent union of two sets
Set operator^ ( Set & ); //to represent intersection of two sets
Set operator- ( Set & ); //to represent difference between two sets
bool element ( int );
private:
static const int DELIM = -999; // delimiter to signal end of input
static const int DEFAULTSIZE = 10;
int numOfElements;
int psize; //physical size of array
int *set; //pointer array to represent set
};
#endif
//SOURCE FILE
//default constructor
Set::Set ( int s ){
if ( s > 0 )
psize = s;
else
psize = DEFAULTSIZE;
//allocate an array of specified size
set = new int[ psize ];
if(!set) {
//send an error is system cannot allocate memory
cout << "Cannot Allocate Memory, exiting program... " << endl;
exit (1);
}
for ( int i = 0; i < psize; i++){
set[i] = 0;
numOfElements = 0;
}
}
//copy constructor
Set::Set ( const Set &setToCopy): psize(setToCopy.psize){
set = new int[psize];
if(!set){
cout << "Cannot Allocate Memory, exiting program..." << endl;
exit (1);
}
for (int i = 0; i < psize; i++ ){
set[i] = setToCopy.set[i];
numOfElements = psize;
}
}
Set::~Set(){
if (set)
delete [] set;
set = NULL;
}
const Set &Set::operator= ( const Set &s1 ){
if ( &s1 != this){
if (numOfElements != s1.numOfElements){
delete [] set;
psize = numOfElements;
set = new int [psize];
if (!set){
cout << "Cannot Allocate memory, exiting program..." << endl;
exit (1);
}
}
}
//assign contents of the array on the right to the contents of the array on the left
for ( int i = 0; i < psize; i++ ){
set[i] = s1.set[i];
numOfElements = psize;
}
return (*this);
}
bool Set::operator== ( const Set &s1 ) const {
bool validate = true;
if ( numOfElements == s1.numOfElements ){
for ( int i = 0; i < numOfElements; i++){
if ( set [i] != s1.set[i] ){
validate = false;
break;
}
}
}
return (validate);
}
int &Set::operator[]( int subscript ){
if ( subscript < 0 || subscript >= psize ) {
cout << " Error, exiting program... " ;
exit (1);
}
return set[subscript];
}
bool Set::element ( int n ) {
bool validate = false;
for ( int i = 0; i < psize; i++){
if ( set[i] = n )
validate = true;
}
return (validate);
}

How do you copy an object of a class to another object of the same class by using '='

How do you copy an object of a class to another object of the same class just by using '='. I know that we have to overload the operator. here's what I have so far
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
class arr
{
public:
int *arr1;
int len;
arr& operator = (const arr& eq) //for copying two arrays. <--- my overloader
{
arr temp1(eq.len);
arr *pttemp;
int i=0;
//temp.arr1=new int[eq.len];
//temp.len = eq.len;
for(i = 0 ; i < eq.len ; i++)
{
temp1.arr1[i] = eq.arr1[i];
}
pttemp = &temp1;
return temp1;
};
friend istream& operator >> (istream& ist, arr & r)
{
static int i = 0;
int *arrNew;
if (i == r.len)
{
r.len *=2;
arrNew = new int[r.len]; // allocate the new array
for(int j = 0; j < r.len/2; j++)// copy the old array to the first half of the new array
arrNew[j] = r.arr1[j];// delete the old array
delete [] r.arr1;// let arr point to the new array and continue use arr
r.arr1 = arrNew;
delete arrNew;
}
ist>>r.arr1[i];
i++;
return ist;
}
arr() //initializing constructor
{
len = 5;
arr1 = new int[len];
};
arr(int size) //initializing constructor with args
{
len = size;
arr1 = new int[len];
};
arr(arr& a) : arr1(a.arr1) //copy constructor
{
arr1 = new int[len];
};
~arr() //delete constructor
{
delete arr1;
};
};
void main()
{
int size = 5,i,temp,trig = 0;
arr orig(size), asc(size), desc(size);
//generate random numbers for orig
for (i = 0 ; i < size ; i++)
{
orig.arr1[i] = rand();
}
//copy original set to asc and desc
asc = orig;
desc = orig;
//sorting ascending
for (i = 0 ; i < size-1 ; i++)
{
trig = 1;
if (asc.arr1[i] < asc.arr1[i+1])
{
temp = asc.arr1[i];
asc.arr1[i] = asc.arr1[i+1];
asc.arr1[i+1] = temp;
trig = 0;
}
if (trig = 1)
break;
if (i == size - 1)
{
i = 0;
}
}
//sorting descending
for (i = 0 ; i < size-1 ; i++)
{
trig = 1;
if (desc.arr1[i] > desc.arr1[i+1])
{
temp = desc.arr1[i];
desc.arr1[i] = desc.arr1[i+1];
desc.arr1[i+1] = temp;
trig = 0;
}
if (trig = 1)
break;
if (i == size - 1)
{
i = 0;
}
}
//printing
cout<<"Original Array: ";
for (i = 0 ; i < size ; i++)
{
cout<<orig.arr1[i]<<" ";
}
cout<<endl;
cout<<"Ascending Array: ";
for (i = 0 ; i < size ; i++)
{
cout<<asc.arr1[i]<<" ";
}
cout<<endl;
cout<<"Descending Array: ";
for (i = 0 ; i < size ; i++)
{
cout<<desc.arr1[i]<<" ";
}
cout<<endl;
getch();
}
It compiles properly but it ('asc' and 'desc') displays numbers that are different from the 'orig' object.
The proper solution is something like this:
struct Foo
{
std::vector<int> arr;
friend std::ifstream & operator>>(/*...*/);
};
The implicitly defined assignment operator already does exactly what you need, and clever code reuse is the heart of C++ programming ("a language for library design").
If you want to write it by hand, you have to make the copy yourself:
struct Bar
{
unsigned int len;
int * arr;
Bar & operator=(Bar const & rhs)
{
len = rhs.len;
delete[] arr;
arr = new int[len];
for (unsigned int i = 0; i != len; ++i) { arr[i] = rhs.arr[i]; }
return *this;
}
Bar() : len(), arr() { }
// more constructors
Bar(Bar const &); // exercise: write this!
~Bar() { delete[] arr; }
};
This is a terrible, terrible idea, though, since this pattern doesn't generalize at all: it isn't exception safe -- imagine one of the copies in the for-loop threw an exception. Now you've lost your original data and leaked memory.
A better solution would be to allocate a temporary buffer first:
int * temp = new int[len];
for (...) temp[i] = rhs.arr[i];
delete[] arr;
arr = temp;
Now this code is quickly getting very ugly, and imagine you had more than one of those!
In a nutshell: use std::vector.
You don't need a temporary array object in the assignment operator, and you should copy to the array in this, and then return *this:
arr &operator=(const arr &eq)
{
// If "this" already has an array, then delete it
if (arr1)
delete [] arr1;
// Create a new array of the same length as the one we're assigning from
len = eq.len;
arr1 = new int [len];
// And copy the array
memcpy(arr1, eq.arr1, len * sizeof(int));
// Returning "*this" allows the assignment operator to be chained
return *this;
}
what you have implemented in operator overloading is quite confusing and seems wrong to me
arr& operator = (const arr& eq) //for copying two arrays. <--- my overloader
{
arr temp1(eq.len);
arr *pttemp;
int i=0;
//temp.arr1=new int[eq.len];
//temp.len = eq.len;
for(i = 0 ; i < eq.len ; i++)
{
temp1.arr1[i] = eq.arr1[i];
}
pttemp = &temp1;
return temp1;
};
1.why are you creating a new object temp?
2.why create a pointer of type arr. and assigning pttemp to point to temp whose scope is with in the function and then you are not using
it anywhere!!
you need not create a new object inside the function as "this" pointer is implicitly passed to the function.
you should overload it this way
arr& operator = (const arr& source)
{
//this->len = source.len;
len = source.len;
for(int i=0;i < source.len ; i++)
{
//this->arr1[i] = source.arr1[i];
arr1[i] = source.arr1[i];
}
return *this;
}
Your copy constructor also looks wrong, it doesn't copy the contents of the array.
I agree with Kerrek that you should use vector. But since you appear to be trying to re-implement vector for yourself, here's a simple "correct" way to manage the resources in your class, for illustration:
class arr
{
public:
// switch order of data members, we want to initialize "len" first
int len;
int *arr1;
// default constructor
// you could use "new int[len]()" instead, to zero-initialize the array
arr() : len(5), arr1(new int[len]) {}
// constructor with size
arr(int size) : len(size), arr1(new int[len]) {}
// copy constructor
arr(const arr &rhs) : len(rhs.len), arr1(new int[len]) {
std::copy(rhs.arr1, rhs.arr1 + len, arr1);
}
// destructor
~arr() {
delete[] arr1; // *not* "delete", you *must* use "delete[]"
}
// swap function (this is useful, observe that it cannot throw)
void swap(arr &rhs) {
std::swap(len, rhs.len);
std::swap(arr1, rhs.arr1);
}
// assignment operator
arr &operator=(arr temp) { // parameter by value uses the copy ctor
// so, anything that could throw (the allocation) is complete,
// before we make any modifications to this object.
// see how useful "swap" is, and the fact it cannot throw?
swap(temp);
return *this;
}
// for C++11
// move constructor
arr(arr &&rhs) : len(rhs.len), arr1(rhs.arr1) {
rhs.arr1 = 0;
}
};
Btw, the name of the data member arr1 makes me fear that you're going to add a second array later. Do not do this, it's far more trouble to write a class that correctly manages two resources, than it is to write a class that correctly manages one resource and another class that has two of those as data members.