Initializing a member class with a non-default constructor

I am trying to create a gui that has a SimpleWindow class that contains a textPanel class:

class textPanel{ private: std::string text_m; public: textPanel(std::string str):text_m(str){} ~textPanel(); }; class SimpleWindow{ public: SimpleWindow(); ~SimpleWindow(); textPanel text_panel_m; }; SimpleWindow::SimpleWindow(): text_panel_m(std::string temp("default value")) { } 

I want to be able to initialize text_panel_m using const char *, which converts to std :: string without having to create another constructor that accepts const char *. Should I just create another constructor with const char * as an argument? If I do this, is this a way to reduce the amount of redundant constructor code using C ++ 0x?

With the approach above, I am having difficulty initializing member_panel_m variable. g ++ gives me the following error:

 simpleWindow.cpp:49: error: expected primary-expression before 'temp' simpleWindow.cpp: In member function 'bool SimpleWindow::drawText(std::string)': 

How do I start initializing member_panel_m without using the default constructor?

+4
source share
4 answers

An unnamed temporary value is required in the initializer list. One simple change will do this:

 SimpleWindow::SimpleWindow(): text_panel_m(std::string("default value")) 
+5
source

You are almost there:

 SimpleWindow::SimpleWindow(): text_panel_m("default value") { } 

Should do the trick using std::string implicit conversion constructor from const char* .

+6
source

Change

 text_panel_m(std::string temp("default value")) 

to

 text_panel_m(std::string("default value")) 
+1
source

try str("string") and remove the std :: string bit.

Alternatively, you can have a default constructor in the textPanel class that calls your string constructor.

0
source

All Articles