Converting C to C++ and Dynamic Memory Allocation - c++

So I have recently been tasked with converting a program I wrote in C to C++ for an assignment in an intro to programming course. The program was a basic database program where the user would create a grade book with student IDs, text names, course IDs, text names, and grades. The user would be able to interact with the menu and perform a number of operations. The most important thing was that the program could reallocate more memory when needed and it would do this automatically. So now, I'm trying to convert this program to C++.
We began discussing C++ about two and a half weeks ago in class so I am fairly new to the language. I have given a snippet for the program and what I have done so y'all can better understand my issue. I've included the class for Course and only two functions (the first adds course IDs and text name and the second prints a full list of the courses). I want the bound to start at 25, and if the user wants to put in more courses past this bound, the program will allocate more memory and copy the old entries into the new space. I'm not sure if I don't understand constructors still or what, but whenever the user inputs the 26th course it doesn't get saved. And if I try to print the courses when this happens, I get a segmentation fault.
If anyone can spot what I did wrong I would greatly appreciate it. If there's anything I didn't make clear, let me know and I'll reply as soon as I can. Thank y'all for taking the time to look at my program.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
const int MAX_COURSES=25;
//Class
class Course
{
//Two private member variables
private:
string courseText;
int courseID;
public:
//Constructor
Course(void);
//Member functions
static void addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
static void printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
};
//Class implementation
//Constructor
Course::Course(void)
{
//Just providing initial value to the two object variables
courseText;
courseID=-1;
}
//This function isn't a part of any class and will print the grade book menu.
void printMenu()
{
cout << endl;
cout << "GRADE BOOK MENU" << endl;
cout << "1. Add a new course" << endl;
cout << "2. Add a new student" << endl;
cout << "3. Add a student to a course" << endl;
cout << "4. Add grades for a student in a course" << endl;
cout << "5. Print a list of all grades for a student in a course" << endl;
cout << "6. Print a list of all students in a course" << endl;
cout << "7. Compute the average for a student in a course" << endl;
cout << "8. Print a list of all courses" << endl;
cout << "9. Print a list of all students" << endl;
cout << "10. Compute the average for a course" << endl;
cout << "11. Store grade book (to a disk file" << endl;
cout << "12. Load grade book (from a disk file" << endl;
cout << "13. Quit the program" << endl;
cout << "14. Check individual student 2D grade matrix" << endl;
cout << endl;
}
//This method function will add a course to the course list
void Course::addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
int userEnteredCourseID=0;
Course* pointerCourses=NULL;
pointerCourses = courses;
do
{
cout << endl;
cout << "Please enter a course ID number using only integers." << endl;
cout << "There is a limit of only 25 courses allowed in the grade book." << endl;
cout << "To exit to grade book menu at any time, enter a negative integer or 0." << endl;
cout << "A message will be returned to you and no course IDs will be added." << endl;
cin >> userEnteredCourseID;
//Checking for a valid integer input.
while(cin.fail())
{
cout << "Error! User entered something other than an integer." << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Try entering a valid integer input this time..." << endl;
cin >> userEnteredCourseID;
}
cout << "You have entered the integer " << userEnteredCourseID << endl;
/*Checking if they entered a negative integer value.*/
if(userEnteredCourseID<=0)
{
cout << endl;
cout << "You have entered a negative integer or 0. Nothing has been added" << endl;
cout << "to the course list and you will be returned to the menu." << endl;
}
/*A valid integer was entered.*/
else
{
/*Now need to check if the course has been entered before. Should be noted, only
course ID numbers will be checked, not text names. Two course IDs could exist for
the same course; these ID numbers could represent different times for the same
course.*/
int j;
for(j=0; j<MAX_COURSES+(*timesReallocatedCoursesCounter); j++)
{
/*Checks if user has entered that course ID before.*/
if(courses[j].courseID==userEnteredCourseID)
{
cout << "You've already entered that course ID!" << endl;
userEnteredCourseID=0;
break;
}
/*If the current element doesn't equal the course ID entered, keep traversing the array.*/
else if(courses[j].courseID!=userEnteredCourseID && j<=((MAX_COURSES + (*timesReallocatedCoursesCounter))-2))
{
continue;
}
/*Entire loop was traversed and there weren't any duplicate course IDs, so a new course will be added to array.*/
else
{
//Since the previous bounds for courses used to be 25, we'll leave that part of the code in.
//However, since we now want to allow for infinite inputs, if the user reaches 25
//courses, the program will reallocate memory and allow for more courses to be entered.
//Only memory space for one course will be allocated each time so space isn't wasted.
if(*courseCounter==(MAX_COURSES + (*timesReallocatedCoursesCounter)))
{
courses = new Course[MAX_COURSES + *timesReallocatedCoursesCounter + 1];
for(int m=0; m < MAX_COURSES + *timesReallocatedCoursesCounter; m++)
{
courses[m] = pointerCourses[m];
}
delete[] pointerCourses;
*timesReallocatedCoursesCounter+=1;
courses[*courseCounter].courseID=userEnteredCourseID;
cout << "What would you like the new course to be called?" << endl;
cin.ignore();
getline(cin, courses[*courseCounter].courseText);
cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
*courseCounter+=1;
cout << "Press enter to continue." << endl;
cin.ignore();
}
else
{
courses[*courseCounter].courseID=userEnteredCourseID;
cout << "What would you like the new course to be called?" << endl;
cin.ignore();
getline(cin, courses[*courseCounter].courseText);
cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
*courseCounter+=1;
cout << "Press enter to continue." << endl;
cin.ignore();
}
}
}
}
}while(userEnteredCourseID>0);
}
//This method function prints the courses that have been successfully entered by the user.
void Course::printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
if(*courseCounter==0)
{
cout << endl;
cout << "You haven't entered any course IDs successfully yet!" << endl;
}
else
{
int i;
cout << endl;
cout << *courseCounter << " course(s) successfully entered so far." << endl;
cout << "The gradebook started with allowing only 25 courses to be entered." << endl;
cout << "Due to the amount of courses entered by the user, memory has been reallocated" << endl;
cout << *timesReallocatedCoursesCounter << " time(s) (in increments of 1) so entries could be made." << endl;
cout << "This means, a maximum of " << MAX_COURSES+*timesReallocatedCoursesCounter << " courses can be entered before reallocation is needed." << endl;
cout << "The list of the courses entered so far are:" << endl;
for(i=0;i<*courseCounter;i++)
{
cout << endl;
cout << courses[i].courseID << ": " << courses[i].courseText;
}
cout << endl;
}
}
//Main program file.
int main(void)
{
Course *courses;
courses = new Course [MAX_COURSES];
int userInput;
int courseCounter = 0;
int timesReallocatedCoursesCounter = 0;
do
{
/*Function that will re-print grade book menu.*/
printMenu();
cout << "What would you like to do with the menu?" << endl;
cin >> userInput;
while(cin.fail())
{
cout << "Error! User entered something other than an integer." << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Try entering a valid integer input this time..." << endl;
cin >> userInput;
}
cout << "You have entered the integer " << userInput << endl;
if(userInput==1)
{
cout << "You want to add a new course." << endl;
Course::addCourse(courses, &courseCounter, &timesReallocatedCoursesCounter);
}
else if(userInput==2)
{
cout << "You want to add a new student." << endl;
}
else if(userInput==3)
{
cout << "You want to add a student to a course." << endl;
}
else if(userInput==4)
{
cout << "You want to add a grade for a student in a course." << endl;
}
else if(userInput==5)
{
cout << "You want to print the grades for a student in a course." << endl;
}
else if(userInput==6)
{
cout << "You want to print a list of students in a course." << endl;
}
else if(userInput==7)
{
cout << "You want to compute the average for a student in a course." << endl;
}
else if(userInput==8)
{
cout << "You want to print a list of all courses." << endl;
Course::printCourses(courses, &courseCounter, &timesReallocatedCoursesCounter);
}
else if(userInput==9)
{
cout << "You want to print a list of all students." << endl;
}
else if(userInput==10)
{
cout << "You want to compute the average for a course." << endl;
}
else if(userInput==11)
{
cout << "You want to store the grade book you've been working on to a text file." << endl;
}
else if(userInput==12)
{
cout << "You want to load a grade book you've worked on previously from a text file." << endl;
}
else if(userInput==13)
{
cout << "You want to quit the program." << endl;
cout << "Goodbye, and thank you for using this program!" << endl;
}
else if(userInput==14)
{
cout << "An optional menu function that prints an individual student's 2D array." << endl;
cout << "This array contains all the course IDs for which the student is enrolled on the top row." << endl;
cout << "The rows below the course IDs correspond to grades made by the student in each course." << endl;
}
else
{
cout << "User entered an integer value that doesn't correspond to any menu option." << endl;
cout << "Nothing will happen." << endl;
}
}while(userInput!=13);
delete[] courses;
return 0;
}

