I have a class hierarchy that looks like this:
class Address {
public:
virtual ~Address() {}
enum Type {
Internal, External
};
Type type() const { return _type; }
protected:
Address(Type type) : _type(type) {}
private:
Type _type;
};
class InternalAddress : public Address {
public:
InternalAddress(const string& portName) : Address(Internal), _portName(portName) {}
~InternalAddress() {}
const string& portName() const { return _portName; }
private:
string _portName;
};
class ExternalAddress : public Address {
public:
ExternalAddress(const string& handlerName) : Address(External), _handlerName(handlerName) {}
~ExternalAddress() {}
const string& handlerName() const { return string("handler"); }
private:
string _handlerName;
};
I want to eliminate dynamic memory allocation so I created a factory function that returns one of these by value, depending on a parameter:
static Address addressForType(Address::Type type) {
if (Address::Internal == type)
return InternalAddress();
else
return ExternalAddress();
}
I then do something like this:
int main(int argc, char **argv) {
Address address = addressForType(Address::External);
cout << ((ExternalAddress&)address).handlerName() << endl;
}
Is there anything wrong with the what I'm doing here? Or, is this just a bad design?? The reason I ask is that I'm in the process of trying to modify a existing system so it uses less dynamic memory allocation. Changing the code to return by value, instead of a dynamically allocated object, causes a segfault when I try to access the string reference return by the "handlerName()" method.
If there's a better way to do this, please enlighten me! I'll add that, for brevity, I've left out copy constructor and assignment operators. Even with these present, I get the same result.
Thanks.