Programming/C++ STL2026. 2. 20. 16:30

sx1276 예제를 보다보니 mbed쪽(?) 드라이버 소스에 함수인데 "= 0"를 해둔게 있어서 이게 머야 하고 검색해보니

순수 가상 함수라는 이상한(?) 이름이 붙은 녀석이 발견되었다.

어떻게 보면 java에서 interface 로 선언되는 녀석과 비슷하게 실 구현체가 없이 선언되고

무조건 구현해서 사용해야 하는 녀석 같은데.. 참 난해한 문법형태구만..

그런데 cpp에 원래 virtual 키워드가 있었던..가?

 

    /*!
     * @brief Checks if the given RF frequency is supported by the hardware
     *
     * @param [IN] frequency RF frequency to be checked
     * @retval isSupported [true: supported, false: unsupported]
     */
    virtual bool CheckRfFrequency( uint32_t frequency ) = 0;

[링크 : https://hwan-shell.tistory.com/223]

[링크 : https://www.geeksforgeeks.org/cpp/pure-virtual-functions-and-abstract-classes/]

 

 

// deriv_VirtualFunctions2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Base {
public:
   virtual void NameOf();   // Virtual function.
   void InvokingClass();   // Nonvirtual function.
};

// Implement the two functions.
void Base::NameOf() {
   cout << "Base::NameOf\n";
}

void Base::InvokingClass() {
   cout << "Invoked by Base\n";
}

class Derived : public Base {
public:
   void NameOf();   // Virtual function.
   void InvokingClass();   // Nonvirtual function.
};

// Implement the two functions.
void Derived::NameOf() {
   cout << "Derived::NameOf\n";
}

void Derived::InvokingClass() {
   cout << "Invoked by Derived\n";
}

int main() {
   // Declare an object of type Derived.
   Derived aDerived;

   // Declare two pointers, one of type Derived * and the other
   //  of type Base *, and initialize them to point to aDerived.
   Derived *pDerived = &aDerived;
   Base    *pBase    = &aDerived;

   // Call the functions.
   pBase->NameOf();           // Call virtual function.
   pBase->InvokingClass();    // Call nonvirtual function.
   pDerived->NameOf();        // Call virtual function.
   pDerived->InvokingClass(); // Call nonvirtual function.
}

 

부모 클래스로 바꾸어서 실행해도 virtual 로 선언된 함수는 무조건 자기 자신의 원래 함수를 호출한다.

내가 누구인지 타입 캐스팅이 되어도 원래꺼를 따라가니 일종의 메타데이터를 가지고 있는걸려나?

Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived

[링크 : https://learn.microsoft.com/ko-kr/cpp/cpp/virtual-functions?view=msvc-170]

[링크 : https://mr-dingo.github.io/c/c++뽀개기/2019/01/10/virtual.html]

'Programming > C++ STL' 카테고리의 다른 글

crt0.o libstdc++.a  (0) 2025.08.12
cpp 그래픽 라이브러리  (0) 2025.04.22
cpp 기본 인자 prototype  (0) 2025.03.28
cpp std::to_string(int)  (0) 2025.02.20
cpp string 끝에 한글자 지우기  (0) 2025.02.06
Posted by 구차니