Answer to Question #309074 in C++ for Rajat Vats

Question #309074

Define an abstract class Human comprising the following members- name and age (with appropriate data types, a parameterized constructor and a pure virtual function printDetails().

The program also defines two concrete classes- Adult and Child inheriting publicly from the class Human.

Class Adult has a data member- voterID (with appropriate data type).

Class Child has a data member- schoolName (with appropriate data type).

Define parameterized constructors for both the classes Adult and Child. The constructors should also have following validation check for the age input.

  • The age of an adult should be more than or equal to 18 years.
  • The age of a child should be in the range 0 to 18 (excluding both numbers).

Override printDetails() function for both the derived classes.

Define main() function to declare one object each for classes Adult and Child respectively and print the details of the objects. 


1
Expert's answer
2022-03-13T08:09:38-0400
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;


class Human {
public:
    Human(string name, unsigned age) {
        this->name = name;
        this->age = age;
    }
    virtual void printDetails()=0;


protected:
    string name;
    unsigned age;
};



class Adult : public Human {
public:
    Adult(string name, unsigned age, unsigned voterID);
    void printDetails();


protected:
    unsigned voterID;
};


class Child : public Human {
public:
    Child(string name, unsigned age, string schoolName);
    void printDetails();


protected:
    string schoolName;
};


Adult::Adult(string name, unsigned age, unsigned voterID)
: Human(name, age)
{
    if (age < 18) {
        cerr << "Error creating Adult. Age must be >= 18";
        exit(1);
    }
    this->voterID = voterID;
}


void Adult::printDetails() {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "VoterID: " << voterID << endl;
}


Child::Child(string name, unsigned age, string schoolName)
: Human(name, age)
{
    if (age == 0 || age >= 18) {
        cerr << "Error creating Child. Age must be < 18";
        exit(1);
    }
    this->schoolName = schoolName;
}


void Child::printDetails() {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "School name: " << schoolName << endl;
}


int main() {
    Adult john("John Snow",  28, 123456789);
    Child alice("Alice Liddell", 8, "White Rabbit");


    john.printDetails();
    cout << endl;
    alice.printDetails();


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog