Fail to call destructor of other class C++ - c++

So I have this code, and when I run it, I got a run time error when class B is trying to call its destructor. The destructor of class A seems fine. I wonder what's wrong with this code. Thanks for helping.
#include <iostream>
using namespace std;
class A{
public:
//Constructor
A(int N){
this->N = N;
array = new int[N];
}
//Copy Constructor
A(const A& A1){
this->N = A1.N;
//Create new array with exact size
this->array = new int[N];
//Copy element
for(int i=0; i<N; i++){
this->array[i]= A1.array[i];
}
}
~A(){
delete [] array;
cout<<"Success"<<endl;
}
int N;
int* array;
};
class B{
public:
B(const A& array1){
array = new A(array1);
}
~B(){
delete [] array;
}
A* array;
};
using namespace std;
int main(){
A matrix1(10);
B testing(matrix1);
return 0;
}

In B::~B(), you call delete[] on B::array after allocating it via new in B::B(const A&).
This is illegal: You must always pair new with delete and new[] with delete[].

you can't use the delete [] when you don't create an array of elements, your destructor must be like:
~B(){
delete array;
}

Remove the [] when you delete the allocated memory in b because you allocated for just one element and the [] makes the compiler assumes that you are deleting an array allocated memory.

Related

does overloading array operator need the assignment operator and the stream operators to be overloaded to use them in the main?

#include <iostream>
using namespace std;
class A
{
public:
int operator [] (int);
private:
int LIST [];
};
int A::operator [] (int index)
{
return LIST[index];
}
int main()
{
A obj[3];
cin >> obj [2]; // or obj [2] = 15;
cout << obj[1];
return 0;
}
I want to know why I have to overload the assignment and stream operators to write such code in main, although I use them with a member function (which is the array operator), not with a standing alone object name.
int LIST []; is not a valid array declaration. If you know the size of the array at compile time, you need to specify it explicitly, eg:int LIST[size]; where size is a compile-time constant. Otherwise, use std::vector instead to allocate an array at runtime.
More importantly, A obj[3]; is an array of A objects, which is not what you want in this situation. You need a single A object instead, eg: A obj;
When obj is an array, obj[index] will not invoke your operator[]. It will simply access an object at the specified index in the array, nothing more. That is why you end up having to implement the extra assignment and stream operators for A to make the shown code actually do things with that object:
cin >> obj [2]; accesses the A object at array index 2, and then passes that object to operator>>.
obj [2] = 15; accesses the A object at array index 2, and then invokes A::operator= on that object.
cout << obj[1]; accesses the A object at array index 1, and then passes that object to operator<<.
To invoke your operator[] on an A object, you need access to a sole A object to begin with, not an array of A objects.
I suspect you wanted to pass 3 from main() into A to allocate the A::LIST member. If so, try this instead:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A(int);
int& operator [] (int);
private:
vector<int> LIST;
};
A::A(int count) : LIST(count) {}
int& A::operator [] (int index)
{
return LIST[index];
}
int main()
{
A obj(3); // calls A::A(3)
cin >> obj[2]; // calls obj.operator[](2)
obj[2] = 15; // calls obj.operator[](2)
cout << obj[1]; // calls obj.operator[](1)
return 0;
}
Online Demo
UPDATE: Or, if you are not allowed to use std::vector, then you can use new[]/delete[] instead, and follow the Rule of 3/5/0 to manage the pointer properly, eg:
#include <iostream>
using namespace std;
class A
{
public:
A(int);
~A();
// I'll leave these Rule-Of-3/5/0 items as an
// exercise for you to implement later...
A(const A&) = delete;
A(A&&) = delete;
A& operator=(const A&) = delete;
A& operator=(A&&) = delete;
//
int& operator [] (int);
private:
int *LIST;
};
A::A(int count) {
LIST = new int[count];
}
A::~A() {
delete[] LIST;
}
int& A::operator [] (int index)
{
return LIST[index];
}
int main()
{
A obj(3); // calls A::A(3)
cin >> obj[2]; // calls obj.operator[](2)
obj[2] = 15; // calls obj.operator[](2)
cout << obj[1]; // calls obj.operator[](1)
return 0;
} // <-- A::~A() called here
Online Demo

Overloading new operator using friend function

