Const Variablen und Methoden in Klassen

Sorgfältige Verwendung const ist wichtig bei Klassen und Objekten (bei bisherigen Beispielen wurde der Einfachheit halber darauf verzichtet).


// My3Vector declarations with const specifiers for arguments and methods
class My3Vector {
 private:        // coordinates, hidden
  double x;
  double y;
  double z;
 public:  
  My3Vector(); // default constructor
  My3Vector(const double c1, const double c2, const double c3);// Other constructor
  // methods:
  // get length of vector
  double Length() const;
  // access elements
  double X() const;
  double Y() const;
  double Z() const;
  // add
  My3Vector Add( const My3Vector & p ) const;
  // scale with double
  void Scale( const double a ) {
    x *= a;  y *= a;  z *= a; 
  };
};



Const Correctness - Motivation

Zitat Herb Sutter:
``Safety-incorrect riflemen are not long for this world. Nor are const- incorrect programmers, carpenters who don’t have time for hard hats, and electricians who don’t have time to identify the live wire. There is no excuse for ignoring the safety mechanisms provided with a product, and there is no excuse for programmers too lazy to write const-correct code.''


Objektübergabe als Referenz bei Methodenaufruf

Wenn Objekte als Argumente bei Aufruf von Funktionen oder Methoden übergeben werden empfiehlt es sich dringend die Objekt-Variable in der Funktions-Deklaration als Referenz anzugeben, also nicht call-by-value
My3Vector Add(My3Vector p ) ;
sondern
My3Vector Add(My3Vector & p );
oder noch besser mit const:
My3Vector Add(const My3Vector & p ) const;

Unterschied:


GDuckeck 2019-08-01