rueki

C++ 클래스의 상속 본문

C,C++ 기초 및 자료구조

C++ 클래스의 상속

륵기 2020. 10. 9. 17:33
728x90
반응형

상속 (inheritance)

객체지향 프로그래밍의 중요한 특성 중 하나이다.

자식 클래스가 부모 클래스의 속성을 물려받아서 사용할 수 있음에 따라 소스코드의 재사용성을 늘릴 수 있다.

부모 클래스의 모든 속성을 물려받고, : 를 이용해서 연결할 수 있다.

 

 

#include <iostream>
using namespace std;
// 부모클래스
class Person{
private:
    string name;

public:
    Person(string name) : name(name){}
    string getName(){
    	return name;
    }
    void showName(){
        cout << "이름: " << getName() << '\n';
    }
};

//자식 클래스
class Student : Person{

private:
    int studentID;
    // name은 Person으로부터 물려받음
public:
    //변수로 전부 다 받을 수 있음
    Student(int studentID, string name) : Person(name){
        this->studentID = studentID;
    }
    void show(){
        cout<<"학생 번호: " << studentID <<'\n';
        cout<<"학생 이름: " << getName() << '\n';
    }
};

int main(void){
    Student student(1, "홍길동");
    student.show();
    system("pause");
}

 

상속에서 생성자와 소멸자

자식 클래스의 인스턴스를 만들 때, 가장 먼저 부모클래스의 생성자가 호출되고, 이후에 자식 클래스의 생성자가 호출된다. 자식 클래스의 수명이 다하게 되면, 자식클래스 소멸자 호출 후, 부모 클래스 소멸자가 호출된다.

 

오버라이딩

부모클래스에서 정의된 함수를 무시하고, 자식클래스에서 동일한 이름의 함수를 재정의한다.

오버라이딩을 적용한 함수의 원형은 기존의 함수와 동일한 매개변수를 전달 받는다.

//자식 클래스 오버라이딩
class Student : Person{

private:
    int studentID;
    // name은 Person으로부터 물려받음
public:
    //변수로 전부 다 받을 수 있음
    Student(int studentID, string name) : Person(name){
        this->studentID = studentID;
    }
    void show(){
        cout<<"학생 번호: " << studentID <<'\n';
        cout<<"학생 이름: " << getName() << '\n';
    }
    void showName() {
        cout << "학생 이름 : " << getName() << "\n";
    }
};

결과는 자식 클래스의 showName을 실행하게 된다.

 

다중 상속

여러개의 클래스로부터 멤버를 상속 받는 것

class Temp{
public:
    void showTemp(){
        cout<<"임시 부모 클래스.\n";
    }
};

//자식 클래스 다중상속 예제
class Student : Person, public Temp{

private:
    int studentID;
    // name은 Person으로부터 물려받음
public:
    //변수로 전부 다 받을 수 있음
    Student(int studentID, string name) : Person(name){
        this->studentID = studentID;
    }
    void show(){
        cout<<"학생 번호: " << studentID <<'\n';
        cout<<"학생 이름: " << getName() << '\n';
    }
    void showName() {
        cout << "학생 이름 : " << getName() << "\n";
    }
};


int main(void){
    Student student(1,'홍길동');
    // 다중상속을 통한 함수 실행 가능
    student.showName();
    student.showTemp();
    system("pause");
}
728x90
반응형

'C,C++ 기초 및 자료구조' 카테고리의 다른 글

깊이 우선 탐색 (Depth First Search)  (0) 2020.10.13
순차탐색과 이진탐색  (0) 2020.10.10
우선순위 큐(priority Queue)  (0) 2020.10.09
생성자와 소멸자  (0) 2020.10.06
C++ 입출력  (0) 2020.09.16
Comments