Skip to content

Instantly share code, notes, and snippets.

@Fiona-J-W
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save Fiona-J-W/ecedb5ead26847f05a31 to your computer and use it in GitHub Desktop.

Select an option

Save Fiona-J-W/ecedb5ead26847f05a31 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
class vehicle {
public:
vehicle(const std::string& model, const std::string& color, unsigned year, unsigned price):
m_model{model}, m_color{color}, m_year{year}, m_price{price} {}
// we have a virtual method, so we should make the dtor virtual too:
virtual ~vehicle() = default;
// get back the default-definitions of copy/move-ctor/assignment-operator:
vehicle(const vehicle&) = default;
vehicle(vehicle&&) = default;
vehicle& operator=(const vehicle&) = default;
vehicle& operator=(vehicle&&) = default;
friend std::ostream& operator<<(std::ostream& stream, const vehicle& v) {
v.print(stream);
return stream;
}
protected:
virtual void print(std::ostream& stream) const {
stream <<
"year: " << m_year << "\n"
"model: " << m_model << "\n"
"color: " << m_color << "\n"
"price: " << m_price << '\n';
}
private:
std::string m_model;
std::string m_color;
unsigned m_year;
unsigned m_price;
};
class truck: public vehicle {
public:
truck(const std::string& model, const std::string& color, unsigned year, unsigned price, unsigned passengers):
vehicle{model, color, year, price}, m_passengers{passengers} {}
protected:
void print(std::ostream& stream) const override {
vehicle::print(stream);
stream << "passengers: " << m_passengers << '\n';
}
private:
unsigned m_passengers;
};
int main() {
const auto vehicle_1 = vehicle{"car", "black", 2013, 20'000};
const auto truck_1 = truck{"bus", "red", 2008, 100'000, 30};
const vehicle& vehicle_2 = truck_1;
std::cout << vehicle_1 << "\n\n" << truck_1 << "\n\n" << vehicle_2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment