Virtual function will be realized after the it is called according to the object associated with it
Non virtual function will be realized by the compiler before the function is called.
See the program below:
#include <iostream>
using namespace std;
class A {
public:
void move(){
cout<<"move A"<<endl;
}
virtual void print(){
cout<<"I am A"<<endl;
};
};
class B : public A {
public:
void move(){
cout<< "move B"<< endl;
}
void print(){
cout<<"I am B"<<endl;
}
};
class C : public A {
public:
void move(){
cout<<"move C"<<endl;
}
void print(){
cout<<"I am C"<<endl;
}
};
int main(){
A a, *pa = &a;;
pa->print();
B b, *pb = &b;
C c, *pc = &c;
cout<<endl;
pb->move();
((A*)pb)->move();
cout<<endl;
pb->print();
((A*)pb)->print();
cout<<endl;
pc->print();
((A*)pc)->print();
cout<<endl;
A* array[] = {&a,&b,&c};
int len = 3;
for(int i = 0; i < len; i++){
array[i]->print();
}
cout<<endl;
for(int i = 0; i < len; i++){
array[i]->move();
}
return 0;
}
The running result is listed as:
I am A
move B
move A
I am B
I am B
I am C
I am C
I am A
I am B
I am C
move A
move A
move A
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Given two words ( start and end ), and a dictionary, find the length of shortest transformation sequence from start to end , such tha...
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, ...
No comments:
Post a Comment