I want the Print()
function, declared virtual in the base class ParticleType
, to print on screen, other than the correct values for mass_
and charge
the correct value for width
. The function works as intended for the base class. Here is my code :
ParticleType.h
#ifndef PARTICLETYPE_H
#define PARTICLETYPE_H
#include <iostream>
class ParticleType {
public:
ParticleType(char name, double mass, int charge) ;
ParticleType() ;
char Getname() const ;
double Getmass() const ;
int Getcharge() const ;
virtual double Getwidth() const ;
virtual void Print() const ;
private:
char const name_ ;
const double mass_ ;
const int charge_;
} ;
#endif
ParticleType.C
#include "ParticleType.h"
ParticleType::ParticleType(char name, double mass, int charge) :
name_{name} , mass_{mass} , charge_{charge} {};
ParticleType::ParticleType() :
name_{'v'} , mass_{0} , charge_{0} {} ;
char ParticleType::Getname() const {
return name_ ;
}
double ParticleType::Getmass() const {
return mass_;
}
int ParticleType::Getcharge() const {
return charge_ ;
}
double ParticleType::Getwidth() const {
return 0;
}
void ParticleType::Print() const {
std::cout << "Name: " << Getname() << " Mass: " << Getmass() << " Charge: " << Getcharge()
<< '\n';
}
ResonanceType.h
#ifndef RESONANCETYPE_H
#define RESONANCETYPE_H
#include "ParticleType.h"
class ResonanceType : virtual public ParticleType {
public :
ResonanceType(char name, double mass, int charge, double width) ;
ResonanceType() ;
double Getwidth() const ;
void Print() const ;
private:
const double width_ ;
} ;
#endif
ResonanceType.C
#include "ResonanceType.h"
ResonanceType::ResonanceType(char name, double mass, int charge, double width) :
ParticleType(name,charge,mass), width_{width} {};
ResonanceType::ResonanceType() :
ParticleType() , width_{} {};
double ResonanceType::Getwidth() const {
return width_ ;
}
void ResonanceType::Print() const {
ParticleType::Print();
std::cout << "Width : " << Getwidth() << '\n' ;
}
and finally my main
#include "ResonanceType.h"
#include <vector>
int main() {
std::vector<ParticleType> v ;
ResonanceType r = ResonanceType('k',0.89166,0,0.050) ;
ParticleType p = ParticleType('p',0.13957,1) ;
v.push_back(r);
v.push_back(p) ;
v[0].Print() ;
v[1].Print() ;
}
this is the output I get :
Name: k Mass: 0 Charge: 0
Name: p Mass: 0.13957 Charge: 1