How do I use an int& parameter with a default value? - c++

I have to add a default int& argument (Eg iNewArgument) to an existing function definition in a header file:
What is the syntax to initialize the last argument to make it take a default value?
..
virtual int ExecNew
(int& param1, int& RowIn,int& RowOut, char* Msg = '0',
bool bDebug=true, int& iNewArgument = NULL ) = 0 ;
.
.
NULL is #defined to 0
Error: default argument: cannot convert from int to int&

Your example indicates that you are creating a virtual function. Default arguments in virtual (especially pure) functions are not a good idea, because they are not considered when you call an overridden function.
struct A {
virtual void f(int = 4711) = 0;
};
struct B : A {
virtual void f(int) { /* ... */ }
};
Now, if someone calls f on a B object, he will have to provide the argument - the default isn't used. You would have to duplicate the default argument in the derived class, which creates ugly redundancies. Instead, you can use the non-virtual interface pattern
struct A {
void f(int a) {
int out;
f(a, out);
}
void f(int a, int &out) {
doF(a, out);
}
protected:
virtual void doF(int a, int out&) = 0;
};
The user can now call f with one, and with two arguments, from whatever class type he calls the function, and the implementers of A don't have to worry about the default argument. By using overloading instead of default arguments, you don't need to break your head around lvalues or temporaries.

The only meaningful way to supply a default argument to a non-const reference is to declare a standalone object with static storage duration and use it as a default argument
int dummy = 0;
...
virtual int ExecNew(/* whatever */, int& iNewArgument = dummy) = 0;
Whether it will work for you or not is for you to decide.
Inside the function, if you'll need to detect whether the default argument was used, you may use address comparison
if (&iNewArgument == &dummy)
/* Default argument was used */

You can't do that. The INewArgument must either be a raw int or a const reference. A non-const reference cannot be used the way you're trying to use it.

In short you're going to have to rework you problem. You can either make your int& a regular int and lose the reference behavior (being able to pass out the changed value) or give up having a default value.

The default has to be lvalue for a non-const reference type, so what try to do above won't work. What you can do is:
namespace detail {
int global;
}
void foo(int &x = detail::global) {}
or
void bar(const int &x = int(3)) {}

You say NULL is #defined to 0, so it's a literal value. The parameter is a reference to an int, which means the function would be able to change the value. How do you change the value of a literal?
You need to make it a const reference, or don't make it a reference at all.

Related

C++: why can a function declaration not assign a name to it's argument(s)? [duplicate]

The following is a perfectly legal C++ code
void foo (int) {
cout << "Yo!" << endl;
}
int main (int argc, char const *argv[]) {
foo(5);
return 0;
}
I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.
Why is this legal to begin with?
Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.
The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, Aasmund Eldhuset for bringing this up).
There is also a special case for defining your own post-increment and post-decrement operators: they must have a signature with an int parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.
Of course not naming a parameter is legal when just declaring the function, but it's also legal in the implementation. This last apparently strange version is useful when the function needs to declare the parameter to have a specific fixed signature, but the parameter is not needed.
This may happen for example for a method in a derived class, for a callback function or for a template parameter.
Not giving the parameter a name makes clear that the parameter is not needed and its value will not be used. Some compilers if you instead name a parameter and then simply don't use it will emit a warning that possibly there is a problem with the function body.
Just wanted to mention a specific (unusual but interesting) usecase - the "passkey idiom".
It uses a "dummy" parameter of a type, constructor of which is accessible only to its friends. Its purpose is only to check, whether the caller has access to this constructor. So it needs no name as it is not used in the function, only the compiler uses it.
It's used like this:
class Friendly; // Just a forward declaration
class Key {
private:
Key() {}
friend class Friendly;
};
class Safe() {
public:
static int locked(Key, int i) {
// Do something with `i`,
// but the key is never used.
return i;
}
private:
static void inaccessible() {}
};
class Friendly {
public:
void foo() {
int i = Safe::locked(Key(), 1); // OK
int j = Safe::locked({}, 2); // OK, sice C++11
}
void bar() {
Safe::inaccessible(); // Not OK, its inaccessible
}
};
int i = Safe::locked(3); // Not OK, wrong parameters
int j = Safe::locked(Key(), 4); // Not OK, `Key` constructor is inaccessible
int k = Safe::locked({}, 5); // Not OK, `{}` means `Key()` implicitly
I just want to add that there is sometimes a difference whether you name a parameter or not. For example, the compiler treats a named rvalue reference as an lvalue and an unnamed rvalue reference as an rvalue.
// named-reference.cpp
// Compile with: /EHsc
#include <iostream>
using namespace std;
// A class that contains a memory resource.
class MemoryBlock
{
// TODO: Add resources for the class here.
};
void g(const MemoryBlock&)
{
cout << "In g(const MemoryBlock&)." << endl;
}
void g(MemoryBlock&&)
{
cout << "In g(MemoryBlock&&)." << endl;
}
MemoryBlock&& f(MemoryBlock&& block)
{
g(block);
return block;
}
int main()
{
g(f(MemoryBlock()));
}
This example produces the following output:
In g(const MemoryBlock&).
In g(MemoryBlock&&).
In this example, the main function passes an rvalue to f. The body of f treats its named parameter as an lvalue. The call from f to g binds the parameter to an lvalue reference (the first overloaded version of g).

