Hi All,
While executing below code without using assigment operator it works fine , eventhough i have been used pointer
values, so any way it must crash as The memory that s2 used to point to was never deleted;
it is lost forever as both a and b now point to same place When one of them goes out of scope, its destructor will delete the same memory. Both are allocated object so memory crash must be happend and it is expected here.
~Mohan
#include<iostream.h>
#include<conio.h>
using namespace std;
class Derived1
{
int *m_p;
public:
Derived1 ();
Derived1& operator =( const Derived1 &obj);
void show()const {cout<<"integer="<<*m_p<<endl;}
void setVal(int);
~Derived1(){
delete m_p;
//m_p=NULL;}
}
};
void Derived1::setVal(int val)
{
*m_p = val;
}
Derived1::Derived1()
{
m_p=new int(0);
}
Derived1& Derived1::operator=(const Derived1 &obj)
{
int *ptr= new int (*obj.m_p);
delete m_p;
m_p=ptr;
return *this;
}
int main()
{
Derived1 s1 ;
s1.setVal(20);
s1.show();
Derived1 s2;
s2.setVal(100);
s2.show();
s2=s1;
s1.show();
s2.show();
getch();
}