Scientific programming

C++ Notes

by Nikolai Shokhirev

Work in progress

Up Scientific Programming

Up: Scientific programming
Previous: CppMatLib - Introduction
Next: C++ notes, tips

Tips

BOOST in VS 2005.

Overloading Derived Class Assignment  

Ref [1] :

//--- file Parent.h
class Parent {...}; // declaration of base class

//--- file Child.h
#include "Parent.h"
class Child : public Parent { // declaration of derived class
  public:
    Child& Child::operator=(const Child& source);
};//end class Child

//--- file Child.cpp
#include "Child.h"
Child& Child::operator=(const Child& source) {
  if (this != &source) {
  this->Parent::operator=(source);
  . . . // copy all our own fields here.
  }
  return *this;
}//end operator=
Ref [2, 3] :
   Child::operator= (d);

or through an actual assignment [2] :

   ((Child&) *this) = d;

Ref [4] :

class TFoo : public TSuperFoo {
    TBar* fBar1;
    // various method definitions go here...
}
TFoo::~TFoo()
{
    delete fBar1;
}
TFoo& TFoo::operator=(const TFoo& that)
{
    if (this != &that) {
        TBar* bar1 = 0;

        try {
            bar1 = new TBar(*that.fBar1);
        }
        catch (...) {
            delete bar1;
            throw;
        }

        TSuperFoo::operator=(that);
        delete fBar1;
        fBar1 = bar1;
    }
    return *this;
}

Better solution is to use = of TBar (if TBar is monomorphic)

TFoo& TFoo::operator=(const TFoo& that)
{
    TSuperFoo::operator=(that);
    *fBar1 = *(that.fBar1);
    *fBar2 = *(that.fBar2);

    return *this;
}

 

Stopwatch [5]

#include <vector>
#include <ctime>
#include <iostream>
using namespace std;

class stopwatch
{
  public:
    stopwatch() : start(std::clock()){} //start counting time
    ~stopwatch();
  private:
     std::clock_t start;
};

  stopwatch::~stopwatch()
  {
     clock_t total = clock()-start; //get elapsed time
     cout << "total of ticks for this activity: " << total << endl;
     cout << "in seconds: " << double(total)/CLOCKS_PER_SEC << endl;
  }

  int main()
  {
     vector<int> v(1000000);
     {
       stopwatch sw; // start measuring time
       for (int i=0; i<1000000.i++) v[i] = i*1234;
     } // sw goes out of scope, ~stopwatch() is called

     return 0;
  }

 

Peferences

  1. http://www.fredosaurus.com/notes-cpp/oop-overloading/overloadassign2.html
  2. http://www.acm.org/crossroads/xrds1-4/ovp.html
  3. Introduction to C++ for Financial Engineers: An Object-Oriented Approach by Daniel J. Duffy
  4. The Anatomy of the Assignment Operator by Richard Gillam
  5. Using class stopwatch for Performance Measurements  by Danny Kalev

  6.  

 

Up Scientific Programming

Up: Scientific programming
Previous: CppMatLib - Introduction
Next: C++ notes, tips

Programming toolsScientific programming | Sample code

Home | Resumé |  Shokhirev.com |  Computing |  Links |  Publications

©Nikolai Shokhirev, 2004-2008