I'm trying to create constructor taking reference to an object. After creating object using reference I need to prints field values of both objects. Then I must delete first object, and once again show values of fields of both objects. My class Person looks like this :
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
~Person(){
cout << "Destroying resources" << endl;
delete[] name;
delete age;
}
void init(char* n, int a) {
name = n;
age = a;
}
};
Here's my implementation (with the use of function show() ). My professor said that if this task is written correctly it will return an error.
#include <iostream>
using namespace std;
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
Person(const Person& p){
name = p.name;
age = p.age;
}
~Person(){
cout << "Destroying resources" << endl;
delete[] name;
delete age;
}
void init(char* n, int a) {
name = n;
age = a;
}
void show(char* n, int a){
cout << "Name: " << name << "," << "age: " << age << "," << endl;
}
};
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
p->show();
Person &p = pRef;
pRef->name = "Tom";
pRef->age = 18;
Person *p2 = new Person(pRef);
p->show();
p2->show();
system("PAUSE");
return 0;
}