CPP-8. 상속

ikkkki·2026년 11월 3일

Cpp

목록 보기
1/2

클래스 상속과 객체

부모 클래스 = 기본 클래스(base class)
자식 클래스 = 파생 클래스(derived class)

다중 상속 허용.
상속 횟수는 제한 없음.

상속의 장점
1. 간결한 클래스 작성
2. 클래스 간의 계층적 분류 및 관리의 용이함
3. 클래스 재사용과 확장을 통한 소프트웨어의 생산성 향상

상속 시, 기본 클래스 앞에 상속 접근 지정 필수!
public, private, protected.

class Student : public Person {
};
#include <iostream>
#include <string>
using namespace std;

class Point {
    int x, y;
public:
    void set(int x, int y) {this->x = x, this->y = y;}
    void showPoint() {
        cout << "(" << x << "," << y << ")" << endl;
    }
};

class ColorPoint : public Point {
    string color;
public:
    void setColor(string color) {this->color = color;}
    void showColorPoint();
};

void ColorPoint::showColorPoint() {
    cout << color << ":";
    showPoint();
}

int main() {
    Point p;
    ColorPoint cp;
    cp.set(3, 4); //Point를 상속받은 ColorPoint 객체의 함수 사용가능 범위 확인!
    cp.setColor("Red");
    cp.showColorPoint();
}

기본 클래스의 private 멤버도 파생 클래스에 상속되고 파생 클래스의 객체에도 포함되지만, 파생 클래스의 어떤 함수에서도 직접 접근할 수 없다.

상속과 객체 포인터

업 캐스팅 (Up-casting)

파생 클래스의 객체를 기본 클래스의 포인터로 가리키는 것.
업 캐스팅한 기본 클래스의 포인터로는 기본 클래스의 멤버만 접근 가능.
캐스팅 시 명시적 타입 변환 필요 없음.

ColorPoint cp;
ColorPoint *pDer = &cp;
Point* pBase = pDer; //업캐스팅

pBase는 Point 클래스의 포인터 →\rarr ColorPoint 내의 Point 클래스 멤버만 접근 가능.

다운 캐스팅 (Down-casting)

명시적 타입 변환 지정 필요.

ColorPoint *pDer;
Point *pBase, po;
pBase = &po;
pDer = (ColorPoint*)pBase; //다운캐스팅

Point 클래스의 객체인 po의 주소를 갖는 객체 포인터 pBase는 Point 클래스
→\rarr pDer은 ColorPoint 타입의 포인터이지만, 실제 공간은 Point임.

protected 접근 지정

접근 가능 여부private 멤버protected 멤버public 멤버
멤버를 선언한 클래스OOO
파생 클래스XOO
다른 클래스나 외부 함수XXO

protected 멤버는 파생 클래스에게 접근 허용.

예제. 오류 찾기

#include <iostream>
#include <string>
using namespace std;

class Point {
protected:
    int x, y;
public:
    void set(int x, int y) {this->x = x, this->y = y;}
    void showPoint() {
        cout << "(" << x << "," << y << ")" << endl;
    }
};

class ColorPoint : public Point {
    string color;
public:
    void setColor(string color) {this->color = color;}
    void showColorPoint();
    bool equals(ColorPoint p);
};

void ColorPoint::showColorPoint() {
    cout << color << ":";
    showPoint();
}

bool ColorPoint::equals(ColorPoint p) {
    if (x == p.x && y == p.y && color == p.color)
        return true;
    else
        return false;
}

int main() {
    Point p;
    p.set(2,3);
    p.x = 5; //main 함수에서 직접 접근 불가
    p.y = 5;
    p.showPoint();

    ColorPoint cp;
    /*
    ColorPoint 멤버함수 내에서는 protected 멤버에 접근 가능하지만,
    main 함수에서는 ColorPoint 객체를 통하더라도 직접 접근 불가능.
    */
    cp.x = 10;
    cp.y = 10;
    cp.set(3, 4); //Point를 상속받은 ColorPoint 객체의 함수 사용가능 범위 확인!
    cp.setColor("Red");

    ColorPoint cp2;
    cp2.set(3, 4);
    cp2.setColor("Red");
    cout << ((cp.equals(cp2))?"true":"false");
}

상속과 생성자, 소멸자

생성자 호출 순서

파생 클래스와 기본 클래스는 각각 생성자를 가지고 있다.
기본 클래스의 생성자가 실행된 후 파생 클래스의 생성자가 실행된다.

파생 클래스에서 기본 클래스 생성자 호출

1. 컴파일러에 의해 묵시적으로 기본 클래스의 기본 생성자가 호출되는 경우

개발자가 기본 클래스의 생성자를 선택하지 않은 경우.
매개 변수가 있는 파생 클래스 생성자가 호출되더라도 기본 클래스의 기본 생성자가 호출됨.

B() : A() {}
B(int x) : A() {}

2. 명시적인 기본 클래스 생성자 선택

B(int x) : A(x+3) { //A(int x) 호출
	cout << "매개변수생성자 B" << x << endl;
}

소멸자 호출 순서

파생 클래스의 소멸자를 실행한 후 기본 클래스의 소멸자를 실행한다.
생성자의 실행 순서와 반대로 실행된다.

#include <iostream>
#include <string>
using namespace std;

class TV {
    int size;
public:
    TV() {size = 20;}
    TV(int size) {this->size = size;}
    int getSize() {return size;}
};

class WideTV : public TV {
    bool videoIn;
public:
    WideTV(int size, bool videoIn) : TV(size) {
        this->videoIn = videoIn;
    }
    bool getVideoIn() {return videoIn;}
};

class SmartTV : public WideTV {
    string ipAddr;
public:
    SmartTV(string ipAddr, int size) : WideTV(size, true) {
        this->ipAddr = ipAddr;
    }
    string getIpAddr() {return ipAddr;}
};
int main() {
    SmartTV htv("192.0.0.1", 32);
    /*
    SmartTV(string, int) 호출
    WideTV(int bool) 먼저 실행
    TV(int) 먼저 실행

    최종 생성자 실행 순서 : TV -> WideTV -> SmartTV
    */
    cout << "size=" << htv.getSize() << endl;
    cout << "videoIn=" << boolalpha << htv.getVideoIn() << endl;
    /*
    boolalpha : bool 자료형의 값을 1, 0 대신 true, false로 출력하도록 설정하는 출력 스트림 조작자(manipulator)
    */
    cout << "IP=" << htv.getIpAddr() << endl;
}

다중 상속

하나의 파생 클래스가 여러 클래스를 동시에 상속받는 것.

class MusicPhone : public MP3, public MobilePhone {}

장점) 클래스의 재사용과 코딩의 효율을 높임.
단점) 다중 상속을 받은 파생 클래스의 객체가 생성될 때, 기본 클래스의 멤버가 중복하여 공간을 차지하는 문제 발생.

#include <iostream>
using namespace std;

class Adder {
protected:
    int add(int a, int b) {return a + b;}
};
class Subtractor {
protected:
    int minus(int a, int b) {return a - b;}
};
class Calculator : public Adder, public Subtractor {
public:
    int calc(char op, int a, int b);
};
int Calculator::calc(char op, int a, int b) {
    int res = 0;
    switch(op) {
        case '+' : res = add(a, b); break;
        case '-' : res = minus(a, b); break;
    }
    return res;
}

int main() {
    Calculator handCalculator;
    cout << "2 + 4 = " << handCalculator.calc('+', 2, 4) << endl;
    cout << "100 - 8 = " << handCalculator.calc('-', 100, 8) << endl;
}

0개의 댓글