I have a project I’m working on that’s actually a school project that I did successfully a long time ago. I haven’t done C++ in a while, and I’m having a bit of a problem jumping back into it, especially with pointers. My question is, if I need a get and set function like this
class Student
{
private:
char firstName[64];
char lastName[64];
public:
void setName(char *fName, char *lName);
void getName(char *fName, char *lName);
}
void Student::setName(char *fName, char *lName);
{
firstName = *fName;
lastName = *lName;
}
when try to make my getName function, I seem to be very confused as to how I’m supposed to return the names with the function returning void. I know that it doesn’t really have to return it, if it sets a value to something that can be returned, but I guess i’m rusty enough with pointers that I can’t seem to make this work. I’ve tried things that I think can’t work, such as returning values, but i’m not sure what would go in this get function.
void Student::getName(char *fName, char *lName);
{
}
int main()
{
char myFirstName[64] = "John"
char myLastName[64] = "Doe"
//testing to see if it's reading the char arrays correctly.
cout << "Your Name is:" << myFirstName << " " << myLastName << endl;
Student aStudent;
aStudent.setName(myFirstName, myLastName);
//This part is where i'm confused. and i'm sure some above is confusing as well.
getStudent = aStudent.getName();
}
I thought maybe I could return the private variable via the constructor, but why would I need a get function then? I’m just redoing this old assignment to get back into c++, I’ve been doing more network admin stuff, and ignored this for long enough to lose my mind apparently. Thanks in advance, and let me know if you need more information, I tried to be thorough.
I would suggest you to use std::string instead of char arrays.
So, your getName function should look like:
Using pointers and returning void can be done too, but is more difficult. Before calling the getName function, you have to allocate an array to keep the string. you code should look like:
And your getName should look like:
First option is your way to go.