but whenever the user inputs the 26th
Maybe because of this:
const int MAX_COURSES=25;
//...
Course *courses;
courses = new Course [MAX_COURSES]
You allocated room for 25 students, not 26. However, this issue would have occurred if you just used arrays:
Course courses[MAX_COURSES];
With an array you may have crashed, but the issue is the same -- a memory overwrite. So either decide -- limit the user to 25 students, or allow any number of students. If it's the latter, then you need to use a dynamic array.
The most important thing was that the program could reallocate more memory when needed and it would do this automatically. So now, I'm trying to convert this program to C++.
If you do with the dynamic array, it would have been advantageous to learn to use std::vector instead of using new[]/delete[]. That is the way dynamic arrays are done using C++. If you instead stick with new[]/delete[] to attempt to resize, all I can tell you is "good luck". I can almost bet you will come back with more issues if you choose the new[]/delete[] path.
The way the vector approach would look is something like this:
#include <vector>
//...
typedef std::vector<Course> CourseVector;
//...
void addCourse(CourseVector& v)
{
Course tempCourse;
// gather all the user information in tempCourse
//...
// now add the course to the array
v.push_back(tempCourse);
}
It took a single line of code to add a course to the vector. A vector is nothing more than a wrapper around a dynamic array. It basically does new[]/delete[] but with one huge advantage - it uses these operations correctly. You never need to get your hands dirty doing this work and making mistakes. The vector knows when to allocate, when to destroy, etc. All you need to do is call the functions to resize(), push_back(), etc.

