The problem with your code is quite simple, for that matter. In your constructor:
xxx :: xxx()
{
a=new char*;
*a="10";
cout<<endl<<*a; // works fine
cout<<"Enter name:";
cin>>*a; // segmentation fault??
}
You are trying to read into an already initialized string literal, which is then causing Undefined Behavior. If you want to do something like this, and you are using C++, you should probably switch to std::string
, which will make your code a lot simpler without dealing with raw string literals and pointers, as follows:
#include <iostream>
#include <string>
class xxx
{
public:
std::string a;
xxx();
~xxx();
};
xxx :: xxx()
{
a = "10";
std::cout << std::endl << a;
std::cout << "Enter name:";
std::cin >> a;
}
int main()
{
xxx x;
std::cout<< x.a;
}
In this example, code such as a=new char*;
and delete a;
are removed along with the destructor itself. Other changes I made include changing your code to not using using namespace std;
(Read why it is considered bad practice) and using the return type of int
for main()
. Additionally, I included the <string>
library as well for std::string
. Finally, as another recommendation, since std::cin
will only read the first word passed to it and ignore the rest, if you want to read a full name then you can use getline()
as follows:
//std::cin >> a; becomes...
getline(std::cin, a);