Call virtual functions during construction or destruction

For c++, virutal funciton invocation during construction or destruction use virtual funcitons defined in base classes. Here is an example.

#include <iostream>
using namespace std;

class Transaction {
  public:
    Transaction() {
      logTransaction();
    }
    virtual void logTransaction() {
     cout << "Transaction logTransaction" << endl;
    } 
};


class BuyTransaction: public Transaction {
  public:
    virtual void logTransaction() const;
};

void BuyTransaction::logTransaction() const {
  cout << "BuyTransaction logTransaction" << endl;
}

int main(int argc, const char *argv[])
{
  BuyTransaction b; 
  return 0;
}

 For Java, overridable method invocation during construction use method defined in sub class.

import java.util.*;

class Super {
  // Broken - constructor invokes an overrided method
  public Super() {
    overrideMe();
  }
  public void overrideMe() {
  }
}

final class Sub extends Super {
  private final Date date; // Blank final, set by constructor

  Sub() {
    date = new Date();
  }

  // Overriding method invoked by superclass constructor
  @Override
  public void overrideMe() {
    System.out.println(date);  
  }
}

public class Foo {
  public static void main (String [] args)  {
    Sub s = new Sub();
  }
}
 

 

你可能感兴趣的:(java,C++,c,C#)