Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

needs to be writtne in C++ Problem Create class Person and demonstrate its capab

ID: 3663345 • Letter: N

Question

needs to be writtne in C++

Problem

Create class Person and demonstrate its capability.

Specification

Given Person (refer to code below)

Add a parametrized constructor that uses an initializer list for name and validates age >0

Create Person.cpp that implements the functionality of Person.h

Create PersonTest.cpp that demonstrates the features of class Person

GIVEN CODE

#include <iostream>
#include<string>

using namespace std;

class Person
{
public:
Person();
string getName();
int getAge();
void setName(string newName);
void setAge(int newAge);
void display();

private:
string name;
int age;
};

Explanation / Answer

/*
* Person.h
*
* Created on: Jan 26, 2016
*      Author: Ravi
*/

#ifndef PERSON_H_
#define PERSON_H_

#include <iostream>
#include<string>

using namespace std;

class Person {
private:
   string name;
   int age;
public:
   Person();
   Person(string name, int age);
   string getName();
   int getAge();
   void setName(string newName);
   void setAge(int newAge);
   void display();

   virtual ~Person();
};

#endif /* PERSON_H_ */

/*
* Person.cpp
*
* Created on: Jan 26, 2016
*      Author: Ravi
*/

#include "Person.h"

Person::Person() {
   // TODO Auto-generated constructor stub
   name = "";
   age = 10; //change default age

}

Person::Person(string pname, int page) {
   // TODO Auto-generated constructor stub
   name = pname;
   if(page > 0)
       age = page;
   else
       cout << "You entered: " << age <<" Age should be greater than zero years" <<endl;

}

string Person::getName() {
   return name;
}

void Person::setName(string newName) {
   name = newName;
}


int Person::getAge() {
   return age;
}

void Person::setAge(int newAge) {
   if(newAge > 0)
       age = newAge;
   else
       cout << "You entered: " << age <<" Age should be greater than zero years" <<endl;
}

void Person::display() {
   cout << "Name: " <<name<< "   Age: "<<age <<endl;
}

Person::~Person() {
   // TODO Auto-generated destructor stub
}

int main()
{
   Person p1;
   p1.display();

   Person p2 = Person("John", 0);
   p2.setAge(20);
   p2.display();
   Person p3 = Person("Kerry",20);
   p3.setAge(0);
   p3.display();
   return 0;
}

---output---

Name:    Age: 10
You entered: 2000325845 Age should be greater than zero years
Name: John   Age: 20
You entered: 20 Age should be greater than zero years
Name: Kerry   Age: 20