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.
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.
#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;
}
Comments
Leave a comment