Default Value while 'passing by reference'

M

mufasa

We know C++ supports functions that can carry default values as
follows:

someFunction(int a, int b, int c =20);

So calling someFunction(x,y) is perfectly legal!

However, if I need to information by reference, can initiate the
referenced variable to a default value?

Eg:

int main()
{
int a = 20;
int b, c;

int &r = a;

someFunction(b,c); // <-------------------- POSSIBLE??
someFunction(b,c,r);//<-------------------- This is allowed

}

someFunction(int x, int y, int& z = 30); //<-- WELL??
{
}
 
S

Sharad Kala

mufasa said:
We know C++ supports functions that can carry default values as
follows:

someFunction(int a, int b, int c =20);

So calling someFunction(x,y) is perfectly legal!

However, if I need to information by reference, can initiate the
referenced variable to a default value?

Eg:

int main()
{
int a = 20;
int b, c;

int &r = a;

someFunction(b,c); // <-------------------- POSSIBLE??
someFunction(b,c,r);//<-------------------- This is allowed

}

someFunction(int x, int y, int& z = 30); //<-- WELL??

There should be no semicolon at the end

This is not legal C++. You are binding a non const reference (z) to a
temporary object, which is illegal. It will work if you bind it to some
l-value.

int a = 30;

void
someFunction(int x, int y, int& z = a)
{
}

Sharad
 
R

Rolf Magnus

mufasa said:
We know C++ supports functions that can carry default values as
follows:

someFunction(int a, int b, int c =20);

So calling someFunction(x,y) is perfectly legal!

However, if I need to information by reference, can initiate the
referenced variable to a default value?
Yes.

int main()
{
int a = 20;
int b, c;

int &r = a;

someFunction(b,c); // <-------------------- POSSIBLE??
someFunction(b,c,r);//<-------------------- This is allowed

}

someFunction(int x, int y, int& z = 30); //<-- WELL??

Your function is missing a return type.

Make that:

void someFunction(int x, int y, const int& z = 30); //<-- WELL??
{
}
 
G

Gianni Mariani

mufasa said:
We know C++ supports functions that can carry default values as
follows: ....

someFunction(int x, int y, int& z = 30); //<-- WELL??

void someFunction(int x, int y, const int& z = 30)

If you're passing a reference to a literal (30), does it make sense that
you can modify it ? The C++ standard says you can't.

G
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,665
Latest member
salkete

Latest Threads

Top