I think your issue is that you are passing in the courses pointer by value. That is, a new copy of courses is created on the call stack, and you are operating on that copy. The copy is lost after addCourse() is executed. So for the first 25 courses that you add, your program works as normal since the copy of the courses pointer points to the same memory block as the "original". When you try to dynamically increase the size of courses by allocating a new block of larger memory, you are not doing anything to the original pointer in main(). This is why I think you are segfaulting when you print out the list.
A possible solution is to have addCourse() return the larger array, set it to courses in main(), and then deallocate the old array.
The prototype for the new addCourse() function would look like this:
static Course* addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
Inside the function allocate the larger array using a new Course pointer, and copy the values one by one into the new array. Then, return the new array.
and to call it, use a statement like:
Course* newCourses = addCourse(...);
delete [] courses;
courses = newCourses;

Related

Selecting an array value using a random number generator

its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.

If variable equal to 0

Then it will reset to the questions number 1.
I wanted to implement health points system in my code, so that if your hp goes to 0 (zero) when choosing the wrong answer, it will start to question number 1
I'm new to c++ and doesn't know much about it but if you have any recommendation how to improve my coding i'm happy to take your advice.
Code:
void questions()
{
int score, end, hp = 1;
char ans[28];
cout <<"\t\tHEALTH POINTS= " << hp <<"\n\n";
cout << "1.What thing has to be broken before it can be used?\n\n"; //Questions
cout << "[A]-Egg,";
cout << " [B]-Heart,"; //Choices
cout << " [C]-Cube,";
cout << " [D]-Case";
cout << "\n\n";
cout << "YOUR ANSWER IS: ";
cin >> ans[1];
if (ans[1]=='a'||ans[1]=='A') //This will decide if the input is correct
{
cout << "YOUR ANSWER IS CORRECT: [A] - Egg \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "2.Jimmy's mother had three children. The first was called April, \nthe second was called May. What was the name of the third?\n";
cout << "[A]-May,";
cout << " [B]-Jimmy,";
cout << " [C]-April,";
cout << " [D]-Third";
cout << "\n\n";
cout << "Your Answer is: ";
cin >> ans[2];
if (ans[2]=='b'||ans[2]=='B')
{
cout << "YOUR ANSWER IS CORRECT: [B] - Jimmy \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "\n\t\t YOUR SCORE IS:" << score << "/2, ";
cout <<"YOU HAVE "<< hp <<" HP LEFT\n\n";
cout << endl;
cout <<"\n\t\t PRESS ANY KEY TO GO BACK TO CHOICES...";
getch(); //Holds the screen
system("cls");
questions();
One way to improve your approach might be implementing some sort of function to handle asking a question, with predefined choices, and getting an answer back. Instead of writing the code out twice like you do above to ask two questions, you could call the same function twice, passing in the different arguments.

Need help on getting into a function in C++

Here is the sample of my code:
//Function Declarations
void askChampSearch(string&, string&);
void displayChampDetail(string);
int main()
{
string searchedChamp;
string aboutUser;
cout << "**********YOU'RE GOING TO WANT TO MAKE YOUR PROMPT FULL SCREEN**********" << endl;
cout << "Welcome to my LEAGUE OF LEGENDS info guide!" << endl;
cout << "You can search any champion in League of Legends, and all" << endl;
cout << "of that champions information will be displayed.The information" << endl;
cout << "that will be displayed is: Abilites, Champion Lore, About The Campion, Best Build, and the Champions Wiki Page!" << endl;
cout << endl;
askChampSearch(aboutUser, searchedChamp);
displayChampDetail(searchedChamp);
return 0;
}
//Function Definitions
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
cin >> UserName;
cout << "Hi " << UserName << ", nice to meet you!" << endl;
cout << endl;
cout << "What League of Legends champion would you like to search? ";
cin >> searchedChamp;
cout << "The champion that you have searched for was " << searchedChamp << "!";
}
void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
cout << "Ahri is a nine-tailed fox who is a whore" << endl;
cout << "If Ahri hits you with a charm, you are fucked" << endl;
}
}
What I am having problems with is after my program leaves the first void:
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
cin >> UserName;
cout << "Hi " << UserName << ", nice to meet you!" << endl;
cout << endl;
cout << "What League of Legends champion would you like to search? ";
cin >> searchedChamp;
cout << "The champion that you have searched for was " << searchedChamp << "!";
}
It won't enter into the next one! For example. If the user types the Name Ahri it should display what I have done, but it says I need to define Ahri. How do I define Ahri within the second Void. Here is the code for my second Void:
void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
cout << "Ahri is a nine-tailed fox" << endl;
cout << "If Ahri hits you with a charm, you are dead" << endl;
}
}
What I am trying to do is, if the user types the name Ahri, it the information that I have provided.
The error code that I am getting is identifier "Ahri" is undefined.
searchedChamp == "Ahri"
It is a string. Other wise compiler tries to find a variable with name "Ahri"and it doesn't find it so it asks you to define it.

