Inheritance and Polymorphism
Separating Header and Source File
- Header file: properties(속성) & method prototype(메소드 원형)
- Source file: 메소드 본문 정의
-> 장점: 실제 프로그래밍을 할 때 클래스의 정의를 분리하는 것이 좋음 -> 코드가 무한대로 길어질 수 있기 때문
this pointer
- C++에서는 클래스 멤버르 "id = _id" 이런 식으로 intailized함
- 근데, this pointer를 사용하면 intailized 없이 멤버를 가르키거나 초기화할 수 있음
Inheritance(상속)
- 부모 클래스 = 기초 클래스 = base class
- 자식 클래스 = 유도 클래스 = derived class
- inheritance: 부모 클래스를 자식 클래스에게 상속
class UnivMem{ //기초 클래스
private:
int id;
int age;
public:
UnivMem(int i, int a){
id = i;
age = a;
}
};
class Student: public UnivMem{ //유도 클래스
private:
double GPA;
public:
Student(int i, int a, double g): UnivMem(i, a) {
GPA = g;
}
};
- 자식 클래스에서도 생성자를 초기화 해야함 -> 부모 클래스의 생성자를 호출해서 초기화하는 것이 일반적임
즉, 자식 클래스는 객체생성 과정에서 기초 클래스의 생성자를 100%로 호출한다.
Three kinds of Inheritance
- public 상속: public보다 접근의 범위가 넓은 멤버는 public으로 변경시켜서 상속 → private를 제외한 나머지는 그냥 그래로 상속
- protected 상속: protected 보다 접근 범위가 넓은 멤버는 protected로 상속 → protected member: private한 성질이지만 유도 클래스에서 접근 가능, 외부에서는 불가능
- private 상속: 기초 클래스에서 private는 접근 불가능, private 범위보다 넒은 범위들은 유도 클래스 내에서만 접근이 가능
Inheritance and Object Pointer
- 부모클래스와 자식클래스를 한 배열 안에 저장 가능
void printMem(UnivMem **mems, int n){ //더블포인터로 받음 for (int i=0; i<n; i++) mems[i] -> Print(); }
int main(){
UnivMem members[2]; //members[2] -> UnivMem형이면서 포인터 변수+배열
Professor p(0,34, 818);
Studnet s(1, 20, 4.3);
members[0] = &p;
members[1] = &s;
printMem(memebers, 2); //UnivMem형인 member를 더블포인트형 매개변수로 보냄
return 0;
}
- Student pointer는 모든 public 멤버에 접근할 수 있음
- But, UnivMem pointer는 UnivMem 객체만 접근할 수 있음
<br/>
## Function Overriding
- Overloading과 다름
- 상속받는 자식클래스는 부모클래스에 있는 함수를 덮어씀(가려짐). 즉, 부모클래스와 자식클래스에 같은 이름의 함수가 있고 따로 부모클래스라고 선언하지 않으면 자식클래스의 함수가 호출됨 -> Overriding
- 만약, 오버라이딩으로 가려진 기초 클래스의 함수를 호출하고 싶으면 UnivMem::print()와 같이 "::"연산자를 이용하면 됨