Professional Documents
Culture Documents
Method Overriding
Method Overriding
overriding
Program 1
PROBLEM Consider a class Product with data members barcode and name of the
STATEMENT : product. Create the appropriate constructor and write getter methods for the
individual data members. and write two virtual methods, scanner() and
printer().
Derive 2 classes from Product, 1st class is Prepacked Food and 2nd class is
Fresh Food. the Prepacked Food class should contain the unit price and the
Fresh Food class should contain a weight and a price per kilo as data
members.
Override the methods scanner and printer in the derived classes. (These
methods will simply output product data on screen or read the data of a
product from the keyboard depending upon whether it is Prepacked or Fresh
Food)
In main, create a base class pointer and point it to the appropriate derived
class objects to demonstrate runtime polymorphism.
class Product
{
protected:
string barcode;
string name;
public:
virtual void scanner()
{
cout<<"A\n";
}
string get_name()
{
return name;
}
Product()
{
}
};
public:
void scanner()
{
cout<<"\nOf Prepacked Food:"<<"\nEnter Name: ";
getline(cin>>ws,name);
cout<<"Enter Barcode: ";
cin>>barcode;
cout<<"Enter Price: ";
cin>>price;
}
void printer()
{
cout<<"\nName: "<<name<<endl;
cout<<"Barcode: "<<barcode<<endl;
cout<<"Price: "<<price<<endl;
}
PrepackedFood()
{
scanner();
}
};
public:
void scanner()
{
cout<<"\nOf Fresh Food:"<<"\nEnter Name: ";
getline(cin>>ws,name);
cout<<"Enter Barcode: ";
cin>>ws>>barcode;
cout<<"Enter Price per Kilo: ";
cin>>price;
cout<<"Enter Weight (in kg): ";
cin>>weight;
}
void printer()
{
cout<<"\nName: "<<name<<endl;
cout<<"Barcode: "<<barcode<<endl;
cout<<"Rate per kg: "<<price<<endl;
cout<<"Weight: " <<weight<<endl;
cout<<"Total Price: " <<price*weight<<endl;
}
FreshFood()
{
scanner();
}
};
int main()
{
while(1)
{
Product *prod;
cout << "\nPress: \n1 for Prepacked Food\n2 for Fresh Food\n3 to
Exit\nEnter Choice: ";
int n;
cin >> n;
if (n == 1)
{
PrepackedFood d;
prod = &d;
prod->printer();
}
else if (n == 2)
{
FreshFood d;
prod = &d;
prod->printer();
}
else if (n == 3)
{
return 0;
}
else
{
cout << "Invalid Input!\n";
}
}
}
RESULT:
INPUT/ OUTPUT: