Knowee
Questions
Features
Study Tools

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

Question

What is the issue with the following code snippet using virtual functions? #include <iostream>

class Base {

public:

virtual void print() const {

    std::cout &lt;&lt; &quot;Base\n&quot;;

}

};

class Derived : public Base {

public:

void print() {

    std::cout &lt;&lt; &quot;Derived\n&quot;;

}

};

int main() {

Base* ptr = new Derived();

ptr-&gt;print();

delete ptr;

return 0;

}

(2 Points)

a) No issue

b) Missing const qualifier

c) Incorrect virtual function declaration

d) Missing virtual destructor

...expand
🧐 Not the exact question you are looking for?Go ask a question

Solution

The issue with the code snippet is option b) Missing const qualifier. In the Base class, the print function is declared as const, which means it promises not to modify any class members. In the Derived class, the print function is not declared as const, which means it could potentially modify class members. This discrepancy between the Base and Derived print functions means that the Derived print function does not properly override the Base print function. To fix this issue, you should declare the print function in the Derived class as const, just like in the Base class.

This problem has been solved

Similar Questions

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

Which of the provided options is the correct way to declare a pure virtual function?

What is the purpose of a pure virtual function in C++?

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.

1/2

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.