hurricaneMitch
hurricaneMitch

Reputation: 173

Translate an Ada record with a conditional into C++

I have an assignment in which I need to translate some Ada code to C++ code, making it as similar as possible to the Ada code. The Ada code is as follows

    type Shape is (Circle, Triangle, Rectangle);
    type Colors is (Red, Green, Blue);
    type Figure(Form: Shape := Circle) is
        record
            Filled: Boolean;
            Color: Colors;
            case Form is 
                when Circle =>
                    Diameter: Float;
                when Triangle =>
                    Left_Side: Integer;
                    Right_Side: Integer;
                    Angle: Float;
                when Rectangle =>
                    Side_1: Integer;
                    Side_2: Integer;
            end case;
        end record;

I know I could use a class but judging by the language of the question and the personality of the teacher I assume he is looking for a struct. I am just unclear as to how to create the logic required for the different cases inside of a struct. The teacher is very particular so I assume that the smallest memory footprint is required.

I am a CSc student so forgive me if the solution is simple. Thanks!

Update: So the final answer was simpler than I thought.

enum Shape {Circle, Triangle, Rectangle};
enum Colors {Red, Green, Blue};
struct Figure {
  bool Filled;
  Colors Color;
  Shape Form;
  union {
    float Diameter;
    struct {
      int Left_Side;
      int Right_Side;
      float Angle;
    } tri;
    struct {
      int Side_1;
      int Side_2;
    } rect;
  };
 };

As usual I overthought it. Thanks for all your input!

Upvotes: 3

Views: 588

Answers (2)

Shark8
Shark8

Reputation: 4198

For non-class based answer:

  1. Make the enumerations for the Shape and Color types.
  2. Make structs for the Circle, Triangle, and Rectangle data.
  3. Make a Figure struct containing the filled field, colored field, and a field which is a union of the structs made in #2.
  4. [optional] Make "constructors" for the various shapes that return the struct from #3, properly initialized.

Upvotes: 1

perreal
perreal

Reputation: 97938

It looks like you are suppose to derive classes Circle, Triangle, and Rectangle from a base Shape class. There are common properties (Filled, Color) that needs to go into your base Shape, and derived classes will have diameter, or left-right sides, or other additional properties.

An alternative would be to have a type-id field (enum {Circle, Rectangle, ..})in a Shape struct and a union field holding different sub-structures for diameter and other type dependent members. This would look more like the example (and C) but less like C++.

Upvotes: 5

Related Questions