I was trying following code in which I defined copy c'tor explicitly to solve aliasing problem.
But code is giving runtime error.
#include<iostream>
#include<cstring>
using namespace std;
class word
{
public:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
word(const word &w)
{
char *temp=new char[strlen(w.str)+1];
strcpy(temp,w.str);
str=temp;
cnt=strlen(str);
}
~word()
{
delete []str;
cout<<"destructor called"<<endl;
}
friend ostream& operator<<(ostream &os,const word &w);
private:
int cnt;
char *str;
};
ostream& operator<<(ostream &os,const word &w)
{
os<<w.str<<" "<<w.cnt;
return os;
}
word noun("happy");
void foo()
{
word verb=noun;
cout<<"inside foo()"<<endl;
cout<<"noun : "<<noun<<endl<<"verb : "<<verb<<endl;
}
int main()
{
cout<<"before foo()"<<endl<<"noun : "<<noun<<endl;
foo();
cout<<"after foo()"<<endl<<"noun : "<<noun<<endl;
return 0;
}