#include <iostream>
#include <string>
using namespace std;
class student
{
public:
string name;
int *id;
student(string a, int b)
: name{a}, id{new int{b}}
{
cout << "Default constructor called.\n";
}
student(const student &obj)
: name{obj.name}, id{new int{*obj.id}}
{
cout << "Copy constructor called.\n";
}
};
int main()
{
student student1("Ahmad", 56);
cout<<student1.name<<endl;
cout<<*student1.id<<endl;
cout<<"========\n";
student student2 = student1;
cout<<student2.name<<endl;
cout<<*student2.id<<endl;
cout<<"========\n";
student1.name="Kamel";
*student1.id = 12;
cout<<student2.name<<endl;
cout<<*student2.id<<endl;
cout<<"========\n";
cout<<student1.name<<endl;
cout<<*student1.id<<endl;
}
Better solution just is using regular int.
Why do you need pointers and new?That's the the reason your code leaks memory now
Igor🇺🇦
Hanz
ASV
nelnel
Gulnar
Pavel
𝙑𝙚𝙙𝙖𝙣𝙩
Global Hub Educational consultancy
Aakash
H
Generation Z
klimi
Vlad