Virtual function in c++(dynamic binding)

taehee kim·2021년 6월 12일
0

1. Up casting

:기반클래스의 포인터 변수로 파생 클래스의 주소를 입력 받는것. 기반 클래스의 포인터가 참조할 수 있는 영역이 파생 클래스에 비해 좁기 때문에 포인터 영역 참조에서 문제가 생기지 않는다.
다만, 파생 클래스에서 추가된 메서드에 접근 할 수 없으므로 overriding시에 항상 기반 클래스의
메서드가 call 된다.

2. virtual function

:1의 upcasting에서 생기는 문제를 해결하기위해(주로 overriding된 파생 클래스의 메서드를 호출) 사용하는 keyword가 virtual keyword이다. virtual keyword를 사용할 시 up casting 후 메서드를 콜 했을 때 파생 클래스의 overriding된 클래스가 적절히 call된다.
원리는 원래 어떤 함수를 call할지는 compile time 에 정해지는 반면에 virtual fuction은 run time에 결정되기 때문이다. 즉, 기반 포인터 자료형을 보고 어떤 함수를 call할지 결정하지 않고(compile시간에 일어나는 일) 실제 대입된 주소값을 보고 (run time이 되어야 결정됨.) 어떤 클래스의 메서드를 호출할지 결정한다.

3. static bind vs dynamic bind

static bind : When type of the object is determined at compiled time(by the compiler), it is known as static binding.

dynamic bind : When type of the object is determined at run-time, it is known as dynamic binding.
객체를 선택하는 시간 여부에 따라 나뉜다.

4.dynamic bind(late bind) vs dynamic dispatch

:bind 는 객체 관점이고 dispatch는 function(subroutine)관점이다. 정확하게는 c++에서 virtual method를 쓰는 것은 dynamic dispatch에 가깝다고 한다.

출처:https://stackoverflow.com/questions/20187587/what-is-the-difference-between-dynamic-dispatch-and-late-binding-in-c/20187789#:~:text=Dynamic%20dispatch%20is%20different%20from,operation%20a%20name%20refers%20to.

profile
Fail Fast

0개의 댓글