How to write a Java-enum-like class with multiple data fields in C++?

One way to simulate Java enums is to create a class with a private constructor that instantiates copies of itself as static variables:

class Planet {  
    // Enum value DECLARATIONS - they are defined later 
    static const Planet MERCURY;  
    static const Planet VENUS;  
    // ... 

    double mass;   // in kilograms  
    double radius; // in meters  

    Planet(double mass, double radius) {  
        this->mass = mass;  
        this->radius = radius;  

    // Properties and methods go here 

// Enum value DEFINITIONS 
// The initialization occurs in the scope of the class,  
// so the private Planet constructor can be used. 
const Planet Planet::MERCURY = Planet(3.303e+23, 2.4397e6);  
const Planet Planet::VENUS = Planet(4.869e+24, 6.0518e6);  
// ... 

Then you can use the enums like this:

double gravityOnMercury = Planet::MERCURY.SurfaceGravity();

Leave a Comment