Program not saving inputted entries? (C++) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am supposed to make a class AddressBook containing a class called Person. My program almost, works, except when I add a person, it doesn't remember it in the next iteration of the Command menu and Display All turns up "There are 0 people in your address book." What is wrong with my code?
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
class Person
{
public:
char firstName[15];
char lastName[15];
char personID[15];
};
Person entries[100];
unsigned int total;
AddressBook()
{
total = 0;
}
void AddPerson()
{
cout << "This is entry number " << (total + 1) << " in your address book. " << endl;
cout << "What shall we put for the first and last name? Limit both to under 15 characters. Example: Bob Smith" << endl;
cin >> entries[total].firstName >> entries[total].lastName;
cout << "What is " << entries[total].firstName << " " << entries[total].lastName << "'s ID code?" << endl;
cin >> entries[total].personID;
++total;
cout << "..." << endl << "Successfully Added." << endl;
};
void DisplayPerson(int i)
{
cout << "Entry " << i + 1 << ": " << endl;
cout << "FIRST NAME: " << entries[i].firstName << endl;
cout << "LAST NAME: " << entries[i].lastName << endl;
cout << "ID: " << entries[i].personID << endl;
};
void DisplayEveryone()
{
cout << "You have " << total << " People in your address book." << endl;
for (int i = 0; i < total; ++i)
DisplayPerson(i);
};
void SearchPerson()
{
char lastname[32];
cout << "Please enter the last name of the person you wish to find." << endl;
cin >> lastname;
for (int i = 0; i < total; ++i)
{
if (strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Person Found. " << endl;
DisplayPerson(i);
cout << endl;
}
}
};
};
int main() {
char command;
bool Exit = false;
while (Exit == false)
{
AddressBook Address_Book;
cout << "---------------COMMANDS---------------" << endl;
cout << "A: Add Person To Address Book" << endl;
cout << "S: Search for Person in Address Book" << endl;
cout << "D: Display Everyone In Address Book" << endl << endl;
cout << "Type the letter of your command: ";
cin >> command;
cout << endl;
switch (command) {
case 'A':
case 'a':
Address_Book.AddPerson();
break;
case 'S':
case 's':
Address_Book.SearchPerson();
break;
case 'D':
case 'd':
Address_Book.DisplayEveryone();
break;
default:
cout << "That is not a valid command. Closing Address Book." << endl;
cout << endl;
}
}
}
The reason is that you create a new address book in each iteration of the while loop and throw it away at the end of the iteration:
This
AddressBook Address_Book;
creates a new address book that is "thrown away" when you reach the end of its scope (ie. the end of the loop).
In reality, do you buy a new address book whenever you want to make new entry? No. You first buy the book and then (possibly in a while loop) you add entries. Move the above line outside of the loop.
Your problem is in the declaration of your address book.
Change it to the following:
AddressBook Address_Book;
while (Exit == false) {
//Ask for input and respond.
}
In your version Address_Book is declared at the start of the while loop. This means that every time an iteration of the loop completes and execution returns to the start of the block, a new local Address_Book object is created that has no knowledge of the previous objects data.

