Object-Oriented Programming in C++

Code display of PL7/galaxy_wrong.cpp

// PL7/galaxy_wrong.cpp
// The definition of a galaxy on top of the celestial object class
// Niels Walet, last updated 06/01/2022
#include<iostream>
#include<string>
using namespace std;
class celestial_object
{
private:
  string name;
  double mass;
  double distance;
  double luminosity;
public:
  celestial_object() : 
    name{"no-name"}, mass{}, distance{}, luminosity{} {}
  celestial_object(const string nm, const double l, const double m, const double d) :
    name{nm}, mass{m}, distance{d}, luminosity{l} {}
  ~celestial_object(){}
  string celestial_object_name() {return name;}
  friend ostream& operator<<(ostream& , const celestial_object& );
};

class galaxy: public celestial_object
{
private:
  string hubble_type;
  long stars;
public:
  galaxy() : 
    name{"no-name"}, luminosity{}, mass{}, distance{},
    hubble_type{"Sc"}, stars{} {}
  galaxy(const string nm, const double l, const double m, const double d,
	 const string ht, const long nst) :
    name{nm}, luminosity{l}, mass{m}, distance{d},
    hubble_type{ht}, stars{nst} {}
  ~galaxy(){}
  friend ostream& operator<<(ostream& , const galaxy& );
}

ostream& operator<<(ostream& o, const galaxy& gx)
{o <<" galaxy "<<gx.name <<": "<<std::endl
   <<" Hubble type "<<gx.hubble_type
   <<" #stars "<<stars<<std::endl
   <<" mass "<<gx.mass <<" Msun,"
   <<" luminosity "<<gx.luminosity <<" ,"
   <<" distance (z) "<<gx.distance <<std::endl;
    return o;
}

ostream& operator<<(ostream& o, const celestial_object& co)
{o <<" object "<<co.name <<": "<<std::endl
   <<" mass "<<co.mass <<" Msun,"
   <<" luminosity "<<co.luminosity <<" ,"
   <<" distance (z) "<<co.distance <<std::endl;
    return o;
}
int main()
{
  celestial_object LMC{"Large Magellanic Cloud",-1,2e10,0.000875};
  std::cout <<LMC;
  return 0;
}
Download here; To copy and paste: double click inside code, then copy.