Thursday, October 10, 2013

One example explaining the virtual function

 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

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/