7

I'd like to know if these are basically the same thing.

class ExampleClass {
    public:
        ExampleClass(Object& newObj) : obj(newObj) {}
    private:
        Object obj;
}

class ExampleClass2 {
    public:
        ExampleClass2(Object& newObj) : objReference(newObj) {}
    private:
        Object& objReference;
}

So would this not work with either of the classes?

ExampleClass* getExampleObject() {
    Object obj;
    return new ExampleClass(obj);
}

ExampleClass2* getExample2Object() {
    Object obj;
    return new ExampleClass2(obj);
}

void main() {
    ExampleClass* ec = getExampleObject();
    ExampleClass2* ec2 = getExample2Object();
    //Do something involving the member objects of ec and ec2
}

So are the member objects invalid after both getExampleObject methods? Doesn't the constructor of ExampleClass save a copy of the object referenced in its constructor?

user1468729
  • 71
  • 1
  • 1
  • 3

2 Answers2

9

ExampleClass is fine, as it takes a copy of the object referenced in its constructor argument.

ExampleClass2 requires that the object referenced in its constructor argument exist for the lifetime of the ExampleClass2 instance (as it stores a reference to the object, it does not copy it). If it does not, then the ExampleClass2 instance will have a dangling reference as soon as the object to which it refers is destructed. This is the case with the getExample2Object() function as obj is destructed when getExample2Object() returns.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 1
    Thanks. That's what I thought but this made me doubt myself: [link](http://stackoverflow.com/questions/1404305/c-reference-in-constructor) – user1468729 Jun 20 '12 at 10:30
  • @user1468729, in that question `myclass` has `std::string` member, not a reference to a `std::string`. – hmjd Jun 20 '12 at 10:33
  • So does my first ExampleClass. Or am I missing something here? – user1468729 Jun 20 '12 at 10:43
  • @user1468729, and your `ExampleClass` is fine. The code in the other question is legal, I think the question was asking _what_ if I stored reference. If you notice, the accepted (and correct) answer to that question also state to store a copy. – hmjd Jun 20 '12 at 10:47
1

I'd like to know if these are basically the same thing.

No, they are not. Example's constructor takes an object reference and constructs a member object to using the object passed. This object is not a reference but a copy. In case of Example2, you are actually making objReference refer to object passed in ctor's parameter. You are good only as long as newObj's lifetime.

The

Object obj;
return new ExampleClass2(obj);

is the classic case when it will fail. Once the function returns, you will have a dangling reference.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104