Thursday, October 10, 2013

understand pure virtual function, abstract class, and virtual function.

See the following program:

#include <iostream>
using namespace std;


class MathSymbol {
public:
  virtual void doOperation() = 0; // pure virtual class, so MathSymbol is a abstract class
  virtual void print(){
    cout<<"print MathSymbol"<<endl;
  }
  void move(){
    cout<<"move MathSymbol"<<endl;
  }
};

class B : public MathSymbol {
public:
  void doOperation(){
    cout<<"Operation in B"<<endl;
  }
  void print(){
    cout<<"print B"<<endl;
  }
  void move(){
    cout<<"move B"<<endl;
  }
};


class C : public MathSymbol {
public:
  void doOperation(){
    cout<<"Operation in C"<<endl;
  }

  void print(){
    cout<<"print C"<<endl;
  }
  void move(){
    cout<<"move C"<<endl;
  }
};


int main(){
  // MathSymbol a; // this is error. because MathSymbol is abstract.
  MathSymbol *pa = NULL;

  B b, *pb = &b;
  C c, *pc = &c;

  MathSymbol* array[] = {pb,pc};
  int len = 2;

  for(int i = 0; i < len; i++){
    array[i] -> doOperation();
  }

  for(int i = 0; i < len; i++){
    array[i] -> print();
  }

  for(int i = 0; i < len; i++){
    array[i] -> move();
  }
  return 0;
}

Its running result is:

Operation in B
Operation in C
print B
print C
move MathSymbol
move MathSymbol





No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

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