0

I am working on a project for school polymorphism project for school with a base class(Musical Instrument) and 2 derived classes(string and brass). In main we need to create an array of base class pointers then read data from a file and use the pointers to create a new object depending on whether it is brass or string. We then need to use a virtual display function to output the results. My problem is my output just repeats the 2nd item in the file and only takes cost, etc from the first item.

Contents of file being read

S
Messiah Stradivarius
18000000
1
4
S
The Titanic Violin
1700000
1
2
S
The Lady Tennant
2032000
1
4
S
The Hammer Stradivarius
3544000
1
4
B
French horm
8500
valves
brass
S
Eric Clapton's Blackie
959500
0
6
S
Jimmy Page's double-neck Gibson EDS-1275
1245600
0
12
S
Willie Nelson's Lucille
30
0
6
I
Bass drum
239
B
Trumpet
1200
valves
brass
I
Saxophone
3800
I
Piccolo
149
S
Jimi Hendrix's First Wife
1250000
0
6

Client File

const int MAX = 15;

int main()
{
    int i = 0;
    string inType;
    string inName;
    int inCost;
    int inBowed;
    int inStrings;
    string inSound;
    string inMaterial;

    MusicalInstrument* p2i[MAX];

    ifstream infile;
    infile.open("prog7.txt");

    while (i < MAX && !infile.eof())
    {
        infile >> inType;
        if (inType == "S")
        {
            getline(infile, inName);
            infile >> inCost;
            infile >> inBowed;
            infile >> inStrings;
            p2i[i] = new StringInstrument(inName ,inCost ,inBowed ,inStrings);
            p2i[i]->displayInstrument();

        }
        else
        {

            getline(infile, inName);
            infile >> inCost;
            getline(infile, inSound);
            getline(infile, inMaterial);
            p2i[i] = new BrassInstrument(inName, inCost, inSound,inMaterial);
            p2i[i]->displayInstrument();

        }
        i++;

    }
    infile.close();
    while (i < MAX)
    {
        delete p2i[i];
        p2i[i] = nullptr;
        i++;
    }


    return(0);
}   

Output

~/cs2020$ a.out
Type: String Instrument
Name: MessiahStradivarius
Cost: 1.8e+07
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4
Type: String Instrument
Name: TheTitanic
Cost: 0
Bowed: 1
Strings: 4

1 Answers1

1

There is no need of creations of objet of derived classes. Because in polymorphism we can directly use derived class from the base class. In the base class, Base_ class object; object.function_name(); It will directly access derived class.

AnkuSh
  • 11
  • 2