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/#/
-
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...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
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 ...
No comments:
Post a Comment