상속은 한 클래스가 다른클래스의 멤버(변수,함수)를 물려받는 기능이다. 이를 통해 기존 코드를 재사용하고 클래스 간의 계층적 관계("is-a")를 형성할 수 있다.
#include <iostream> #include <string> using namespace std; class Vehicle { protected: string color; int speed; public: Vehicle(string c, int s) : color(c), speed(s) {} void move() { cout << "The vehicle is moving at " << speed << " km/h." << endl; } void setColor(string c) { color = c; } string getColor() { return color; } }; // 파생 클래스 1: 자전거 class Bicycle : public Vehicle { private: bool hasBasket; public: Bicycle(string c, int s, bool basket) : Vehicle(c, s), hasBasket(basket) {} void ringBell() { cout << "Bicycle bell: Ring Ring!" << endl; } }; // 파생 클래스 2: 트럭 class Truck : public Vehicle { private: int cargoCapacity; public: Truck(string c, int s, int capacity) : Vehicle(c, s), cargoCapacity(capacity) {} void loadCargo() { cout << "Truck loading cargo. Capacity: " << cargoCapacity << " tons." << endl; } }; int main() { Bicycle b("Yellow", 30, true); Truck t("Blue", 40, 95); b.ringBell(); t.loadCargo(); return 0; }
하나 이상의 순수 가상함수를 포함하는 클래스이다. 순수 가상 함수는 선언만 있고 구현은 없는 함수를 말한다. 추상 클래스는 그자체로 객체를 생성할 수 없고 반드시 자식 클래스에서 상속받아 순수 가상 함수를 오버라이딩 재정의 해야 사용할 수 있다.
#include <iostream> #include <string> using namespace std; class Animal { public: Animal() {} virtual void bark() = 0; }; class Lion : public Animal { public: Lion(string word) : m_word(word) {} void bark() { cout << "Lion" << " " << m_word << endl; } private: string m_word; }; class Wolf : public Animal { public: Wolf(string word) : m_word(word) {} void bark() { cout << "Wolf" << " " << m_word << endl; } private: string m_word; }; class Dog : public Animal { public: Dog(string word) : m_word(word) {} void bark() { cout << "Dog" << " " << m_word << endl; } private: string m_word; }; void print(Animal* animal) { animal->bark(); } int main() { Lion lion("ahaaaaaa!"); Wolf wolf("ohhhhhh"); Dog dog("ooooooooooooooops"); Animal* cat = new Dog("dsasdasdas"); print(&lion); print(&wolf); print(&dog); print(cat); delete cat; return 0; }
C++에는 Jave,C#처럼 Interface 키워드는 따로 존재하지 않는다. 대신 모든 멤버 함수가 순수 가상 함수인 추상 클래스를 만들어 인터페이스를 구현한다.
#include <string> #include <iostream> using namespace std; class ILoggable { public: virtual void writeLog(const string& message) = 0; virtual ~ILoggable() {} }; class DatabaseManager : public ILoggable { public: void writeLog(const string& message) override { cout << "[DB LOG]: " << message << endl; } }; class FileManager : public ILoggable { public: void writeLog(const string& message) override { cout << "[File LOG]: " << message << endl; } }; void logActivity(ILoggable& logger, const string& activity) { logger.writeLog(activity); } int main() { DatabaseManager db; FileManager fm; logActivity(db, "User logged in."); logActivity(fm, "Data saved to file."); return 0; }