[C++] 동적 바인딩
Updated:
개요
- 런타임에 동작을 결정
예제
- 코드
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; class Base { public: Base(){}; virtual ~Base() {} virtual void func() { cout << "Base::func call" << endl; } }; class Derived : public Base { public: Derived() : Base(){}; virtual ~Derived() {} virtual void func() override { cout << "Derived::func call" << endl; } }; int main() { const int number = time(NULL) % 2; cout << number << endl; Base *base = NULL; if (number) { base = new Base; } else { base = new Derived; } base->func(); if (base != NULL) { delete base; base = NULL; } return 0; }
- 실행 결과 1
0 Derived::func call
- 실행 결과 2
1 Base::func call