1

According to what I have found in this question an array of references is illegal. Im kinda new to C++ and was playing around with pointers and dereferencing and the following code seems to execute just fine.

#include <iostream>
#include <cstdlib>

using namespace std;

struct A
{
    int data1;
    int data2;

    A (void) : data1(0), data2(0) {}

    // many more datas
};

int main()
{
    cout << "test start" << endl;

    A *a = new A();
    A arr[100];

    for (int x=0; x<100; x++) arr[x] = *a;

    cout << "test done" << endl;
}

what happens here under the hood? is a copy of the a object being put in every location of the array? if so, when returning a object reference from a function like:

A &function (void) { return &A(); }

is it the same thins as this?:

A function (void) {return A();}
Community
  • 1
  • 1
shishkebab
  • 13
  • 3

1 Answers1

0

For your first question, arr[x] = *a; causes the program to copy all the data stored in the object to the specified array element.

For your second question, A &function (void) { return &A(); } appears to attempt to return the address of a function, but the format is incorrect. Look up "pointer to function" for more information. You could however, do this:

A test;

A &function(void)
{
    return test;
}

A &ref = function();

This way, you have an actual object in your program that can be used in a reference and your function returns the address to that object. Which appears to be what you are trying to do with that particular function.

Edit: Removed incorrect part of answer. A function(void) { return A(); } does create an object and return the created object.

Edit2: changed return &test; to return test; in A &function().

TChapman500
  • 139
  • 13
  • 1
    "appears to attempt to return the address of a function". No, he's trying to return a reference to a temporary instance of A. The `()` is simply a explicit call to the default constructor. That's a bad idea offcourse, and it won't compile, but his intentions can be deduced from his next line of code in the question: `A function(void) {return A();}` which is perfectly correct BTW. – Unimportant Jan 07 '17 at 17:54
  • I know what he's trying to do. And thanks for the info about the original `A function(void)` function. – TChapman500 Jan 07 '17 at 18:07
  • 2
    Then what's up with the broken code ? Your function returns the address of `test` in a function that should return a `A&` reference, it won't compile. – Unimportant Jan 07 '17 at 18:12
  • You are correct. My mistake. I have corrected the problem. – TChapman500 Jan 07 '17 at 18:17