Files
2nd/10_Wiki/Dev/Topic_CPP/CPP_Virtual_Functions.md
T
Antigravity Agent 1cfd3bbb56 docs(10_Wiki): 위키 구조 정리 — 언어 튜토리얼 카테고리 폴더 제거 + 신규 자산 동기화
Topic_CSS/Topic_HTML/Topic_JavaScript/Topic_Prompt/Topic_Comfyui 등 기존 카테고리 폴더를 정리하고,
Topic_Graphic/Dev 등 신규 산출물과 Topics 내부 세션/메모리 기록을 동기화.
2026-07-05 00:10:59 +09:00

4.7 KiB

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

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++):

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)

📚 출처 (Sources)

📝 변경 이력 (Change history)

  • 2026-07-04: Initial draft synthesized from the W3Schools "C++ Virtual Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).