[C/C++] 상속(Inheritance), 추상 클래스(Abstract Class), 인터페이스(Interface)

할랑말랑·2026년 3월 9일

C/C++

목록 보기
9/45

1. 상속(Inheritance)

상속은 한 클래스가 다른클래스의 멤버(변수,함수)를 물려받는 기능이다. 이를 통해 기존 코드를 재사용하고 클래스 간의 계층적 관계("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;
}

2. 추상 클래스(Abstract Class)

하나 이상의 순수 가상함수를 포함하는 클래스이다. 순수 가상 함수는 선언만 있고 구현은 없는 함수를 말한다. 추상 클래스는 그자체로 객체를 생성할 수 없고 반드시 자식 클래스에서 상속받아 순수 가상 함수를 오버라이딩 재정의 해야 사용할 수 있다.

특징

  • 추상 클래스 자체의 객체를 생성할 수는 없지만 추상 클래스를 가리키는 포인터는 만들수있다.
#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;
}

3. 인터페이스(Interface)

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;
}

0개의 댓글