-
C++ Study. final, overridec++ 2024. 1. 21. 16:46
final
용도1: 자신의 가상함수를 자식클래스들이 override하지 못하도록 해줌
사용법1
#include <iostream> using namespace std; // 부모 class Base { public: virtual void myfun() final { cout << "myfun() in Base"; } }; // 자식 class Derived : public Base { void myfun() { cout << "myfun() in Derived\\n"; } }; int main() { Derived d; Base &b = d; b.myfun(); return 0; } // Output: prog.cpp:14:10: error: virtual function ‘virtual void Derived::myfun()’ void myfun() ^ prog.cpp:7:18: error: overriding final function ‘virtual void Base::myfun()’ virtual void myfun() final
용도2: 클래스나 구조체의 상속을 막는 역할
사용법2
#include <iostream> // 부모 class Base final { }; // 자식 class Derived : public Base { }; int main() { Derived d; return 0; } // Output: error: cannot derive from ‘final’ base ‘Base’ in derived type ‘Derived’ class Derived : public Base
장점
- 컴파일러 최적화 - devirtualization
원래 가상함수 찾으려면 vtable이라는 가상함수테이블을 거쳐서 실제 함수 구현부로 가야하는데,
final 붙으면 바로 함수 구현부로 간다 → 반가상화(devirtualization)
예시
class IAbstract { public: virtual void DoSomething() = 0; }; class CDerived : public IAbstract { void DoSomething() final { m_x = 1 ; } void Blah( void ) { DoSomething(); } };
DoSomething에 final 붙었을 때: Blah 호출하면 CDerived::DoSomething() 이런식으로 직접 호출됨(direct call)
final 없을 때: vtable 거침
override
C++11 이후부터는 파생 클래스에서 기본 클래스의 가상 함수를 오버라이드하는 경우, override 키워드를 통해서 명시적으로 나타낼 수 있다.
class Base { public: Base() : s("Base") { std::cout << "Contructor of Base Class\\n"; }; virtual void what() { std::cout << "--- Base Class의 what ---\\n"; } private: std::string s; }; class Derived : public Base { public: Derived() : s("Derived"), Base() { std::cout << "Constructor of Derived Class\\n"; } void what() override { std::cout << "--- Derived Class의 what ---\\n"; } private: std::string s; };
https://stackoverflow.com/questions/37414995/is-final-used-for-optimization-in-c/37415241#37415241
'c++' 카테고리의 다른 글
C++ Study. move assignment operator (0) 2024.01.21 C++ Study. stl unordered_set (0) 2024.01.21 C++ 스터디. standard template library (1) 2024.01.21 C++ Primer CH15. Object-Oriented Programming (0) 2024.01.21 C++ Primer CH13. Copy Control (0) 2024.01.21