0
votes

I have 2 classes. The base class has a virtual display function and member variable shipname and date. The display() function in the base class prints the ship name. The derived class has an override of display() which also prints the ship name and a member variable y.

void Ship::display(){
    cout << shipName << endl << manufactureDate < <endl;
}

void CruiseShip::display(){
    cout << shipName << maxNoOfPassengers << endl;
}

I have a loop that calls an object from base class and object from derived class but it outputs only one ship name instead of two

When I call display from derived class I the ship name is empty, but when I call it from base object it returns its value.

void main(){
    Ship       sh;
    CruiseShip cruShip;
    CargoShip  cargShip;

    sh.setName("Monster");
    sh.setDate("11/11/2011");
    cruShip.setNoOfPassengers(10);
    cargShip.setCapacity(1000);
    /*Ship *x[3] = {&sh, &cruShip, &cargShip};
    for(int i=0;i<3;++i){
        x[i]->display();
    }*/
    cout<<sh.getName()<<endl;
     cout<<cruShip.getName()<<endl;
     cout<<cargShip.getName();

    system("pause");
}

Monster shows only from object sh

2
Um. Perhaps you need to call setName() on cruShip and cargShip?Chris Cooper
You've only set the name on sh. What names do you expect the others to have, and why?Mike Seymour
when i inherit from a class i get its variable which is shipName then i set shipName in sh object did it lose it value when i call it from another class??MohamedAbbas

2 Answers

1
votes

You are not setting the attributes of your cargShip object. You set the name and date of the sh object, but the cargShip object is a whole separate object, with its own name and date that you have not set yet. Try:

cargShip.setName("Cargo Ship")
cargShip.setCapacity(1000);
0
votes

First of all it is not clear how the classes are defined, whether you initialize data members of the base class in the constructor of the derived class or not. Also I do not see that function display declared as virtual.