Hello everybody!
I wrote an example about a copy constructor and the result wasn't what i expected. Here's the example:
#include <iostream>
using namespace std;
class A {
public:
A(const A& cp);
A(double t[], int size);
~A();
double *getTab() const { return tab; }
double *tab;
int size;
};
int main() {
double t[] = {3.4, 5.6, 7.6};
A obj1(t, 3);
{
A obj2 = obj1;
cout << "ob1.tab[0] = {" << obj1.getTab()[0] << "}" << endl;
cout << "ob2.tab[0] = {" << obj1.getTab()[0] << "}" << endl;
} //-->this is where obj2 is out of scope
cout << "ob1.tab[0] = {" << obj1.getTab()[0] << "}" << endl;
return 0;
}
A::A(const A& cp) : size(cp.size) {
tab = new double[size];
for (int i = 0; i < size; i++)
tab[i] = cp.tab[i];
}
A::A(double t[], int size) {
tab = new double[size];
for (int i = 0; i < size; i++)
tab[i] = t[i];
}
A::~A() {
cout << "Destructor ~A() called\n";
delete [] tab;
}
So, in the example above i created a class having a private double pointer and wrote and the copy constructor as well. Deliberately i created a block, where inside that block i declared object obj2 using my copy constructor:
A obj2 = obj1;
All went well but when i deleted my copy constructor and tested the code, surprisingly the code was executed correctly again! I thought that if i didn't write a copy constructor then, when obj2 would be out of scope the destructor would be called and eventually would delete the pointer. So i wouldn't be able to get the correct result. But i did get the correct result with the following line:
cout << "ob1.tab[0] = {" << obj1.getTab()[0] << "}" << endl;
Am i missing something? Thank you for your time!