Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing enum to a constructor

I have a base class Shape and some other derived classes like Circle, Rectangle and so on.

This is my base class

class Shape {

private:
enum Color {
    Red,
    Orange,
    Yellow,
    Green
};
protected:
int X;
int Y;

// etc...
};

This is one of my derived classes

class Rectangle : public Shape {
private:
int Base;
int Height;
string shapeName;

//etc...
};

This is how I call a constructor:

Rectangle R1(1, 3, 2, 15, "Rectangle 1");

My constructor:

Rectangle::Rectangle(int x, int y, int B, int H, const string &Name)
:Shape(x, y)
{
setBase(B);
setHeight(H);
setShapeName(Name);
}

I want to add one argument to my constructor so I can pass the color of the shape using enum Color in my base class. How can I do that? I also want to print the color as a string. I have no idea on how to use enum as an argument in a constructor.

Any help is appreciated...

like image 429
Jack in the Box Avatar asked Jan 16 '23 00:01

Jack in the Box


1 Answers

First of all, you should make Color protected or public. One simple way to make Color from enum to string is to use an array.

class Shape {
public:
    enum Color {
        Red = 0, // although it will also be 0 if you don't write this
        Orange, // this will be 1
        Yellow,
        Green
    };

};

class Rectangle : public Shape {
public:
    Rectangle(int x, int y, int B, int H, Color color);
};

string getColorName(Shape::Color color) {
    string colorName[] = {"Red", "Orange", "Yellow", "Green"};
    return colorName[color];
}

void test() {
    // now you may call like this:
    Rectangle r(1,2,3,4, Shape::Red);
    // get string like this:
    string colorStr = getColorName(Shape::Yellow);
}
like image 130
Ovilia Avatar answered Jan 26 '23 04:01

Ovilia