SlideShare a Scribd company logo
1 of 11
Download to read offline
상속과 캐스팅
( Inheritance & Casting )
FaceBook Group "코딩의 아침"
Self Study & Sharing
Ø 상속관계 "IS - A 상속"
CMonster
CJump
Monster
CFly
Monster
Monster의 기본 속성을 갖고있는
부모의 모든 데이터를
JumpMonster / FlyMonster가
상속받고,
자신의 고유특성인
Jump / Fly 가 새로 추가된 형태
Parents
Child
Inheritance
üJumpMonster is Monster / FlyMonster is Monster 의 관계가 성립된다.
Ø 상속관계 "HAS - A 상속"
CJump
Monster
CFly
Monster
CSteel
Spring
CAngel
Wing
만약, 기본능력으로 생성된 후
JumpMonster는 추진력을 얻기
위해 Spring을 갖고 있어야하고,
FlyMonster는 천상계로 가기
위해 천사날개를 얻어야 한다면?
ü 모든 몬스터가 +특성을 상속 받는 형태가 아닌, 소유하는 있는 방식의 형태
üJumpMonster has SteelSpring / FlyMonster has AngelWing 의 관계가 성립된다.
Ø 상속관계 "Casting이란?"
CMonster
CJump
Monster
CFly
Monster
Parents
Child
Inheritance
- (1) 상속관계에 있는 클래스끼리
형(TYPE)변환이 가능하다.
- (2) 부모 포인터(Parents*)
자식 포인터(Child*) 의 참조변수에
따라 사용방식이 달라 진다.
Ø Casting방식은 자신이 접근하고자는 유효한 범위에 따라 캐스팅 방식을
선택할 수 있다.
Ø 상속관계 "Up Casting"
§ 하위 클래스에서 상위클래스로 Casting한 경우
§ 자식객체 참조를 부모형 포인터로 받은 경우를 말한다.
§ 다형성(virtual)관계에 있을 경우, 자식의 함수가 호출 된다.
Parents
Child
virtual void Move (void) { cout << "부모움직임" <<endl; }
void Name(void) { cout << "나는 부모" <<endl; }
virtual void Move (void) { cout << "자식움직임" <<endl; }
void Name(void) { cout << "나는 자식" <<endl; }
만약 Parents* pObj = new Child 한 경우
Move함수와 Name함수를 호출한다고 했을때 어떤 결과가 나올까?
(호출 x )
(호출 o )
(호출 x )
(호출 o )
모두 자식의 함수가 호출되지 않았다.
virtual함수는 오버라이딩에 의해 자식의 함수가 호출되었으나,
자식의 멤버함수 Name( ) 호출되지 않았다.
Ø Up Casting 예시
Ø 상속관계 "Down Casting"
§ 상위클래스에서 하위클래스쪽으로 Casting을 하는 경우
§ Up캐스팅된 참조변수를 본래의 참조변수로 되돌릴 경우 사용한다.
Parents
Child
virtual void Move (void) { cout << "부모움직임" <<endl; }
void Name(void) { cout << "나는 부모" <<endl; }
virtual void Move (void) { cout << "자식움직임" <<endl; }
void Name(void) { cout << "나는 자식" <<endl; }
Parents* pObj = new Child 의 경우에, Child의 Name함수를
호출하기 위해 업캐스팅 된 참조변수의 변경이 필요하다.
멤버함수를 호출하기 위해 C++캐스팅을 활용해 보자.
Ø Down Casting 예시 (1)
u C 스타일 캐스팅
- ( ) 안에 캐스팅하고자 하는 클래스의 포인터를 넣어준다.
- C스타일의 캐스팅으로, 정말 강력한 캐스팅이다. 좋은 의미일까? 아니다.
- 가독성을 떨어뜨릴 뿐만 아니라, 컴파일러를 속여 무분별한 캐스팅을 한다면? 상상하고 싶지 않다.
Ø Down Casting 예시 (2)
u C++ 스타일 캐스팅 - reinterpret_cast
- reinterpret_cast<포인터형>(대상) 으로 사용한다.
- C스타일 캐스팅과 유사한 캐스팅이다.
- 강제형변환이 가능한 캐스팅이기 때문에 C스타일 캐스팅처럼 매우 불안한 캐스팅이라 볼 수 있다.
Ø Down Casting 예시 (3)
u C++ 스타일 캐스팅 - dynamic_cast
- dynamic_cast<포인터형>(대상) 으로 사용 한다.
- 상속관계의 캐스팅에서 사용한다.
- 단, 다운캐스팅할 포인터 변수의 대상이 좁은 범위(부모)에서 넓은 범위(자식)로 캐스팅하는 경우 NULL을 반환한다.
으로 pParents 포인터 변수를 받은 경우,
이후, 자식형으로 다운캐스팅을 시도할 경우 NULL값을 반환하므로, 예외처리를 해주면 좋다.
[C++] 상속과 캐스팅(Inheritance & casting)

