user11749173
user11749173

Reputation: 1

How to properly initialize copy constructor (of constructor with class as reference)

How do you initialize a copy constructor of constructor that has as reference a class. I simply do not know what to put after the colon in order to initialize it.

class Me{
 public:   
    Me (const otherMe& t)
    :other_me(t)
    {}
    //copy constructor
    Me(const Me& me)
    : /*what do you put here in order to write 
    the line of code bellow. I tried t(t), and gives me the 
    warning 'Me::t is initialized with itself [-Winit-self]' */

    {cout << t.getSomthing() << endl;}

 private:
    const otherMe& other_me;
};

Upvotes: 0

Views: 56

Answers (1)

Alecto
Alecto

Reputation: 10740

Let's say you have two classes, Value, and Wrapper:

class Value { // stuff... }; 

class Wrapper; // This one contains the reference

We can write the constructor and copy-constructor like so:

class Wrapper {
    Value& val;

   public:
    Wrapper(Value& v) : val(v) {}

    Wrapper(Wrapper const& w) : val(w.val) {}
};

This wold also work if Value& were a const reference! In addition, if you can write Wrapper as an aggregate, it'll automatically get a copy constructor:

class Wrapper {
   public:
    Value& val;

    // copy constructor automatically generated
};

Upvotes: 2

Related Questions