what is the significance of unnamed argument list while defining function in c++ [duplicate]

The following is a perfectly legal C++ code
void foo (int) {
cout << "Yo!" << endl;
}
int main (int argc, char const *argv[]) {
foo(5);
return 0;
}
I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.
Why is this legal to begin with?
Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.
The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, Aasmund Eldhuset for bringing this up).
There is also a special case for defining your own post-increment and post-decrement operators: they must have a signature with an int parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.
Of course not naming a parameter is legal when just declaring the function, but it's also legal in the implementation. This last apparently strange version is useful when the function needs to declare the parameter to have a specific fixed signature, but the parameter is not needed.
This may happen for example for a method in a derived class, for a callback function or for a template parameter.
Not giving the parameter a name makes clear that the parameter is not needed and its value will not be used. Some compilers if you instead name a parameter and then simply don't use it will emit a warning that possibly there is a problem with the function body.
Just wanted to mention a specific (unusual but interesting) usecase - the "passkey idiom".
It uses a "dummy" parameter of a type, constructor of which is accessible only to its friends. Its purpose is only to check, whether the caller has access to this constructor. So it needs no name as it is not used in the function, only the compiler uses it.
It's used like this:
class Friendly; // Just a forward declaration
class Key {
private:
Key() {}
friend class Friendly;
};
class Safe() {
public:
static int locked(Key, int i) {
// Do something with `i`,
// but the key is never used.
return i;
}
private:
static void inaccessible() {}
};
class Friendly {
public:
void foo() {
int i = Safe::locked(Key(), 1); // OK
int j = Safe::locked({}, 2); // OK, sice C++11
}
void bar() {
Safe::inaccessible(); // Not OK, its inaccessible
}
};
int i = Safe::locked(3); // Not OK, wrong parameters
int j = Safe::locked(Key(), 4); // Not OK, `Key` constructor is inaccessible
int k = Safe::locked({}, 5); // Not OK, `{}` means `Key()` implicitly
I just want to add that there is sometimes a difference whether you name a parameter or not. For example, the compiler treats a named rvalue reference as an lvalue and an unnamed rvalue reference as an rvalue.
// named-reference.cpp
// Compile with: /EHsc
#include <iostream>
using namespace std;
// A class that contains a memory resource.
class MemoryBlock
{
// TODO: Add resources for the class here.
};
void g(const MemoryBlock&)
{
cout << "In g(const MemoryBlock&)." << endl;
}
void g(MemoryBlock&&)
{
cout << "In g(MemoryBlock&&)." << endl;
}
MemoryBlock&& f(MemoryBlock&& block)
{
g(block);
return block;
}
int main()
{
g(f(MemoryBlock()));
}
This example produces the following output:
In g(const MemoryBlock&).
In g(MemoryBlock&&).
In this example, the main function passes an rvalue to f. The body of f treats its named parameter as an lvalue. The call from f to g binds the parameter to an lvalue reference (the first overloaded version of g).

