Hi all, im wondering if someone could offer a solution to my current problem which is passing and return information using pointer notation.

I have created a small program using the class Person, who has a first and last name and methods to add and retrieve this information which looks as follows:

#ifndef PERSON_H
#define PERSON_H

class Person {
    
    private:
        
        char* firstName;
        
        char* surname;

    public:
        
        Person();

        void addFirstName(char* firstName);
    
        void addSurname(char* surname);

        char* viewFirstName();
    
        char* viewSurname();
};
#endif
#include "Person.hpp"
#include <string>

Person::Person() {
}


void Person::addFirstName(char* firstName){
    strcpy(this->firstName, firstName);
}

void Person::addSurname(char* surname){
    strcpy(this->surname, surname);
}

char* Person::viewFirstName() {
    return firstName;
}

char* Person::viewSurname() {
    return surname;
}

My problem occurs when I retrieve the information back from the object. If i enter the name Jane Doe as firstname and surname,
when I call the methods to get the name back,something like this is returned:

first name: DoeJ

surname: Doe

Here is my test program:

#include "Person.cpp"
#include <iostream>
#define SIZE 100
using namespace std;

main() {
    
    char fname[SIZE];
    char sname[SIZE];
    Person* p = new Person();
    
    
    
    cout << "Enter Person first name: ";
    cin.getline(fname, 100);
    
    cout << "\nEnter Person surname: ";
    cin.getline(sname, 100);
    
    p->addFirstName(fname);
    p->addSurname(sname);
    
    cout << "\nRetrieving details..." << endl;
    
    cout << "Fname: " << p->viewFirstName();
    cout << "Sname: " << p->viewSurname();
}

Thanks in advance for any help.

Instead of using

strcpy(this->firstName, firstName);

use instead

this->firstName = firstName

strcpy is more suited to pass from string to char *

This solved my problem perfectly thanks Jiwe.

My understanding now is that

this->firstname = firstname

is more suited because I am working with pointers which are addresses, so string copy is of no real use?

Exactly. Working with pointers has it's advantages has you only need to know the first element adress to get to the others.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.