다음을 통해 공유


가상 함수에 대한 액세스

가상 함수에 적용되는 액세스 제어는 함수 호출 시 사용된 형식에 따라 결정됩니다. 함수의 선언 재정의는 지정된 형식에 대한 액세스 제어에 영향을 주지 않습니다. 예를 들면 다음과 같습니다.

// access_to_virtual_functions.cpp
class VFuncBase
{
public:
    virtual int GetState() { return _state; }
protected:
    int _state;
};

class VFuncDerived : public VFuncBase
{
private:
    int GetState() { return _state; }
};

int main()
{
   VFuncDerived vfd;             // Object of derived type.
   VFuncBase *pvfb = &vfd;       // Pointer to base type.
   VFuncDerived *pvfd = &vfd;    // Pointer to derived type.
   int State;

   State = pvfb->GetState();     // GetState is public.
   State = pvfd->GetState();     // C2248 error expected; GetState is private;
}

앞의 예제에서 VFuncBase 형식에 대한 포인터를 사용하여 GetState 가상 함수를 호출하면 VFuncDerived::GetState가 호출되며, GetState는 public으로 취급됩니다. 그러나 GetState가 VFuncDerived 클래스에서 private로 선언되기 때문에 VFuncDerived 형식에 대한 포인터를 사용하여 GetState를 호출하는 것은 액세스 제어 위반이 됩니다.

경고

가상 함수 GetState는 기본 클래스 VFuncBase에 대한 포인터를 사용하여 호출할 수 있습니다.이는 호출된 함수가 해당 함수의 기본 클래스 버전임을 의미하지는 않습니다.

참고 항목

참조

멤버 액세스 제어