C++
클래스 상속
khon98
2020. 12. 15. 16:10
상속
- 상속은 객체 지향 프로그래밍의 주요한 특성 중 하나
- 현실 세계에서의 상속의 개념을 프로그래밍으로 그대로 가져와 사용할 수 있음
- 이를 통해 프로그램의 논리적 구조를 계층적으로 구성할 수 있음
- 흔히 자식이 부모의 속성을 물려받듯이 자식 클래스가 부모 클래스의 속성을 그대로 물려받아 사용할 수 있음
- 그러므로 상속을 활용하여 소스코드의 재사용성을 늘일 수 있음
- 자식 클래스는 파생 클래스라고도 불리며 부모 클래스의 모든 속성을 물려 받음
- 자식 클래스는 콜론(:)을 활용하여 부모 클래스와 연결될 수 있음
* 부모 클래스 정의하기
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class Person {
private:
string name;
public:
Person(string name): name(name) {}
string getName() {
return name;
}
void showName(){
cout << "이름: " << getName() << '\n';
}
};
* 자식 클래스 정의 및 사용하기
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class Person { // 부모 클래스
private:
string name;
public: // 생성자
Person(string name) : name(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, "khon");
student.show();
system("pause");
return 0;
}
생성자와 소멸자
- 자식 클래스의 인스턴스를 만들 때 가장 먼저 부모 클래스의 생성자가 호출, 이후 자식 클래스의 생성자가 호출
- 자식 클래스의 수명이 다했을 때는 자식 클래스의 소멸자가 먼저 호출된 이후에 부모 클래스의 소멸자가 호출
오버 라이딩
- 부모 클래스에서 정의된 함수를 무시하고 자식 클래스에서 동일한 이름의 함수를 재정의하는 문법
- 오버 라이딩을 적용한 함수의 원형은 기존의 함수와 동일한 매개 변수를 전달 받음
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';
}
};
int main(void) {
Student student(1, "khon");
student.showName();
system("pause");
return 0;
}
다중 상속
- 여러 개의 클래스로부터 멤버를 상속받는 것을 말함
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class Temp {
public:
void showTemp() {
cout << "임시 부모 클래스.\n";
}
};
class Person {
private:
string name;
public: // 생성자
Person(string name) : name(name) {}
string getName() {
return name;
}
void showName() {
cout << "이름: " << getName() << '\n';
}
};
class Student : Person, public Temp {
private:
int studentID;
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, "khon");
student.showName();
student.showTemp();
system("pause");
return 0;
}
다중 상속의 한계
- 여러 개의 부모 클래스에 동일한 멤버가 존재할 수 있음
- 하나의 클래스를 의도치 않게 여러 번 상속받을 가능성이 있음
- C++의 클래스 상속은 객체 지향 프로그래밍의 중요한 키워드
- 상속의 원리를 활용하여 소스코드의 재사용성을 증대시킬 수 있음