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 an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, ...
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
-
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...
No comments:
Post a Comment