meow00
asked on
return type of a function ?
To C++ Experts,
We can return a reference, a point, or a copy of the object from a function. The object can also be const. Is it illegal to return a static object ?
If so, when is it used ?
i.e.
class A{} ;
const A* func(); //ok (right ?)
static A* func(); // is this allowed ? if so, when do we use it ?
Thanks a lot !
We can return a reference, a point, or a copy of the object from a function. The object can also be const. Is it illegal to return a static object ?
If so, when is it used ?
i.e.
class A{} ;
const A* func(); //ok (right ?)
static A* func(); // is this allowed ? if so, when do we use it ?
Thanks a lot !
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the answers and sorry for the late response, as I was out of town for a while.
This doesn't necessarily return a pointer to a static object. There is no way of indicating whether the object pointed to is in static memory or in the free store. There is nothing wrong with returning a pointer to a static object.
Having this declared outside a class is deprecated use of the keyword static. It is equivalent to putting a function into an unnamed namespace making it visible only to the module in which it is defined.
i.e.
namespace {
A* func();
}
Having this declared within a class means that the function may be called without instantiating the class, because the function does not use any instance variables.
i.e.
class X {...};
class foo {
....
static X* func(); /* Returns a pointer to an instance of X, but doesn't make use of any of the non-static class members of foo in doing so */
};