Creating new "dynamic" objects?

What is the best way of creating dynamic (not sure if this is the correct word) objects? For example, if I run the following:
Person man[10];
cout << "MENU" << endl;
cout << "1. Add a person to the list" << endl;
cout << "2. Delete a person from the list" << endl;
cout << "3. Change a person's information'" << endl;
cout << "4. Locate a person by ID number" << endl;
cout << "5. Locate a person by last name" << endl;
cout << "6. Print the list on the screen" << endl;
cout << "7. Load the list from a file" << endl;
cout << "8. Save the list to a file" << endl;
cout << "9. Exit the program" << endl;
cin >> a;
if (a == 1) {
if (i <= 10) {
Person man[i];
cout << "Please enter your last name: " ;
cin >> last;
man[i].setLastName(last);
i++;
cout << man[i].getLastName();
}
}
When I run this, I am allowed to enter my last name, but when I press ENTER the program stops running. What is the reason for this and is there a better way to create these objects "profiles"?
Thank you and I'm sorry if this is a stupid question.
The reason is your entire program only take one input cin >> a; and then check if its equal to 1. After the block the program has nothing left to do. So your program terminated.
If you want to edit all first name and last name of your 10 Person obj, you'd better create a loop to do that. For loop, you can google for / while.
Heres a example:
int i;
while(cin >> i)
{
if(i == 9)
return;
else if[....]
}
When you say dynamic, object allocation is via new operator. In your code, the array is already declared with 10 elements(static allocation). Hence in you code you are not performing dynamic allocation.
For dynamic allocation,add a function which can return you a new Person object. In this function create a object using new operator and return this object.
This way you add new objects dynamically.
Refer to new operator for more details on dynamic allocation.