우리가 부모님으로부터 재산을 상속받는것처럼, 객체지향프로그래밍 언어들의 class 역시 상속을 받을 수 있다.
# include <iostream>
# include <string>
class Parent {
// protected:
std::string s;
public:
Parent() : s("Parent") { std::cout << s << std::endl; }
void println() {std::cout << s << std::endl; }
};
class Child : public Parent{
std::string s;
public:
Child() : Parent(), s("Child") {std::cout << s << std::endl;
println();
}
//void println() {std::cout << s << std::endl; }
};
int main() {
std::cout << "Parent Class" << std::endl;
Parent P;
std::cout << "Child Class" << std::endl;
Child C;
return 0;
}
클래스가 다른 클래스를 상속하기 위해서는 그 옆에 : public [classname] 을 적어주면 된다.
위의 코드의 경우 실행을 하면
Parent Class
Parent
Child Class
Parent
Child
Parent
같은 결과를 가지게 된다.
하지만 여기서 의문이 생길 수 있다. 분명 child에서 println을 실행했는데 왜 parent의 println이 나오지? 라는 의문이다. 이는 child 안에 println이 선언되지 않아 parent안에 println이 실행되었기 때문이다.
이를 오버라이딩이라 부른다.
하지만 자바에서 캡슐화를 통해 내용물들을 보호했던것처럼, cpp에서도 private, public, protected를 통해 보호한다.
만약, 자식 클래스에서 parent안의 private값을 변경시도한다면 접근불가능 오류가 발생한다.
class Child : public Parent{
std::string cs;
public:
Child() : Parent(), cs("Child") {std::cout << cs << std::endl;
ps = "Pparents"
}
멤버 "Parent::ps" (선언됨 줄 6)에 액세스할 수 없습니다.
이는 Parents 안의 ps가 private 영역이기 때문이다. 이에 우리는 이를 protected 영역에 넣어서 해결할 수 있다.
혹은 반대로 보호해주려면, private에 넣어두거나
이러한 방법으로 작동방식을 지정하면 된다.
class child : <public, private, protected> parent
public의 경우 기존의 적힌 상태 그대로 작동하며
protected의 경우 public이 protected로 변하여 작동한다.
private의 경우 아예 모든 접근을 차단한다.
# include <iostream>
# include <string>
class Employee {
protected:
std::string name;
int age;
std::string position;
int rank;
public:
Employee(std::string name, int age, std::string position, int rank) :
name(name), age(age), position(position), rank(rank) {}
Employee(const Employee& employee) {
name = employee.name;
age = employee.age;
position = employee.position;
rank = employee.rank;
}
Employee() {}
void print_info() {
std::cout << name << " (" << position << " , " << age << ") ==> " << calc_pay() << "Man Won" << std::endl;
}
int calc_pay() { return 200 + rank * 50; }
};
class Manager : public Employee {
int year_of_service;
public:
Manager(std::string name, int age, std::string position, int rank,
int year_of_service)
: Employee(name, age, position, rank), year_of_service(year_of_service) {}
Manager(const Manager& manager)
: Employee(manager.name, manager.age, manager.position, manager.rank) {
year_of_service = manager.year_of_service;
}
Manager() : Employee() {}
int calculate_pay() { return 200 + rank * 50 + 5 * year_of_service; }
void print_info() {
std::cout << name << " (" << position << " , " << age << ", "
<< year_of_service << " Years) ==> " << calculate_pay() << "Man Won"
<< std::endl;
}
};
class EmployeeList {
int alloc_employee;
int current_employee;
int current_manager;
Employee** employee_list;
Manager** manager_list;
public:
EmployeeList(int alloc_employee) : alloc_employee(alloc_employee) {
employee_list = new Employee*[alloc_employee];
manager_list = new Manager*[alloc_employee];
current_employee = 0;
current_manager = 0;
}
void add_employee(Employee* employee) {
employee_list[current_employee] = employee;
current_employee++;
}
void add_manager(Manager* manager) {
manager_list[current_manager] = manager;
current_manager++;
}
int current_employee_num() { return current_employee + current_manager; }
void print_employee_info() {
int total_pay = 0;
for (int i = 0; i < current_employee; i++) {
employee_list[i]->print_info();
total_pay += employee_list[i]->calc_pay();
}
for (int i = 0; i < current_manager; i++) {
manager_list[i]->print_info();
total_pay += manager_list[i]->calculate_pay();
}
std::cout << " Total : " << total_pay << " Man Won " << std::endl;
}
~EmployeeList() {
for (int i = 0; i < current_employee; i++) {
delete employee_list[i];
}
for (int i = 0; i < current_manager; i++) {
delete manager_list[i];
}
delete[] employee_list;
delete[] manager_list;
}
};
int main() {
EmployeeList emp_list(10);
emp_list.add_employee(new Employee("John", 34, "Noraml", 1));
emp_list.add_employee(new Employee("Brian", 34, "Noraml", 1));
emp_list.add_manager(new Manager("Kayle", 41, "Bucho", 7, 12));
emp_list.add_manager(new Manager("Notch", 43, "Kacho", 4, 15));
emp_list.add_manager(new Manager("Vista", 43, "Chajang", 5, 13));
emp_list.add_employee(new Employee("Seal", 36, "daeri", 2));
emp_list.add_employee(new Employee("Albert", 36, "intern", -2));
emp_list.print_employee_info();
return 0;
}
이는 상속을 통해 직원관리 프로그램을 구현한것이다.
출처
여기서 manager는 employee와 매우 유사한 기능을 수행하고 이에 상속으로 처리해서 코드중복을 줄인것이다.