Create a person class to represent a person. (You may call the class personType.
ID: 3537760 • Letter: C
Question
Create a person class to represent a person. (You may call the class personType.) To simplify things, have the class have 2 variable members for the person's first and last name. Include 2 constructors. One should be a default constructor and the other should be one with parameters. Include respective functions for:
setting the name,
getting the name, and
printing the name on the screen.
Have your main program call these functions to demonstrate how they work.
Explain how you can replace both constructors with one constructor by using a single constructor with default parameters.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
// class Person
// with two private fields name and age
// two public methods to retrieve fields (called "getters")
// and public non-default constructor
class Person {
public:
Person()
{
}
Person(string name, string lastname) {
this->name = name;
this->lastname= lastname;
}
string getName() {
return name;
}
int getlastname() {
return lastname;
}
string setName(string name) {
this->name = name;
}
int setlastname(string lastname) {
this->lastname= lastname;
}
void printName()
{
count<<name<<" "<<lastname;
}
private:
string name;
string lastname;
};
int main() {
cout << "Creating a person..." << endl;
Person johnDoe("John", "Doe");
cout << "Person's name: " << johnDoe.getName() << endl;
cout << "Person's age: " << johnDoe.getlastname() << endl;
johnDoe.printName();
Person johnSev;
johnSev.setName("john");
johnSev.setlastname("Sev");
johnSev.printName();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.