I am writing this code where the user can input a name and an age. The program should then print out the name and if the age is over 19 or not, it should print out whether that person is an adult or not.
[Input]
Name : Rivf
Age : 20
[Output]
Rivf is adult.
I was just introduced to copy constructors and destructors so I believe there is something wrong with my implementation of them. The code runs and prints out the desired output but then I get the following error:
Makefile:6: recipe for target 'cpp_run' failed
make: *** [cpp_run] Error 134
munmap_chunk(): invalid pointer
Aborted (core dumped)
I would greatly appreciate some help with this since I am just starting to learn about constructors and these other tools that come with classes. Since this is an assignment I cannot change anything in the class person. Here is my code:
#include <iostream>
#include <string>
using namespace std;
class person{
private:
string name;
int* age;
bool adult;
public:
person();
person(const person& other);
void setName(string n);
string getName();
void setAge(int a);
bool isAdult();
~person();
};
// (1) Implement class functions with constructor
person::person(){
}
void person::setName(string n){
name = n;
}
void person::setAge(int a){
age = new int;
*age = a;
}
person::person( const person& other){
this->name = other.name;
this->age = other.age;
this->adult = other.adult;
}
person::~person(){
delete(age);
}
string person::getName(){
return name;
}
bool person::isAdult(){
if(*age > 19){
adult = true;
}
else{
adult = false;
}
return adult;
}
int main()
{
// (2) make 'defultP' and 'newP' object
person defaultP;
person newP = defaultP;
string name; int age;
cout<<"Name : "; getline(cin, name);
cout<<"Age : "; cin>>age;
defaultP.setName(name);
defaultP.setAge(age);
// (3) print values with member functions of new object
cout<<defaultP.getName();
if(defaultP.isAdult() == true){
cout << " is adult." << endl;
}
else{
cout << " is kid." << endl;
}
return 0;
}