Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing member class with non-default constructor

I'm trying to make a gui which 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 the text_panel_m using a const char* that gets converted to a std::string without needing to make another constructor that takes a const char*. Should I just create another constructor with const char* as an argument anyway? If I do it this way is there a way to reduce the amount of redundant constructor code using c++0x?

With the approach above I'm having difficulties initializing the text_panel_m member 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 go about initializing the text_panel_m member variable without using the default constructor?

like image 600
shuttle87 Avatar asked Dec 17 '22 14:12

shuttle87


2 Answers

You're almost there:

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

Should do the trick, using std::string's implicit converting constructor from const char*.

like image 94
Mark B Avatar answered Dec 19 '22 05:12

Mark B


You want an unnamed temporary value in the initializer list. One simple change will do it:

SimpleWindow::SimpleWindow():
         text_panel_m(std::string("default value"))
like image 30
Mark Ransom Avatar answered Dec 19 '22 05:12

Mark Ransom