본문 바로가기
c++

[C++] 객체 포인터의 참조관계

by goblin- 2023. 6. 9.

우리는 클래스를 기반으로도 포인터 변수를 선언할 수 있다. 예를 들어서 Person이라는 이름의 클래스가 정의되었다면, Person 객체의 주소 값 저장을 위해서 다음과 같이 포인터를 변수를 선언할 수 있다.

 

Person *ptr;			//포인터 변수 선언
ptr = new Person();		//포인터 변수의 객체 참조

위의 두 문장이 실행되면, 포인터 Ptr은 Person 객체를 가리키게 된다. 그런데 Person형 포인터는 Person 객체뿐만 아니라, Person을 상속하는 유도 클래스의 객체도 가리킬 수 있다.

 

class Student : public Person{
...
};

class PartTimeStudent : public Student{
...
};

Person *ptr = new Student();		
//유도 클래스인 Student객체를 Person형 포인터 변수가 가리키고있다.

Person *ptr = new PartTimeStudent();
//Person형 포인터 변수가 PartTimeStudent 객체도 가리킬 수 있다.

Student * ptr = new PartTimeStudent();
//Student형 포인터 변수도 PartTimeStudent 객체를 가리킬 수 있다.

C++에서, AAA형 포인터 변수는 AAA 객체 또는 AAA를 직접 혹은 간접적으로 상속하는 모든 객체를 가리킬 수 있다.(객체의 주소 값을 저장할 수 있다.

 

학생(Student)은 사람(Person)이다.

근로학생(PartTimeStudent)은 학생(Student)이다.

근로학생(ParTimeStudent)은 사람(Person)이다

 

 

함수의 오버라이딩(함수의 오버로딩과 혼동하지 말자)

.
.
.
class PermanentWorker : public Employee{
.
.
public:
	int GetPay() const{}
    int ShowSalaryInfo() const{}
};


class SaleWorker : public PermanentWorker{
private:
.
.
public:
	int Getpay() cont{
    	return PermanetWorker::GetPay() + (int)(SalesResult*bonusRatio);
        //PermanentWorker의 GetPay 함수 호출
.
.
}