What is the purpose of the virtual keyword in C++?To define a function that can be overridden in a derived class.To define a function that cannot be overridden.To declare a function outside of a class.To create a template function.
Question
What is the purpose of the virtual keyword in C++?To define a function that can be overridden in a derived class.To define a function that cannot be overridden.To declare a function outside of a class.To create a template function.
Solution
The purpose of the virtual keyword in C++ is to define a function that can be overridden in a derived class. When a function is declared as virtual in a base class, the function can be redefined in any derived class. This allows for polymorphism, or the ability for objects of different classes related by inheritance to respond differently to the same function call.
Here's a step-by-step explanation:
- Declare a function in the base class as
virtual. This makes the function "overridable" in any class that inherits from this base class.
class Base {
public:
virtual void print() {
cout << "This is the base class." << endl;
}
};
- In the derived class, you can override the
virtualfunction from the base class.
class Derived : public Base {
public:
void print() override { // 'override' keyword is optional but good practice
cout << "This is the derived class." << endl;
}
};
- Now, if you have a pointer or reference to the base class, you can call the
printfunction and it will execute the version of the function that corresponds to the actual object type, not the type of the pointer or reference.
Base* ptr = new Derived();
ptr->print(); // Outputs: "This is the derived class."
In this example, even though ptr is a pointer to Base, the print function of the Derived class is called. This is because print was declared as virtual in the Base class, and then overridden in the Derived class.
Similar Questions
What is the purpose of using the final keyword with a virtual function? (2 Points) a) To prevent the function from being overridden in derived classes. b) To mark the function as static. c) To mark the function as deprecated. d) To make the function a template.
What is the purpose of a pure virtual function in C++?
What is the purpose of a virtual base class in C++?
What are virtual functions?
What is the issue with the following code snippet using virtual functions? #include <iostream> class Base { public: virtual void print() const { std::cout << "Base\n"; } }; class Derived : public Base { public: void print() { std::cout << "Derived\n"; } }; int main() { Base* ptr = new Derived(); ptr->print(); delete ptr; return 0; } (2 Points) a) No issue b) Missing const qualifier c) Incorrect virtual function declaration d) Missing virtual destructor
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.