object Slicing
Q) vector<Shape>에 파생 클래스를 담으면 어떻게 될까?
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
int num;
public:
virtual void draw() { cout << "shape..." << endl; }
};
class Rect : public Shape
{
int h, w;
public:
virtual void draw() { cout << "rect..." << endl; }
};
int main()
{
std::vector<Shape> v;
Shape s; v.push_back(s);
Rect d1; v.push_back(d1);
Rect d2; v.push_back(d2);
for (auto i : v)
{
i.draw(); // ???
}
}
파생 클래스 Rect 담아주었지만 Shape draw()가 호출되었다.
이는 vector<Shape>에서 Shape 타입만 보관하고 있다.
Q) vector<Shape>와 vector<Shape*> 무슨 차이가 있을까?
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
int num;
public:
virtual void draw() { cout << "shape..." << endl; }
};
class Rect : public Shape
{
int h, w;
public:
virtual void draw() { cout << "rect..." << endl; }
};
int main()
{
std::vector<Shape> v1;
std::vector<Shape*> v2;
}
std::vector<Shape> v1; 에서는 객체 값을 담고 있고
std::vector<Shape*> v2; 객체 포인터를 담아주고 있다.
부모-자식 upcasting에서는 내부적으로 어떻게 동작할까?
[C++] Upcasting
Upcasting• 기반 클래스 포인터로 파생 클래스 객체를 가리킬 수 있다.• 기반 클래스 포인터로는 기반 클래스 멤버만 접근 가능• 파생 클래스 접근하려면 static_cast 필요 [예제] upcasting 이란class
zoosso.tistory.com
[예제]
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
int num;
public:
virtual void draw() { cout << "shape..." << endl; }
};
class Rect : public Shape
{
int h, w;
public:
virtual void draw() { cout << "rect..." << endl; }
};
void foo(Shape* p, Shape& r, Shape s) // 포인터, 참조, 값 복사
{
p->draw(); // ??? - 1
r.draw(); // ??? - 2
s.draw(); // ??? - 3
}
int main()
{
Rect r;
foo(&r, r, r);
}
① , ②: "Rect"
③: Shape
① 포인터 이므로 만들어진 객체를 가리킨다.
② 참조 연산자로 원본 자체를 가리킨다.
③ call by value 방식에서는 복사본 객체 생성되는데
object slicing 되어 Shape 객체가 전달된다.
📌 [C++] 가상 함수 (virtual funciton)
[C++] 가상 함수 (virtual funciton)
가상 멤버 함수 (virtual function)동적 바인딩을 위해 사용class A{public: virtual void sub(void);}; [예제] 함수 재정의(overriding) 주의사항#include class Animal{public: void Cry() { std::cout Cry(); // ??? -> Dog? Animal?}Q) p-
zoosso.tistory.com
[C++] 레퍼런스 Reference
레퍼런스 (reference, 참조)이미 존재하는 변수에 추가적인 별칭 부여#include int main(){ int n = 10; int& r = n; r = 20; // 값 변경 std::cout C 언어에서는 void swap(int* p1, int* p2) 와 같이call by pointer 방식을 사
zoosso.tistory.com
'프로그래밍 언어 > C++' 카테고리의 다른 글
[C++] dynamic_cast (1) | 2025.03.03 |
---|---|
[C++] 인터페이스(Interface) (5) | 2025.03.02 |
[C++] RTTI (Run-Time Type Information) (3) | 2025.02.28 |
[C++] 가상함수와 디폴트 파라미터 (1) | 2025.02.27 |
[C++] 추상 클래스 (abstract class) (1) | 2025.02.26 |
댓글