Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Type Conversion C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Mgmt

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Destructors C++ The this Pointer C++ Access Specifiers C++ Encapsulation C++ Friend Functions C++ Inheritance C++ Polymorphism C++ Operator Overload C++ Templates

C++ Files

C++ Files

C++ Date

C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions C++ Input Validation

C++ Problem Solving

C++ Problem Solving C++ Build the Logic C++ Test Cases

C++ Projects

C++ Projects

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Unordered Map C++ Unordered Set C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Cert

C++ Certificate

C++ How To

C++ How Tos

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Code Challenges C++ Practice Problems C++ Syllabus C++ Study Plan C++ Interview Q&A

C++ Reference

C++ Reference C++ Keywords C++ <algorithm> C++ <cctype> C++ <cmath> C++ <cstdlib> C++ <cstring> C++ <ctime> C++ <deque> C++ <fstream> C++ <iomanip> C++ <iostream> C++ <list> C++ <map> C++ <memory> C++ <queue> C++ <random> C++ <set> C++ <sstream> C++ <stack> C++ <stdexcept> C++ <string> C++ <unordered_map> C++ <unordered_set> C++ <vector>


C++ Virtual Functions


Share

C++ Virtual Functions

A virtual function is a member function in the base class that can be overridden in derived classes.

Virtual functions are a key part of polymorphism in C++. They let different objects respond differently to the same function call.


Why Use Virtual Functions?

Without virtual, C++ decides which function to call based on the pointer type, not the actual object type.

With virtual, it checks the actual object the pointer is pointing to.

Or to put it even more simply:

  • Without virtual: the base function runs, even if the object is from a child class.
  • With virtual: the child's version runs, like you expect.

Without Virtual Function

Example (No virtual keyword)

class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound\n";
    }
};

class Dog : public Animal {
  public:
    void animalSound() {
      cout << "The dog says: bow wow\n";
    }
};

int main() {
  Dog myDog;
  Animal* a = &myDog;  // A pointer to the base class (Animal), pointing to a Dog
  a->animalSound();    // animalSound() is not virtual, so this calls Animal's version
  return 0;
}
Try it Yourself »

This is the Animal and Dog example from the Polymorphism chapter. But this time, we call animalSound() through a pointer to the base class.

Even though a points to a Dog, it still calls Animal's animalSound(), because the function is not virtual.



With Virtual Function

Example (With virtual keyword)

class Animal {
  public:
    virtual void animalSound() {
      cout << "The animal makes a sound\n";
    }
};

class Dog : public Animal {
  public:
    void animalSound() override {
      cout << "The dog says: bow wow\n";
    }
};

int main() {
  Dog myDog;
  Animal* a = &myDog;
  a->animalSound();  // The dog says: bow wow
  return 0;
}
Try it Yourself »

Now it works! Because animalSound() is virtual, the call uses the actual object's function and not just the pointer type.

  • Use virtual only in the base class
  • Use override (optional, but recommended) in the derived class for clarity

The -> Operator in C++

You learned about the -> operator in The this Pointer chapter. That is why the examples above use ->: a is a pointer, not an object.

The -> operator is used to access members (like functions or variables) through a pointer.

It's a shortcut for writing (*pointer).member:

Dog myDog;
Animal* a = &myDog;
a->animalSound();  // Same as (*a).animalSound();

Tip: If you are using a pointer to an object, use -> to access its members.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.