Scientific programming in C++

C++ Notes

by Nikolai Shokhirev

Up Scientific Programming

Tips

BOOST.

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 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;
}

 

 

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

 

Up Scientific Programming
Programming toolsScientific programming | Sample code

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

ŠNikolai V. Shokhirev, 2004-2008