Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I doing something wrong here (references in C++)?

Tags:

c++

reference

I've been playing around with references (I'm still having issues in this regard).

1- I would like to know if this is an acceptable code:

int & foo(int &y)
{
    return y;  // is this wrong?
}

int main()
{
    int x = 0;    
    cout << foo(x) << endl;

    foo(x) = 9;   // is this wrong?
    cout << x << endl;

    return 0;
}

2- Also this is from an exam sample:

Week & Week::highestSalesWeek(Week aYear[52])
{
  Week max = aYear[0];
  for(int i = 1; i < 52; i++)
  {
    if (aYear[i].getSales() > max.getSales())
      max = aYear[i];
  }
  return max;
}

It asks about the mistake in this code, also how to fix it.

My guess is that it return a local reference. The fix is:

Week & max = aYear[0];

Is this correct/enough?

like image 581
m4design Avatar asked Jun 12 '10 22:06

m4design


People also ask

Does C have reference?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.

How do c++ references work?

The main use of references is acting as function formal parameters to support pass-by-reference. In an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value). Changes inside the function are reflected outside the function.

When to use pointer and reference in c++?

Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

Are references safer than pointers?

In C++, Reference variables are safer than pointers because reference variables must be initialized and they cannot be changed to refer to something else once they are initialized.


1 Answers

The first one is correct.

For the second one, there are infinite number of solutions :), but this would be mine:

Week Week::highestSalesWeek(Week aYear[52]) // return a copy of the week
{ 
  Week max = aYear[0]; 
  for(int i = 1; i < 52; i++) 
  { 
    if (aYear[i].getSales() > max.getSales()) max = aYear[i]; 
  } 
  return max; 
} 

If max is a reference, you would modify the first element of aYear everytime you do:

max = aYear[i]

Also, you could use a pointer to return a reference to the week:

Week & Week::highestSalesWeek(Week aYear[52])
{ 
  Week* max = &aYear[0]; 
  for(int i = 1; i < 52; i++) 
  { 
    if (aYear[i].getSales() > max->getSales()) max = &aYear[i]; 
  } 
  return *max; 
} 
like image 136
Khaled Alshaya Avatar answered Sep 27 '22 15:09

Khaled Alshaya