---
id: cpp-virtual-functions
title: "C++ Virtual Functions"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["virtual keyword", "override keyword", "pointer type vs object type", "C++ 가상 함수"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["cpp", "programming-language", "w3schools", "oop", "virtual-functions", "polymorphism"]
raw_sources: ["https://www.w3schools.com/cpp/cpp_virtual_functions.asp"]
applied_in: []
github_commit: ""
---

# [[CPP Virtual Functions]]

## 🎯 한 줄 통찰 (One-line insight)
Without the `virtual` keyword, a base-class pointer calls the function based on its DECLARED TYPE (`Animal*`), completely ignoring what it actually POINTS TO (a `Dog` object) — the source's own example proves this: `Animal* a = &d;` (where `d` is a `Dog`) still calls `Animal::sound()`, not `Dog::sound()`, UNTIL `virtual` is added to the base method, at which point the SAME pointer-based call correctly resolves to the actual object's type — meaning polymorphism through pointers doesn't work AT ALL by default in C++, and `virtual` is the specific opt-in required to make it happen. [S1]

## 🧠 핵심 개념 (Core concepts)
- **Virtual function** — a base-class member function that CAN be overridden in derived classes and resolved based on the ACTUAL object, not the pointer's declared type. [S1]
- **Without `virtual`** — a base-class pointer always calls the BASE class's version of a method, even if it points to a derived-class object. [S1]
- **With `virtual`** — the SAME pointer call now resolves to the DERIVED class's overridden version — this is how runtime polymorphism actually works in C++. [S1]
- **`override` keyword** — optional but recommended in the derived class, for clarity (documents that this method is intentionally overriding a virtual base method). [S1]
- **`->` operator** — accesses members through a pointer; shorthand for `(*pointer).member`. [S1]

## 📖 세부 내용 (Details)
- Without virtual — the base class's version runs despite the pointer pointing to a Dog: `class Animal { public: void sound() { cout << "Animal sound\n"; } }; class Dog : public Animal { public: void sound() { cout << "Dog barks\n"; } }; Animal* a; Dog d; a = &d; a->sound(); // "Animal sound" — WRONG, ignores actual object type`. [S1]
- With virtual — the derived class's version correctly runs: `class Animal { public: virtual void sound() { cout << "Animal sound\n"; } }; class Dog : public Animal { public: void sound() override { cout << "Dog barks\n"; } }; Animal* a; Dog d; a = &d; a->sound(); // "Dog barks" — CORRECT`. [S1]
- The `->` shorthand explained: `Animal* a = new Animal(); a->sound(); // same as (*a).sound();`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **virtual 없이는 포인터 기반 다형성이 전혀 작동하지 않음**: Animal 포인터가 실제로는 Dog 객체를 가리키고 있어도 virtual이 없으면 항상 Animal::sound()가 호출된다는 점이 직접 예제로 증명됨 — virtual을 붙여야만 실제 객체 타입 기반으로 올바르게 해석됨. [S1]

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — 베이스 클래스 포인터로 파생 클래스 객체를 가리키고 올바른 오버라이드 메서드가 호출되도록 하는 것이 실전 다형성 구현의 핵심 요구사항이다. [S1]

## 💻 코드 패턴 (Code patterns)
virtual making a base-class pointer correctly resolve to the derived class's overridden method (C++):
```cpp
class Animal {
public:
  virtual void sound() { cout << "Animal sound\n"; }
};
class Dog : public Animal {
public:
  void sound() override { cout << "Dog barks\n"; }
};
int main() {
  Animal* a;
  Dog d;
  a = &d;
  a->sound(); // Outputs: Dog barks (correct, thanks to virtual)
  return 0;
}
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[C++ Tutorial]]
- **관련 개념:** [[CPP Polymorphism]], [[CPP Pointers]], [[CPP Friend Function]]
- **참조 맥락:** 가상 함수 — friend 함수(Friend Function) 챕터로 이어짐.

## 📚 출처 (Sources)
- [S1] W3Schools — C++ Virtual Functions — https://www.w3schools.com/cpp/cpp_virtual_functions.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ Virtual Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