I have overloaded 'new' operator as a member function for my class Array. I need help overloading it as a friend function. See the program below:
#include<iostream>
using namespace std;
class Array {
private:
int *arr;
int size;
public:
void * operator new (size_t size)
{
void *ptr = ::new Array;
return ptr;
}
void operator delete(void *ptr)
{
::delete ptr;
}
Array(int n=5)
{
this->size = n;
this->arr = new int[n];
}
void input()
{
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
cin>>arr[i];
}
void show()
{
for(int i=0; i<size; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
};
int main()
{
Array *A = new Array(4);
A->input();
A->show();
return 0;
}
What I tried to do in friend function:
void * operator new (size_t size) throw (std::bad_alloc)
{
void * ptr = ::new Array;
return ptr;
}
I got an infinite loop for this. Can anyone help me here?
Edit : Grammar
There can be only one ::operator new(size_t). Normally the standard library provides one. If you provide one, it replaces (doesn't overload) the one provided by the standard library.
Your version calls itself unconditionally (there's no other ::operator new(size_t)) so there's an unbounded recursion and a stack overflow in there.
You cannot provide ::operator new(size_t) and hope it will work together with the system-provided ::operator new(size_t) but only for your class.
The only way to make a global overloaded operator new is to give it a different signature, e.g.
enum foo {bar};
void* operator new (std::size_t size, foo) { ... }
...
Array* arr = new (bar) Array;
But you can use it to allocate any type, not just Array, regardless of which classes decide to befriend it.
So just adding on above answer you can overload your operator new and delete in following manner and this will work because one inside constructor will call operator new[] not operator new.Also no need to make this friend since you are not accessing any private data member in this function:
#include <iostream>
#include <string>
using namespace std;
class Array {
private:
int *arr;
int size;
public:
Array(int n=5)
{
this->size = n;
this->arr = new int[n];
}
void input()
{
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
cin>>arr[i];
}
void show()
{
for(int i=0; i<size; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
};
void * operator new (size_t size)
{
void *ptr = std::malloc(size);
return ptr;
}
void operator delete(void *ptr)
{
std::free(ptr);
}
int main()
{
Array *A = new Array(4);
A->input();
A->show();
return 0;
}

Dynamic memory allocation in constructor

I am learning dynamic memory allocation. I have the following class where 'class A' should own a dynamically allocated array in the constructor. Also the copy constructor and destructor should be modified. This is what I have so far...
#include <iostream>
#ifndef A_HH
#define A_HH
#include "B.hh"
class A {
public:
A() { B *array = new B[12];}
A(const A&) { /* Do not know what to put here..*/ }
~A() { delete[] array;}
private:
//B array[12] ; <- This is the array that I have to modify so it becomes dynamic.
B *array;
} ;
#endif
For starters your default constructor there is overriding the member variable "array" with a local variable of the same type, so you want the default constructor to look like this:
A() { array = new B[12]; }
Then the copy constructor presumably needs to deep copy the array over, but with a simple array you can't tell the arraysize at runtime. You need to either move to a smarter container (e.g. stl::vector) or store the size, but a naive copy constructor would look like this:
A(const A& other)
{
array = new B[12];
for(int i=0;i<12;i++)
{
array[i] = other.array[i];
}
}
Check out this code:
#include <iostream>
using namespace std;
class MyArray{
public:
int* array;
int length;
MyArray(int length){ // constructor which takes length of array as argument
this->length = length;
this->array = new int[this->length];
for(int i=0; i<this->length; i++){
this->array[i] = i;
}
}
MyArray(const MyArray &obj){
this->length = obj.length;
this->array = new int[this->length];
for(int i=0; i<this->length; i++)
{
this->array[i] = obj.array[i];
}
}
~MyArray(){ // destructor
delete[] this->array;
}
void print(){ // test method for printing the array
for(int i=0; i<this->length; i++){
cout << this->array[i] << endl;
}
cout << endl;
}
private:
protected:
};
int main()
{
MyArray *array = new MyArray(10);
MyArray *array2 = new MyArray(*array); // call copy constructor
array->print();
array2->print();
delete array;
delete array2;
}

In void getData() , How can I access the memory location returmed by void* pointer?

when I try to enter elements through getData() function, I get error segmentation fault(core dumped).
I am not able to enter elements into array. I am not able to understand why i cannot access the memory location returned by void* into Class type.
size of *parr is 4 bytes, still I cannot data into that memory location???
#include<iostream>
#include<cstdlib>
using namespace std;
class Array
{
int *arr;
public:
void* operator new(size_t size)
{
void *parr=::new int[size];
//cout<<sizeof(parr);
return parr;
}
void operator delete(void *parr)
{
::delete (int*)parr;
}
void getData()
{
cout<<"Enter the elements";
for(int i=0;i<5;i++)
cin>>arr[i];
}
void showData()
{
cout<<"Array is:\n";
for(int i=0;i<5;i++)
cout<<arr[i];
}
};
int main()
{
Array *A=new Array;
A->getData();
//A->showData();
(*A).showData();
delete A;
return 0;
}
What you probably meant to do instead of overloading the new and delete operators for class Array, is to write appropriate constructor and destructor functions:
class Array {
int *arr;
public:
Array(size_t size) : arr(new int[size]) {
}
~Array() {
delete arr;
}
// ...
};

Deleting Private Array in Copy Constructor and Assignment operator

I'm trying to implement a container that allocated memory to the heap, but it seems as though my base constructor and my argument constructor don't like each other. Below, I've posted the code without anything commented out. As it stands, it crashes.
#include <iostream>
using namespace std;
class foo
{
public:
foo() {size=1; vals = new double[1]; vals[0]=0;}
~foo() {delete[] vals;}
foo(const foo& other)
{
size=other.getsize();
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=other[i];
}
foo& operator=(const foo& other)
{
size=other.getsize();
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=other[i];
return *this;
}
foo(double* invals, long unsigned insize)
{
size=insize;
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=invals[i];
}
double operator[](long unsigned i) const {return vals[i];}
long unsigned getsize() const {return size;}
private:
double* vals;
long unsigned size;
};
int main()
{
double bar[3] = {5,2,8};
foo B(bar, 3);
cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl; //couts fine
foo A; //crashes here
return 0;
}
However, when I change main to be:
int main()
{
double bar[3] = {5,2,8};
foo B(bar, 3);
cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl; //couts fine
foo A(); //works now
return 0;
}
It runs fine. But then I can't assign A = B because it thinks foo is a function or something.
I assume you have some really compelling reason not to use std::vector<double> here...
But anyway... in your copy constructor, you don't want to delete[] vals.
foo(const foo& other)
{
size=other.getsize();
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=other[i];
}
When the copy constructor is called, your object hasn't been initialized yet, so vals* doesn't even point to anything valid. Therefore, deleting it invokes undefined behavior (and your program crashes.) You only need to delete[] vals in your assignment operator.
Also, when you declare the Foo variable A, you don't want those parentheses after the variable name. Just say:
foo A;
When you place those parenthesis after the variable name, you're actually writing a function declaration using syntax inherited from C, and A becomes a function pointer type.