Object-Oriented Programming in C++

Code display of PL4/class5.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// PL4/class5.cpp
// An example using a vector of objects
// Niels Walet, last updated 04/12/2019
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
using namespace std;
class particle
{
private:
  string type;
  double mass;
  double momentum;
  double energy;
public:
// Default constructor
  particle() : type{"Ghost"}, mass{}, momentum{}, energy{}  {}
// Parameterized constructor
  particle(string particleType, double particleMass, double particleMomentum) :
    type{particleType}, mass{particleMass}, momentum{particleMomentum},
    energy{sqrt(particleMass*particleMass+particleMomentum*particleMomentum)}
  {}
  ~particle(){cout<<"Destroying "<<type<<endl;}  // Destructor
  double gamma() {return energy/mass;}
  void print_data();
};
 
void particle::print_data()
{
  cout.precision(3); // 2 significant figures
  cout<<"Particle: [type,m,p,E] = ["<<type<<","<< mass
       <<","<<momentum<<","<<energy<<"]"<<endl;
  return;
}
 
int main()
{
  vector<particle> particle_data;
  particle_data.push_back(particle("electron",5.11e5,1.e6));
  particle_data.push_back(particle("proton",0.938e9,3.e9));
  //vector<particle>::iterator particle_it;
  for(auto particle_it=particle_data.begin();
      particle_it<particle_data.end();
      ++particle_it){
    particle_it->print_data();
    cout<<"has Lorentz factor gamma="<<particle_it->gamma()<<endl;
  }
  return 0;
}
Download here; To copy and paste: double click inside code, then copy.