Enumerated data types and class APIs in C ++
If you have to encapsulate everything inside a class definition, how then can the listed data types be used with the class? For example, I just wrote the following code ...
enum PizzaType {DEEP_DISH, HAND_TOSSED, PAN};
enum PizzaSize {SMALL, MEDIUM, LARGE};
class Pizza {
public:
Pizza();
void setPizzaType(PizzaType type);
PizzaType getPizzaType();
void setPizzaSize(PizzaSize size);
PizzaSize getPizzaSize();
void setToppings(int toppings);
int getToppings();
void outputDescription();
double computePrice();
private:
PizzaType pizzaType;
PizzaSize pizzaSize;
int totalToppings;
};
Is there a way to include the listed datatypes inside the class itself and still allow access to mutator / access functions from outside?
Yes, you can do it like this:
class Pizza {
public:
enum PizzaType {DEEP_DISH, HAND_TOSSED, PAN};
enum PizzaSize {SMALL, MEDIUM, LARGE};
Pizza();
void setPizzaType(PizzaType type);
PizzaType getPizzaType();
void setPizzaSize(PizzaSize size);
PizzaSize getPizzaSize();
void setToppings(int toppings);
int getToppings();
void outputDescription();
double computePrice();
private:
PizzaType pizzaType;
PizzaSize pizzaSize;
int totalToppings;
};
.. and then others said, you just need to use the "Pizza" namespace to go to enum types:
Pizza::PizzaType tmp = pPizza->getPizzaType();
etc. etc.
(As a style note, when you put an enum inside a class like this, I personally remove Pizza in front of it so that you have Pizza :: Type and Pizza :: Size.)
a source to share
The preferred method of using enums in C ++ is to define them inside a class:
class Foo {
public:
enum Bar {
ENUM_VALUE1,
ENUM_VALUE2
};
};
Then you can link to them using:
Foo::Bar var;
var = Foo::ENUM_VALUE1;
Inside the class, you can drop the prefix Foo::
.
As you probably noticed, while an enum type Foo::Bar
, values are not referenced Foo::Bar::ENUM_VALUE1
, but rather appear in the namespace Foo
. This can be problematic if different enums have the same value names. To avoid this, you can do the following trick:
class Foo {
public:
struct Bar {
enum ENUM {
ENUM_VALUE1,
ENUM_VALUE2
};
struct Baz {
enum ENUM {
ENUM_VALUE1,
ENUM_VALUE2
};
};
};
Foo::Bar::ENUM e = Foo::Bar::ENUM_VALUE1;
Foo::Baz::ENUM e2 = Foo::Baz::ENUM_VALUE1;
a source to share
This is not a problem, you can create variables of this enum type by specifying Pizza :: PizzaType.
Place enums inside your class, if you want to be visually accessible make sure they are public as well.
Pizza p; p.setPizzaType(Pizza::PAN); Pizza::PizzaType pt = p.getPizzaType(); assert(pt == Pizza::PAN);
a source to share