For example:
class Airport : public vector<Airline*>
How do I free the memory properly? I would prefer not use smart pointers as I have not learned it yet in my course.
As others have pointed out, Airport should not inherit from vector. Airport should contain a vector. Then there is the question of who owns the Airlines, do you want the Airlines to be destroyed when the Airport is destroyed? If so I suggest either a simple std::vector<Airline>:
class Airport {
std::vector<Airline> airlines_;
//...
};
Or if you need polymorphism, i.e Airline is a base class with specializations for different Airlines I suggest smart pointers:
class Airport {
std::vector<std::unique_ptr<Airline>> airlines_;
//...
};
If you really don't want to use smart pointers you could use raw pointers and then carefully delete them in the destructor:
class Airport {
std::vector<Airline*> airlines_;
public:
Airport(const Airport&) = delete; // not allowed
Airport& operator=(const Airport&); = delete; // not allowed
~Airport() {
for (auto airline : airlines) {
delete airline;
}
}
//...
};
If you do this you need to think carefully about what copying behaviour you want Airport to have because the default copy constructor and assignment operator will not manage the memory properly. As a first step you can prevent copying by 'delete'ing copy constructor and assignment operator as I have above. But I suggest as soon as you learn about smart pointers use them instead as most of these problems go away.
If the Airport does not own the Airlines then store raw pointers or shared smart pointers in the vector and leave it to whoever owns the Airlines to free the memory properly. In my mind an Airline can operate in more than one Airport so it doesn't make sense for the Airport to own the Airline so there should be a separate container of Airline but it depends on your model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With