1

I have the following C++ class:

class Eamorr {
public:
        redispp::Connection conn;

        Eamorr(string& home, string& uuid)
        {
            //redispp::Connection conn("127.0.0.1", "6379", "password", false);   //this works, but is out of scope in put()...
            conn=new redispp::Connection("127.0.0.1", "6379", "password", false);   //this doesn't work ;(
        }
        put(){
            conn.set("hello", "world");
        }
        ...
}

As you can see, I want conn to be initialised in the constructor and available in the put() method.

How can I do this?

Many thanks in advance,

Eamorr
  • 9,872
  • 34
  • 125
  • 209

2 Answers2

8

This is what member-initialization-list is for:

 Eamorr(string& home, string& uuid) 
     : conn("127.0.0.1", "6379", "password", false) 
 {
    //constructor body!
 }

The syntax after : ( and including this) forms member-initiazation-list. You can initialize the members here, each member separated by comma.

Here is an elaborated example:

struct A
{
     int n;
     std::string s;
     B *pB;

     A() : n(100), s("some string"), pB(new B(n, s))
     {
        //ctor-body!
     }
};

For more, see these:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

Just to expand on Nawaz answer.

The thing that was actually wrong was that you used new for a variable that wasn't a pointer. So as the variable conn isn't a pointer you could have written:

Eamorr(string& home, string& uuid)
{
    conn = redispp::Connection("127.0.0.1", "6379", "password", false);
}
Cpt. Red
  • 102
  • 3