开发者

Dereferencing syntax in copy constructor for class that contains other objects

Suppose the class MyClass has constructor:

MyClass::MyClass( ... ) {
    var = new OtherClass( ... );
}

and suppose the class OtherClass has copy constructor:

OtherClass::OtherClass(const OtherClass &obj) {
    for (int i = 0; i < array_size; ++i) {
        array[i] = obj.array[i];
    }
}

Is the below a recommended way to write the copy constructor for MyClass?

MyClass::MyClass(const MyClass &obj) {
    var = new OtherClass(*obj.var);
}

I'm asking because I haven't been able to find an example of the dereferencing syntax the above copy constructor uses.

Edit: I'm sorry, I left 开发者_StackOverflow中文版a typo in the copy constructor (introduced while I was trying to make the code example abstract): *obj.array was intended to be *obj.var.


No, that doesn't really make sense. What makes sense is this:

MyClass::MyClass(const MyClass &obj) {
    var = new OtherClass(*obj.var);
}

Or rather:

MyClass::MyClass(const MyClass &obj)
    :var(new OtherClass(*obj.var))
{}


Assuming that var is actually a member of MyClass and a pointer to OtherClass, I would write

MyClass::MyClass(const MyClass &obj) : var(new OtherClass(obj.array))
{
   ...
}


Yes, it's generally recommended that copy ctors take const reference parameters.

You do not need to dereference a reference. Change your code to:

MyClass::MyClass(const MyClass &obj) {
    var = new OtherClass(obj.array);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