This article is a detailed example demonstration of const modifying virtual functions in C++. I hope that through the introduction of the editor of the Wrong New Technology Channel, we can thoroughly grasp how to use it. Friends in need can refer to the following.
Detailed explanation of the instance of const modified virtual function in C++
【1】Program 1
#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print();};void Test::print(){ cout << "Test::print()" << endl;}void main(){ // Base* pChild = new Test(); // compile error! // pChild->print();}【2】Program 2
#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print(); void print() const;};void Test::print(){ cout << "Test::print()" << endl;}void Test::print() const{ cout << "Test::print() const" << endl;}void main(){ Base* pChild = new Test(); pChild->print();}/*Test::print() const*/【3】Program 3
#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print(); void print() const;};void Test::print(){ cout << "Test::print()" << endl;}void Test::print() const{ cout << "Test::print() const" << endl;}void main(){ Base* pChild = new Test(); pChild->print(); const Test obj; obj.print(); Test obj1; obj1.print(); Test* pOwn = new Test(); pOwn->print();}/*Test::print() constTest::print() constTest::print() constTest::print() Test::print()*/Note: Everything is in the code.
Summary: Const modify member functions, which also belongs to a category of function overloading.
Thank you for reading the detailed explanation of the example demonstration of const modifying virtual functions in C++. I hope it can help you. At the same time, I would like to thank you for your support from the new technology channel right or wrong!