S
sacgarg
Following code is behaving strange:
class WithPointerMember
{
char* str;
const size_t size;
public:
WithPointerMember():size(15) //ctor
{
str = new char[size];
strcpy(str, "Initialized");
}
WithPointerMember (const WithPointerMember& other):size(other.size)
//copy ctor
{
str = new char[size];
for(size_t i=0;i<size;i++)
str= other.str;
}
char* GetString(void) const
{
return str;
}
~WithPointerMember() //dtor
{
delete [] str;
}
};
Now In main function first I do like
int main(void)
{
WithPointerMember wpm;
WithPointerMember wpm1 = wpm; <---------- Initializing wpm1 from wpm
cout<<"string="<<wpm.GetString()<<"\n";
wpm.~WithPointerMember();
cout<<"string="<<wpm.GetString()<<endl;
cout<<"string="<<wpm1.GetString()<<endl;
return 0;
}
The output is expected :
string=Initialized
string=
string=Initialized
Now I change my main:
int main(void)
{
WithPointerMember wpm;
cout<<"string="<<wpm.GetString()<<"\n";
wpm.~WithPointerMember();
WithPointerMember *wpm1 = new WithPointerMember(); <-------
Initializing wpm1 from new
cout<<"string="<<wpm.GetString()<<endl;
cout<<"string="<<wpm1->GetString()<<endl;
return 0;
}
Here Output is : ( which is not expected )
string=Initialized
string=Initialized <------ This is not expected
string=Initialized
Can anybody explain that what is going wrong here. I am running code on
Windows using MSVC compiler
Thanks.
sacgarg
class WithPointerMember
{
char* str;
const size_t size;
public:
WithPointerMember():size(15) //ctor
{
str = new char[size];
strcpy(str, "Initialized");
}
WithPointerMember (const WithPointerMember& other):size(other.size)
//copy ctor
{
str = new char[size];
for(size_t i=0;i<size;i++)
str= other.str;
}
char* GetString(void) const
{
return str;
}
~WithPointerMember() //dtor
{
delete [] str;
}
};
Now In main function first I do like
int main(void)
{
WithPointerMember wpm;
WithPointerMember wpm1 = wpm; <---------- Initializing wpm1 from wpm
cout<<"string="<<wpm.GetString()<<"\n";
wpm.~WithPointerMember();
cout<<"string="<<wpm.GetString()<<endl;
cout<<"string="<<wpm1.GetString()<<endl;
return 0;
}
The output is expected :
string=Initialized
string=
string=Initialized
Now I change my main:
int main(void)
{
WithPointerMember wpm;
cout<<"string="<<wpm.GetString()<<"\n";
wpm.~WithPointerMember();
WithPointerMember *wpm1 = new WithPointerMember(); <-------
Initializing wpm1 from new
cout<<"string="<<wpm.GetString()<<endl;
cout<<"string="<<wpm1->GetString()<<endl;
return 0;
}
Here Output is : ( which is not expected )
string=Initialized
string=Initialized <------ This is not expected
string=Initialized
Can anybody explain that what is going wrong here. I am running code on
Windows using MSVC compiler
Thanks.
sacgarg