-1

I have this c++ class.

class Dinosaur {
    public:
        Dinosaur();
        ...
    private:
        char* name_str_pointer;
        ...
}

I'm trying use implicit conversion from Dinosaur to char* so this line works comparing "velociraptor" with name_str_pointer.

Dinosaur d();
strcmp(d, "velociraptor");

Which returns

error: cannot convert ‘const Dinosaur’ to ‘const char*’ for argument ‘1’ to ‘int strcmp(const char*, const char*)’

How can I achieve that?

Bruno A.
  • 13
  • 2
  • Specifically, look at the implicit conversion section [`operator const char*()`](http://stackoverflow.com/a/16615725/2296458) – Cory Kramer Jul 14 '14 at 12:38
  • 5
    `Dinosaur d();` does not create an object instance, it declares a function. – interjay Jul 14 '14 at 12:39
  • 1
    This looks (strongly) like the x-y problem. In c++ you should not use `char*` for storing data in a class. Look at `std::string`, `std::vector` or `std::array` instead (depending on the requirements in your code). Since you use `strcmp` in client code, it seems you should use `std::string` instead of a `char*`. Either way, if you need instances to compare to strings in client code, your class should probably implement a `bool operator==(const std::string&) const` instead. – utnapistim Jul 14 '14 at 12:48
  • @interjay You are right. – Bruno A. Jul 14 '14 at 13:33
  • @JonathanWakely I come from Java and I'm just learning c++, I tried to use some kind of operator overload but didn't know how. – Bruno A. Jul 14 '14 at 13:38

1 Answers1

2

Try the following

class Dinosaur {
    public:
        Dinosaur();
        operator char *() const { return name_str_pointer; }
        ...
    private:
        char* name_str_pointer;
        //...
};

//...

Dinosaur d;
strcmp(d, "velociraptor");

Take into account that you have to allocate enough memory pointed to by name_str_pointer in the default constructor that to accomodate string literal "velociraptor". Also you need to define the copy constructor, copy assignment operator and destructor. In any case such an approach is unsafe,

It would be much better if instead of the pointer and dynamically allocated memory you would use standard class std::string

For example

class Dinosaur {
    public:
        Dinosaur( const std::string &name ) : name_str_pointer( name ) {}
        operator const std::string &() const { return name_str_pointer; } 
        ...
    private:
        std::string name_str_pointer;
        //...
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks. I was trying operator overloading but I didn't know how to approach this case. I knew how to overload some operators but I didn't know about this kind (conversion operators). Yeah, it would be better using string but I'm learning c++ and it seems I'm not allowed to use it yet. – Bruno A. Jul 14 '14 at 13:32