Тема: C++ Конструктор копіювання
Код ніби написав робочий, але вилітає помилка "Exception thrown: read access violation. this->data1 was nullptr.".
#include <iostream>
using namespace std;
class Myclass
{
public:
int *data1;
int data2;
public:
int SIZE;
Myclass (int size)
{
; data1 = new int [size];
data2 = size;
for (int i = 0; i < size; i++)
{
data1[i] = size;
}
cout << "Constructor = " << "data1 = " << *data1 << " " << "data2 = " << data2 << endl;
}
Myclass() = default;
~Myclass()
{
cout << "Destructor = " << "data1 = " << *data1 << " " << "data2 = " << data2 << endl;
delete[] data1, data2;
}
Myclass(Myclass const& other)
{
data1 = new int [other.data2];
for (int i = 0; i < other.data2; i++)
{
data2 = other.data1[i];
*data1 = other.data1[i];
}
cout << "Copy-Constructor = " << "data1 = " << *data1 << " " << "data2 = " << data2 << endl;
}
int Input(int a=1)
{
a = SIZE;
cin >> SIZE;
return SIZE;
}
};
Myclass* Obj;
class Pohidniy :public Myclass
{
public:
Pohidniy(int a=0, int b=0)
{
a = *data1; b = data2;
cout << "Class Pohidniy = " << "data1 = " << *data1 << " " << "data2 = " << data2 << endl;
}
int Dodavanya(int a, int b)
{
a = *data1; b = data2;
int result;
result = a + b;
cout << "The result of Dodavanya is " << result << endl;
return result;
}
int Vidnimanya(int a, int b)
{
a = *data1; b = data2;
int result;
result = a - b;
cout << "The result of Vidnimanya is " << result << endl;
return result;
}
int Mnojenya(int a, int b)
{
a = *data1; b = data2;
int result;
result = a * b;
cout << "The result of Mnojenya is " << result << endl;
return result;
}
void Check(int a=1, int b=1)
{
a = *data1; b = data2;
cout << "What do you want to do?" << endl << "1) Dodavanya" << endl <<
"2) Vidnimanya" << endl << "3) Mnojenya" << endl;
char check;
do
{
cin >> check;
} while (check != '1' && check != '2' && check != '3');
if (check == '1')
{
Dodavanya(*data1, data2);
}
else if (check == '2')
{
Vidnimanya(*data1, data2);
}
else
{
Mnojenya(*data1, data2);
}
}
};
int main()
{
Obj = new Myclass();
Obj->Input();
int a;
a = Obj->SIZE;
Myclass first(a);
Myclass second(first);
/*int a;
cin >> a;
Myclass Obj(a);
Myclass Obj2(Obj);*/
Pohidniy pohidniy(2,3);
pohidniy.Check();
}