Untitled
unknown
c_cpp
2 years ago
1.2 kB
9
Indexable
#include <iostream>
using namespace std;
//THIS CODE WILL RESULT IN HEAP CORRUPTION!!!! TWO OBJECTS ARE POINTING TO THE SAME AREA, AND ONE OF THEM IS
//RELASING THE MEMORY WHICH STILL IS BEEING REFERED BY OTHER ONE
class Shallow {
private:
int *data; //ALLWAYS USE DEEP COPY WHEN HAVING RAW C++ POINTERS!!!
public:
void set_data_value(int d){*data =d;}
int get_data_value(){return *data;}
//Constructor
Shallow(int d);
//Copy constructor
Shallow(const Shallow &source);
//Destructor
~Shallow();
};
Shallow::Shallow(int d){
cout << "Constructor - creating an object" << endl;
data = new int;
*data = d;
}
Shallow::Shallow(const Shallow &source)
: data(source.data){
cout << "Copy constructor - shallow copy" << endl;
}
Shallow::~Shallow(){
delete data;
cout << "Destructor freeing data" << endl;
}
void display_shallow(Shallow s){
cout << s.get_data_value() << endl;
}
int main() {
Shallow obj1{100};
display_shallow(obj1);
Shallow obj2{obj1};
obj2.set_data_value(1000);
return 0;
}Editor is loading...