More Related Content

Featured

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

Featured (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

[C++] 상속과 캐스팅(Inheritance & casting)

  • 1. 상속과 캐스팅 ( Inheritance & Casting ) FaceBook Group "코딩의 아침" Self Study & Sharing
  • 2. Ø 상속관계 "IS - A 상속" CMonster CJump Monster CFly Monster Monster의 기본 속성을 갖고있는 부모의 모든 데이터를 JumpMonster / FlyMonster가 상속받고, 자신의 고유특성인 Jump / Fly 가 새로 추가된 형태 Parents Child Inheritance üJumpMonster is Monster / FlyMonster is Monster 의 관계가 성립된다.
  • 3. Ø 상속관계 "HAS - A 상속" CJump Monster CFly Monster CSteel Spring CAngel Wing 만약, 기본능력으로 생성된 후 JumpMonster는 추진력을 얻기 위해 Spring을 갖고 있어야하고, FlyMonster는 천상계로 가기 위해 천사날개를 얻어야 한다면? ü 모든 몬스터가 +특성을 상속 받는 형태가 아닌, 소유하는 있는 방식의 형태 üJumpMonster has SteelSpring / FlyMonster has AngelWing 의 관계가 성립된다.
  • 4. Ø 상속관계 "Casting이란?" CMonster CJump Monster CFly Monster Parents Child Inheritance - (1) 상속관계에 있는 클래스끼리 형(TYPE)변환이 가능하다. - (2) 부모 포인터(Parents*) 자식 포인터(Child*) 의 참조변수에 따라 사용방식이 달라 진다. Ø Casting방식은 자신이 접근하고자는 유효한 범위에 따라 캐스팅 방식을 선택할 수 있다.
  • 5. Ø 상속관계 "Up Casting" § 하위 클래스에서 상위클래스로 Casting한 경우 § 자식객체 참조를 부모형 포인터로 받은 경우를 말한다. § 다형성(virtual)관계에 있을 경우, 자식의 함수가 호출 된다. Parents Child virtual void Move (void) { cout << "부모움직임" <<endl; } void Name(void) { cout << "나는 부모" <<endl; } virtual void Move (void) { cout << "자식움직임" <<endl; } void Name(void) { cout << "나는 자식" <<endl; } 만약 Parents* pObj = new Child 한 경우 Move함수와 Name함수를 호출한다고 했을때 어떤 결과가 나올까? (호출 x ) (호출 o ) (호출 x ) (호출 o )
  • 6. 모두 자식의 함수가 호출되지 않았다. virtual함수는 오버라이딩에 의해 자식의 함수가 호출되었으나, 자식의 멤버함수 Name( ) 호출되지 않았다. Ø Up Casting 예시
  • 7. Ø 상속관계 "Down Casting" § 상위클래스에서 하위클래스쪽으로 Casting을 하는 경우 § Up캐스팅된 참조변수를 본래의 참조변수로 되돌릴 경우 사용한다. Parents Child virtual void Move (void) { cout << "부모움직임" <<endl; } void Name(void) { cout << "나는 부모" <<endl; } virtual void Move (void) { cout << "자식움직임" <<endl; } void Name(void) { cout << "나는 자식" <<endl; } Parents* pObj = new Child 의 경우에, Child의 Name함수를 호출하기 위해 업캐스팅 된 참조변수의 변경이 필요하다. 멤버함수를 호출하기 위해 C++캐스팅을 활용해 보자.
  • 8. Ø Down Casting 예시 (1) u C 스타일 캐스팅 - ( ) 안에 캐스팅하고자 하는 클래스의 포인터를 넣어준다. - C스타일의 캐스팅으로, 정말 강력한 캐스팅이다. 좋은 의미일까? 아니다. - 가독성을 떨어뜨릴 뿐만 아니라, 컴파일러를 속여 무분별한 캐스팅을 한다면? 상상하고 싶지 않다.
  • 9. Ø Down Casting 예시 (2) u C++ 스타일 캐스팅 - reinterpret_cast - reinterpret_cast<포인터형>(대상) 으로 사용한다. - C스타일 캐스팅과 유사한 캐스팅이다. - 강제형변환이 가능한 캐스팅이기 때문에 C스타일 캐스팅처럼 매우 불안한 캐스팅이라 볼 수 있다.
  • 10. Ø Down Casting 예시 (3) u C++ 스타일 캐스팅 - dynamic_cast - dynamic_cast<포인터형>(대상) 으로 사용 한다. - 상속관계의 캐스팅에서 사용한다. - 단, 다운캐스팅할 포인터 변수의 대상이 좁은 범위(부모)에서 넓은 범위(자식)로 캐스팅하는 경우 NULL을 반환한다. 으로 pParents 포인터 변수를 받은 경우, 이후, 자식형으로 다운캐스팅을 시도할 경우 NULL값을 반환하므로, 예외처리를 해주면 좋다.