Last active
August 29, 2015 14:11
-
-
Save Fiona-J-W/ecedb5ead26847f05a31 to your computer and use it in GitHub Desktop.
suggestion for https://www.reddit.com/r/cpp_questions/comments/2p93b3/how_do_i_inherit_a_overloaded_operator_in_c/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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