Cpp some basic problems
        Posted  
        
            by DevAno1
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by DevAno1
        
        
        
        Published on 2010-05-24T23:25:52Z
        Indexed on 
            2010/05/24
            23:31 UTC
        
        
        Read the original article
        Hit count: 370
        
Hello. My task was as follows : Create class Person with char*name and int age. Implement contructor using dynamic allocation of memory for variables, destructor, function init and friend function show. Then transform this class to header and cpp file and implement in other program. Ok so I've almost finished my Person class, but I get error after destructor. First question is how to write this properly ?
#include <iostream>
using namespace std;
class Person {   
    char* name;
    int age;
public:
    int * take_age();   
    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 * take_age();
    }  
    friend void(Person &p);
   int * Person::take_age(){
       return age;
   }
    void init(char* n, int a) {
        name = n;
        age = a;
    }
void show(Person &p){
    cout << "Name: " << p.name << "," << "age: " << p.age << endl; 
}
}; 
int main(void) {
    Person *p = new Person;  
    p->init("Mary", 25);
    p.show();
    system("PAUSE");
    return 0;
}
And now with header/implementation part :
- do I need to introduce constructor in header/implementation files ? If yes - how?
- my show() function is a friendly function. Should I take it into account somehow ?  
I already failed to return this task on my exam, but still I'd like to know how to implement it.
© Stack Overflow or respective owner