in Cpp
when the reference of parent class points to child class object,the reference can not directly invoke child-class-specific methods;To address the limitation,virtual function were intorduced;By prefixing parent-class-method with vitrual keyword,these methods become overridable,allowing child class to override them and enable dynamic dispatch based on the object’s actual type at runtime;
A prime example in cpp
#include <iostream>
using namespace std;
class Animal {
public:
virtual void eat() {
cout << "animal eating" << endl;
}
};
class Dog : public Animal {
public:
void eat() override { //override keyword is optional,adding "override" is explicit,and the opposite is implicit;
cout << "dog eating bone" << endl;
}
}; // 类定义结束需要分号
int main() {
Animal* dog = new Dog();
dog->eat(); //dog eating bone
delete dog; // 释放内存(实际开发中建议用智能指针)
return 0;
}
-
Unlike c++ ,java achieve the same effect in polymorphism obly by using the “@override” keyword;
-
A prime example in Java
public class test{
public static class Animal{
public void eat(){
System.out.println("animal is eatind");
}
}
public static class Dog extends Animal{
@Override
public void eat(){
System.out.println("Dog is eating");
}
}
public static void main(String args[]){
Animal dog=new Dog();
dog.eat(); //Dog is eating
}
}
Weather in java or c++,there are must no limitate keywords such as "private","final","protected" in front of virtual funtion