kotoko
kotoko

Reputation: 599

Object with attribute that can different type for the same attribute

I'm trying to figure out the best approach for a c++ program:

I need to make an object called Characteristic. This guy has 4 attributes:
- String name (just the name)
- ? type (what type of characteristic it is. Can be either numeric or descriptive)
- ? range (numeric - the min and max
descriptive - the options)
- ? value (the actual chosen value could be int or string depending on the type)

If I was in Java I would create an object Type with two children: Numeric and Descriptive. Each would have the appropriate range and store the value in the appropriate format.

Examples for both:
Name: Warmeness
Type: Numeric
Range: min 1 max 5
Value: 2

Name: Style
Type: Descriptive
Range: minimalistic photography
Value: minimalistic

I have no idea what is the best way to do this in c++.
Should I be looking at templates? Because if so I cannot figure out how to use them.

Upvotes: 0

Views: 500

Answers (2)

bames53
bames53

Reputation: 88185

You can do the same thing as Java if you want.

struct Type {
    std::string Name;
};

struct Numeric : Type {
    int value, min, max;
};

struct Descriptive : Type {
    std::string value, min, max;
};

However before you can decide how to implement your Characteristic you have to better define how you're going to use it and the interface you want. For example the above doesn't make it easy to use to use a Type object as a polymorphic object. You'd have to manually check if a Type pointer points at a Numeric or Descriptive and act accordingly.


One way to get polymorphism is C++ is to use virtual methods:

struct Type {
    ~Type() {} // virtual destructor
    virtual void do_something() = 0; // pure virtual function. Derived classes must provide an implementation
    std::string Name;
};

struct Numeric : Type {
    virtual void do_something() {
        std::cout << "Numeric value: " << value << " (" << min << ',' << max << ")\n"; 
    }
    int value, min, max;
};

struct Descriptive : Type {
    virtual void do_something() {
        std::cout << "Descriptive value: " << value << " (" << min << ',' << max << ")\n"; 
    }
    std::string value, min, max;
};

Now when you call do_something on a Type * it will figure out the right method for the dynamic type and call that.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

There are several approaches you could choose from in C++:

  • Inheritance. It's not just Java where you can do this. If this is the approach you'd use in Java, I don't see why you couldn't do the same in C++.
  • Templates. This approach would correspond to Java generics.
  • Unions. I don't think there's a Java corresponded, might worth looking into.

Without further details, it's not possible to give good arguments why you should prefer one over the other.

Upvotes: 0

Related Questions