3
namespace abc{
    class MyClass{
    protected:
       tm structTime;
    public:
       const tm& getTM(){
            return structTime;
        }
       void foo(){ std::string tmp = asctime ( this->getTM() ); }
    };

The above code gives me this error:

 error: cannot convert 'const tm' to 'const tm*' for argument '1' to 'char* asctime(const tm*)'

I then changed the code to this:

std::string tmp = asctime ( static_cast<const tm*>(getTM()) );

but that gives me an error that says:

invalid static_cast from type 'const tm' to type 'const tm*'

How can I make a 'const tm*' from a 'const tm&'?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jamiil
  • 59
  • 5

1 Answers1

4

static_cast<const tm*>(getTM())

You certainly don't want a static_cast<> (nor a reinterpret_cast<>) to do this!

See the reference for std::asctime(), it wants a pointer actually:

char* asctime( const std::tm* time_ptr );
                         // ^

"How can I make a 'const tm*' from a 'const tm&'?"

Your function returns a const &, that's not a pointer. Change your code to pass the address of the result:

asctime ( &getTM() );
       // ^ <<<< Take the address of the result, to make it a const pointer

See a complete LIVE DEMO.


You may also be interested in reading this Q&A:

What are the differences between a pointer variable and a reference variable in C++?

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • @Jamiil _"Yes, you are right!"_ Did you consider accepting the answer then? It might help future researchers to judge this Q&A pair being helpful. – πάντα ῥεῖ Nov 26 '14 at 18:06
  • @Jamiil This will also support to avoid silly feature requests [like this](http://meta.stackoverflow.com/questions/277918/should-users-with-high-rep-be-able-to-accept-answers-to-questions-with-no-accept) appearing on MSO. – πάντα ῥεῖ Nov 26 '14 at 18:21