Why does C++ allow unnamed function parameters?

The following is a perfectly legal C++ code
void foo (int) {
cout << "Yo!" << endl;
}
int main (int argc, char const *argv[]) {
foo(5);
return 0;
}
I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.
Why is this legal to begin with?
Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.
The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, Aasmund Eldhuset for bringing this up).
There is also a special case for defining your own post-increment and post-decrement operators: they must have a signature with an int parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.
Of course not naming a parameter is legal when just declaring the function, but it's also legal in the implementation. This last apparently strange version is useful when the function needs to declare the parameter to have a specific fixed signature, but the parameter is not needed.
This may happen for example for a method in a derived class, for a callback function or for a template parameter.
Not giving the parameter a name makes clear that the parameter is not needed and its value will not be used. Some compilers if you instead name a parameter and then simply don't use it will emit a warning that possibly there is a problem with the function body.
Just wanted to mention a specific (unusual but interesting) usecase - the "passkey idiom".
It uses a "dummy" parameter of a type, constructor of which is accessible only to its friends. Its purpose is only to check, whether the caller has access to this constructor. So it needs no name as it is not used in the function, only the compiler uses it.
It's used like this:
class Friendly; // Just a forward declaration
class Key {
private:
Key() {}
friend class Friendly;
};
class Safe() {
public:
static int locked(Key, int i) {
// Do something with `i`,
// but the key is never used.
return i;
}
private:
static void inaccessible() {}
};
class Friendly {
public:
void foo() {
int i = Safe::locked(Key(), 1); // OK
int j = Safe::locked({}, 2); // OK, sice C++11
}
void bar() {
Safe::inaccessible(); // Not OK, its inaccessible
}
};
int i = Safe::locked(3); // Not OK, wrong parameters
int j = Safe::locked(Key(), 4); // Not OK, `Key` constructor is inaccessible
int k = Safe::locked({}, 5); // Not OK, `{}` means `Key()` implicitly
I just want to add that there is sometimes a difference whether you name a parameter or not. For example, the compiler treats a named rvalue reference as an lvalue and an unnamed rvalue reference as an rvalue.
// named-reference.cpp
// Compile with: /EHsc
#include <iostream>
using namespace std;
// A class that contains a memory resource.
class MemoryBlock
{
// TODO: Add resources for the class here.
};
void g(const MemoryBlock&)
{
cout << "In g(const MemoryBlock&)." << endl;
}
void g(MemoryBlock&&)
{
cout << "In g(MemoryBlock&&)." << endl;
}
MemoryBlock&& f(MemoryBlock&& block)
{
g(block);
return block;
}
int main()
{
g(f(MemoryBlock()));
}
This example produces the following output:
In g(const MemoryBlock&).
In g(MemoryBlock&&).
In this example, the main function passes an rvalue to f. The body of f treats its named parameter as an lvalue. The call from f to g binds the parameter to an lvalue reference (the first overloaded version of g).

How can I make a bool reference argument defaulted?

