kkirtac <ka**********@gmail.comwrote in news:1188320088.558946.59700
@g4g2000hsf.googlegroups.com:
Hi, i have a class "myClass", and i want to return two instances of
the same class from a function. I define an array as follows :
"myClass sample[2] ;" and i initialize two instances: "myClass
sample1, sample2 ;"
"sample[0] = sample1 ; sample[1] = sample2 ; return sample ;" This
caused the error :
error C2512 : 'myClass' : no appropriate default constructor available
any idea how to return 2 instances and what is wrong with this
implementation..
Regards
I am guessing that the problem is that when you declare an array like:
myClass arr[2];
It actually will default construct two instances of myClass. The
message sounds like you don't have a default constructor.
The second problem you will have with an array is that when you return
one, it automatically converts the array reference into a pointer.
Sadly, this pointer will point to memory that is local to the function
and will therefore be invalid after the return.
There are a lot of ways to return two instances to the caller. The
easiest is to have the caller pass into you an array of pointers to
myClass or a struct with two pointers:
void func(myClass ** ppRet)
{
ppRet[0] = new myClass;
ppRet[1] = new myClass;
}
-or-
struct MyRet {
myClass * pFirst;
myClass * pSecond;
};
void func(MyRet & ret)
{
ret.pFirst = new myClass;
ret.pSecond = new myClass;
}
Alternately, you can make use to std::pair<and construct the returns:
std::pair<myClass *, myClass *func()
{
return std::make_pair(new myClass, new myClass);
}
or if myClass is more value oriented:
std::pair<myClass, myClassfunc()
{
return std::make_pair(myClass(), myClass());
}
If you have access to boost or TR1, you can look at boost::tuple to get
more perl-like multiple return value support.
Like I said earlier, there are lots of ways to do this, your imagination
is the limiting factor. The key things to remember is that if you
construct something on the stack in func, then you will have to copy it
to it's target and the target will usually be default constructed. If
you create something on the heap with new, then you are talking about
passing pointers around and not the class itself.
Hope that helps some,
joe