Ok, so i know this is kind of basic, but i can't understand what i'm doing wrong here. this is the class:
class numar_complex {
friend std::ostream& operator<<(std::ostream& out, const numar_complex& numar_complex);
friend std::istream& operator>>(std::istream& is, numar_complex& numar_complex);
private:
double* p_real;
double* p_imaginar;
public:
//constructor, destructor:
numar_complex()
{
double* p_real{ new double(0.0) };
double* p_imaginar{ new double(0.0) };
cout << "constructor" << endl;
}
numar_complex(const numar_complex& nr)
{
if (p_real != nullptr) {
p_real = nullptr;
delete p_real;
}
p_real = new double(*nr.p_real);
if (p_imaginar != nullptr) {
p_imaginar = nullptr;
delete p_imaginar;
}
p_imaginar = new double(*nr.p_imaginar);
cout << "copy constructor " << endl;
}
~numar_complex()
{
p_real = nullptr;
delete p_real;
p_imaginar = nullptr;
delete p_imaginar;
cout << "destructor" << endl;
}
// getteri:
double get_p_real()
{
return *p_real;
}
double get_p_imaginar()
{
return *p_imaginar;
}
//setteri:
void set_p_real(double x)
{
p_real = nullptr;
delete p_real;
p_real = new double(x);
}
void set_p_imaginar(double x)
{
p_imaginar = nullptr;
delete p_imaginar;
p_imaginar = new double(x);
}
std::ostream& operator<<(std::ostream& out, const numar_complex& numar_complex)
{
if (*numar_complex.p_imaginar >= 0) {
out << *numar_complex.p_real << "+" << *numar_complex.p_imaginar << "*i \n";
}
else if (*numar_complex.p_imaginar < 0) {
out << *numar_complex.p_real << *numar_complex.p_imaginar << "*i \n";
}
return out;
}
and for some reason, when i simply declare an object of this class, as
numar complex x;
cout << x;
it crashes (memory problem); however, if i use the setters/getters, the problem doesn't appear anymore. in the case of
numar complex x;
x.set_p_real(1);
x.set_p_imaginar(1);
cout << x;
will result in 1 + 1i;
PS: If i don't use the setters to initialize values, the getters will also result in a crash.
doubles the shown code will be half its current size. No need to have a copy constructor. No need to have an assignment operator (one was missing). No opportunities for making simple bugs, like attempting to delete a null pointer. This kind of a bug is called "pointless use of pointers".