i have a code to read some products from a file.(.dat). it hasthe name, model number, price and its purpose.
example. = knife 103 10 cut

currently it can read the first 3. The question asks i make a derived class to read the purpose. Here is my code

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int maxProds = 20;

class product {
   string name;
   string model;
   float price;
   string purpose;
   void createProduct(string,string,float,string);
   void readRecord(ifstream &);
   void displayDetails(); 

void product::createProduct(string n, string m, float p, string u) {
   name =n;
   model = m;
   price =p;
   purpose =u;

void product::readRecord(ifstream &infile)

void product::displayDetails()
     cout<<"Name:"<<name<<" model no.: "<<model<<endl;
     cout<<"Price: "<<price<<"Purpose: "<<purpose<<"\n"<<endl;


class weapon:public product                       
       product prods[maxProds];
       ifstream infile;
       string purpose;
       void readProducts();
       void run();

void weapon::readProducts() {
 int count=0;
 ifstream infile;
      while(infile.peek()!=EOF) {
     for(int i=0;i<count;i++)

int main(){      
 weapon w;
 cout<<"This is from the class"<<endl;
 return 0;

in my code i added purpose into the base class. However after re-reading the question, it actually asks me to include the purpose string into the derived class(weapon). the derived class is responsible for purpose string and the readProducts bit. How would i go about doing it?
The base class is asked to read or display the inherited data members and add code to read or display the additional data member.

how would i go about achieving this? any help is appreciated.

I think that my answer would include a ProductSet class that stores all the products that ae read from the file. Since you might have several classes of product (all derived from Product), such as Weapon, Tool, Clothing, Food, etc. then your ProductSet class should probably use store the products in the form std::vector< Product * >, so that all the types of product can be stored in the same place. The ProductSet class would be responsible for reading the file an deciding which kind of derived class the product actually is. I would imagine that you don't ever want anyone to store an item of type Product, so the displayDetails function in the Product class should be pure-virtual. I hope that makes some sense, I don't have more time to give a fuller answer, but have a think about those things.

This article has been dead for over six months. Start a new discussion instead.