In C++, is it possible to make a bool & argument of a function optional?
void foo(bool &argument = /* What goes here? */);
In my function foo, if the caller does not care about the result put into argument, I'd like the compiler to give a dummy location by default. Otherwise, callers who do not care must do this:
bool ignored;
foo(ignored);
Make another function
void foo(){
bool b=true;
foo(b);
}
The only way is to pass a global variable :
bool someArgument = false;
void foo(bool &argument = someArgument );
Ideally you should be using a function overload instead of trying to work around the system. Although there are legitimate ways to achieve this like the one #VJovic mentioned. With function overloads you can make other parameters optional too if ever you need to add more.
A non-const reference argument means your function intends to modify the object being passed. If you know which object you want that to be by default, then just use it as the default argument.
If you do not intend to modify the bool being passed in, then you should declare the function to take bool argument (i.e. not a reference) or const bool &argument. In either case you can provide a constant default value of true or false.
You can do it. But it is very ugly and messes up data locality:
static bool result__ = false;
static void foo(bool & result = result__)
{
result = true;
}
int main()
{
bool v;
foo();
foo(v);
return v ? 0 : 1;
}
Since C++ supports function overloading, use #QuentinUK's solution.

How can you modify an object without calling member functions?

At 3.10/10, the standard says:
An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to modify its referent under certain circumstances. [Example: a member function called for an object (9.3) can modify the object. ]
So, rvalues are non-modifiable except under certain circumstances. We're told that calling a member function is one of those exceptions. This gives the idea that there are ways of modifying objects other than calling a member function. I can't think of a way.
How can one modify an object without calling a member function?
How can one modify an object [that's specified by an rvalue expression] without calling a member function?
I know of only one way to do that, namely to bind the object to a reference to const, and then cast away the const-ness.
E.g.
template< class Type >
Type& tempRef( Type const& o ) { return const_cast< Type& >( o ); }
struct S { int x; };
int main()
{ tempRef( S() ).x = 3; }
This is because a temporary object is not const itself unless it is of const type, so the example above does not cast away original const-ness (which would be UB).
EDIT, added: Luc Danton’s answer showed another (non-general) way, namely where the temporary's construction stores some reference or pointer to the object in some accessible location.
Cheers & hth.,
This seems to be accepted:
struct T {
int x;
};
int main() {
T().x = 3;
}
I am slightly surprised that this works, because IIRC the LHS of op= must be an lvalue, yet the following implies that even T().x is an rvalue:
struct T {
int x;
};
void f(int& x) {
x = 3;
}
int main() {
f(T().x);
}
Edit: As of 4.6, GCC does warn about T().x = 3: error: using temporary as lvalue.
I can't think of any other way to modify a class object other than through data member access or member function calls. So, I'm going to say... you can't.
Modifying a temporary and not through an lvalue to that temporary:
#include <cstring>
class standard_layout {
standard_layout();
int stuff;
};
standard_layout* global;
standard_layout::standard_layout()
{ global = this; }
void
modify(int)
{
std::memset(global, 0, sizeof *global);
}
int
main()
{
modify( (standard_layout {}, 0) );
}
I don't think it's correct to assume that rvalues of class types are non-modifiable. I now understand that paragraph as 'for non-class types, an lvalue for an object is needed in order to modify that object'.
I can think of one way:
If your class exposes public member variables, you can assign directly to those member variables. For example:
class A
{
public:
int _my_var;
...
};
int main(int argc, char** argv)
{
A *a = new C();
a->_my_var = 10;
}
This is not a good programming style though - exposing a member variable as public isn't something I would advocate or even suggest.
Also, if you can do something really weird, such as directly writing some address in memory, an offset from the pointer to the class object - but why would you do that?
How can one modify an object without calling a member function?
By assigning a value to one of the object's visible data members, of course.
Doing an implicit cast is sort of like calling a member function -- also modifying rvalue refs seems to work.
Tested the following in vc++10 and g++ 4.4.
struct b { int i; b(int x) : i(x) {} };
struct a { int i; a() : i(0) { } operator b() { return i++ /* this works */, b(i); } };
a f(a&& x) { return x.i++ /* this works */, x; }
int main() { b b = f(a()); /* implicit operator b() cast; b.i will equal 2 */ }
A member function can change the member directly, but it can also delegate that responsibility:
struct Foo {
int x;
void Bar() { scanf("%d", &x); }
};
The current wording of the standard has the advantage that one doesn't need to argue whether this is a case of Bar changing the object. If we'd agree that scanf changes the object, then that's just another example.