Call derived class func from base class reference

Hi . here is my code

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
class Ship {

    private:
        int yrBuilt;
    protected:
        string name;
    public:
        Ship();
        ~Ship();
        void setName(string);
        void setYear(int);

        string getName();
        int getYear();

        virtual void showInfo(){
            cout <<"Name: "<<name<<endl;
            cout<<"Year built: "<<yrBuilt<<endl;
                            }


};

class CruiseShip: public Ship{

    private:
        int maxPass;

    public:
        CruiseShip();
        ~CruiseShip();
        void setPass(int);
        int getPass();
        void showInfo();
};


int main(){

    Ship** ship=new Ship* [3];

    ship[0]->showInfo();
    ship[0]->setName("Shihab Pacific");
    ship[0]->setYear(1999);

    ship[1]=new CruiseShip();
    ship[1]->showInfo();
    ship[1]->setName("The Tourist");
    ship[1]->setPass(5000);// Says error class Ship has no member setPss 


How can I do this one?

If you just want to call the function right after you created the object you could store the pointer as a CruiseShip pointer while you call the functions.

1
2
3
4
5
CruiseShip* cruiseShip = new CruiseShip();
cruiseShip->showInfo();
cruiseShip->setName("The Tourist");
cruiseShip->setPass(5000);
ship[1] = cruiseShip;


If you want to be able to call setPass on a Ship pointer you might want to make the function a (virtual?) member function of Ship.
Last edited on
Thanks, the first soln meets my task
Last edited on
One more thing, for the array should I just delete like
Ship ** ship= new Ship*[2];//what I defined
delete [] ship

or i delete in a loop?

Last edited on
You should use delete on everything that you created using new.
Topic archived. No new replies allowed.