Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor without assigning it to any variable c++

This might be a very silly question, but I don't even know what should I write to look for answers. I'm not even sure if the title I gave is correct.

If I have a constructor like this:

CError(const std::string& msg) { showMessage(msg) }

And I'd like to call it like this ...

CError("some message");

... everything works, but when string is specified in some variable, I got an error that "Default constructor for class CError doesn't exist":

std::string str = "some message";
CError(str);

When I write it like this, it works:

std::string str = "some message";
CError err(str);

But I just don't need this err object.

Could anyone explain me why can't I call only constructor itself?

Thanks in advance for the answers.

like image 375
Piotr Chojnacki Avatar asked Nov 02 '12 08:11

Piotr Chojnacki


1 Answers

The line CError(str); is parsed as CError str;, which defines a new variable, str. My compiler fails differently, which makes the problem more obvious: redefinition of 'str' with a different type.

A simple work-around for this problem is to cast the object:

(void)CError(str);

The burning question, however, is: why do this? If you don't plan to use the constructed object in any way, why not simply make it a static member function or even just a plain old free function?

like image 122
Marcelo Cantos Avatar answered Nov 15 '22 00:11

Marcelo Cantos