-7

I came across this C++ code. What are the issues in it? I can see that copy and assignment will be an issue, because a pointer is used as data member.

class Vehicle
{
    char const* type;
public:
    Vehicle(char const* tt) : type(tt) {}
    char const* getType() const
    {
        return type;
    }
    ~Vehicle()
    {
        delete type;
    }
};
Striezel
  • 3,693
  • 7
  • 23
  • 37
SymS
  • 3

1 Answers1

2

A trivial bit of refactoring makes this class much more stable, at the expense of a string copy:

class Vehicle
{
    std::string type;
public:
    Vehicle(char const* tt) : type(tt) {}
    char const* getType() const
    {
        return type.c_str();
    }
};

Then I'd suggest that you change the return type of getType() to a const std::string&:

const std::string& getType() const
{
    return type;
}

At least then you don't need to worry about the returned pointer of a getType type being invalidated if the type member is changed.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483