rjc@geech.gnu.ai.mit.edu (Ray Cromwell) (04/12/91)
I have been studying C++ source lately and I've noticed an odd construct in some type declarations. For instance in Complex.h you see member functiuons declared as: Complex& Complex(double re, double im); ^^ Is this just a new formatting style encouraged in C++ or a new use of the & operator. Why not write: Complex &Complex(double re, double im); Or Complex *Complex(double re, double im); Could someone explain the difference. Both declarations return a reference to a class Complex. Does it have something to do with the calling method? (Complex.function() vs Complex->function()) ? -- /~\_______________________________________________________________________/~\ |n| rjc@albert.ai.mit.edu Amiga, the computer for the creative mind. |n| |~| .-. .-. |~| |_|________________________________| |_| |________________________________|_|
davew@panache.cs.umd.edu (David G. Wonnacott) (04/12/91)
In article <1991Apr11.181205.22641@mintaka.lcs.mit.edu> rjc@geech.gnu.ai.mit.edu (Ray Cromwell) writes: > > For instance in Complex.h you see member functiuons declared as: > Complex& Complex(double re, double im); > ^^ Actually, I don't see anything like that in Complex.h. It looks like you have a complex constructor with a return type, which is illegal (at least in AT&T C++ -- and I checked the g++ headers on my system and they show no such thing). If you have been declaring return types for constructor functions, you should look again at the section on constructors in your favorite C++ book. In any case, the question about return type declarations makes sense for functions other than constructors and destructors, so, taking the liberty of re-nameing your function make_complex, > Is this just a new formatting style encouraged in C++ or a new >use of the & operator. Why not write: > Complex &make_complex(double re, double im); These two declarations are equivalent, much as "char* p" and "char *p" are the same. The choice is a matter of style. Some people like the first to show that the "*" is part of the type information, not the identifier. Others prefer the second because it extends better to multi-pointer declarations like "char *p, *q". > Or > Complex *make_complex(double re, double im); This, on the other hand, is quite different. It returns a pointer, not a reference, so you have to explicitly follow the pointer (using unary * or ->) returned by the function. For example, you would write i = *make_complex(0, 1); /* funciton returns pointer */ instead of i = make_complex(4, 5); /* function returns reference or value */ -- David Wonnacott davew@tove.cs.umd.edu Although the moon is smaller than the earth, it is further away.