May 27, 2020 at 8:28am UTC
Hello,
I want to implement a simple OOP program.
Could you please check my program? I use a good solution?
I don't want to use a virtual function.
Is this a good solution I call to read and display method in canderDisplay and cancerRead?
Thank you
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#include <iostream>
#include<string>
using namespace std;
class Person
{
private :
string name;
string family;
int age;
string sex;
int id_number;
public :
void Read()
{
cout << "Name: " ;
getline(cin,name);
cout << "Family: " ;
getline(cin, family);
cout << "Sex: " ;
getline(cin, sex);
cout << "Age: " ;
cin >> age;
cout << "ID Number: " ;
cin >> id_number;
}
void Display()
{
cout << "Name: " << name << endl;
cout << "Family: " <<family << endl;
cout << "Sex: " << sex << endl;
cout << "Age: " << age << endl;
cout << "ID Number: " << id_number << endl;
}
};
class Cancer : public Person
{
private :
int r;
string position;
public :
void CancerRead()
{
Read();
cout << "Position: " ;
cin.ignore(1000,'\n' );
getline(cin,position);
cout << "Radius: " ;
cin >> r;
}
void CancerDisplay()
{
Display();
cout << "Area is: " << Area()<<endl;
cout << "Perimeter is: " << Perimeter() << endl;
cout << "Position is: " << position << endl;
}
double Area()
{
return 3.14 * r * r;
}
double Perimeter()
{
return 2 * 3.14 * r;
}
};
int main()
{
Cancer c;
c.CancerRead();
c.CancerDisplay();
return 0;
}
Last edited on May 27, 2020 at 9:35am UTC
May 27, 2020 at 8:41am UTC
Thank you for your reply,
It means someone who has cancer.
Is this a good solution I call read and display methods in canderDisplay and cancerRead?
May 27, 2020 at 10:24am UTC
Then you shouldn't structure the program in this way. Inheritance models an is-a relationship. Cancer is not a person. A person can HAVE cancer. You could have a Person class with a private cancer member
May 27, 2020 at 3:00pm UTC
Better to create a class Patient that inherits from Person and has a has_cancer attribute