AlgoMan
AlgoMan

Reputation: 2935

Abstract class reference

Can i have a class

Class Room{ ~Room(); virtual cost()
=0; }

Class Hotel{ map<int, Room> rooms; /*
*/ };

will my hotel become abstract ? Can it hold the list of concrete Room objects that are derived from Room ?

Upvotes: 1

Views: 673

Answers (3)

anon
anon

Reputation:

The code you have written is not valid C++. If you mean:

class Room{ 
   ~Room();
   virtual int cost() =0; 
};

then yes, the class is abstract. You cannot then create a map like this:

map <int, Room> rooms;

but you can like this:

map <int, Room *> rooms;

Then assuming you have a class SingleRoom that is derived from Room and implements cost(), you can say:

rooms.insert( make_pair( 101, new SingleRoom ) );

Also, please note that abstract classes must have virtual destructors.

Upvotes: 6

Konrad
Konrad

Reputation: 40947

class Hotel
{
public:
    void AddRoom()
    {
        m_Rooms.insert( std::make_pair( 10, new Room ));    // Remember to delete
    }

    void AddNicerRoom()
    {
        m_Rooms.insert( std::make_pair( 10, new NicerRoom ));    // Remember to delete
    }
private:
    std::map< unsigned int, HotelRoom* > m_Rooms;
}

class HotelRoom
{
public:
    ~HotelRoom;    // Virtual Dtor

protected:
    virtual int cost() = 0;
}

class Room : public HotelRoom
{
    /*virtual*/ int cost()
    {
        // impl
    }
}

class NicerRoom : public HotelRoom
{
    /*virtual*/ int cost()
    {
        // impl
    }
}

There you go. Basic example, here HotelRoom is an abstract class with Room and NicerRoom inheriting and implementing the pure virtual method cost(). This is one way you might go about doing it.

If you expand or rephrase your question so I can better understand what you are asking I'll update my answer.

Upvotes: 1

Patrick
Patrick

Reputation: 23619

What you probably want is that the Hotel can store different kinds of rooms. In that case the map in the hotel needs to store pointers to rooms rather than rooms itself, like this:

class Hotel
   {
   std::map<int,Room *> roomMap;  // maps room numbers to rooms
   };

In this example I used a map to map the room numbers to pointers pointing to the room. If we would have stored Rooms instead of Room-pointers, then this wouldn't simply compile since we can't instantiate a Room by itself.

Notice that if you store Room-pointers, there should also be somebody that delete's the rooms afterwards. Give Room a virtual destructor (like Neil already pointed out) and just delete the rooms in the destructor of Hotel.

Upvotes: 1

Related Questions