Dynamic binding에 대해서.

yann8166의 이미지

아래와 같은 구조에서 ( AAA를 BBB가 상속했으며 virtual fct()함수는 오버라이딩 되어 있는 상태 )

class AAA
{
virtual void fct();
}

class BBB : public AAA
{
virtual void fct();
}

main()
{
BBB b;
b.fct(); // static binding

AAA* a = new BBB; ------ (1)
a->fct(); // dynamic binding ------ (2)
}

(2)번의 경우 a가 호출하는 fct를 결정하는 것은

컴파일시간이 아닌 실행시간에 결정 된다고 해서 dynamic binding이라고 하는데요

컴파일 시간에 결정되는 이유가 (1)에서 BBB를 new로 할당해서 (new가 실행시간에 메모리 할당하므로) 인건가요?

그렇다면
AAA* a = new BBB를
AAA* a = &b 로 대체하면
a가 가리키는 BBB클래스의 객체가 컴파일 시간에 할당 크기를 정하므로

static binding이 되는 건가요?

익명 사용자의 이미지

All the virtual functions are dynamically-bound. This means that to invoke a virtual function, it needs to follow a function pointer in the virtual function table.

Since compilers do all sort of optimizations, it might be possible that some of the virtual functions are optimized to be statically-bound, but in general, consider all the virtual functions use dynamic binding.