473,586 Members | 2,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Allocating and returning new class in function



Hello to all,

My question is on right way of returning newly created class from a function
(and thus, from class method or operator). As I currently see it, there are
two different ways to do that. One way is to create new class as a local
(automatic) variable in function and then to return it:

TClass AutoDummy (...) {

TClass newClass;

...

return newClass; // return class from the local stack

}

The other way is to create new class dynamically with the operator 'new' and
then to return new class from a function. This would require caller to
invoke delete on this class afterwards.

TClass DynamicDummy (...) {

TClass *newClass;

newClass = new TClass;

...

return *newClass; // new class is dynamically allocated

}

(Ignore the aspect of whether it should be returned by address or value).

While I was programming in C and I needed to instantiate something new in a
function, I would instantiate it dynamically and return pointer.
Furthermore, I read in comp.lang.c FAQ by Steve Summit that function should
never return pointer to items allocated on stack. That seems okay, caller
should not rely on content of stack that is released when function is done.
But, my lecturers on college create new classes locally and return them from
functions. In book 'Data Structures with C++ and STL' by W. Ford and W.
Topp, I saw examples which do this by creating a new anonymous class. I'm
interested what is the right way to do this, in both the matter of validity
and accurate programming style?

Thanks in advance,

Milan Gornik (mgornik dot eunet dot yu)

Jul 23 '05 #1
3 1826
"Milan Gornik" <no****@nospam. com> schrieb im Newsbeitrag news:d2******** **@news.eunet.y u...


Hello to all,



My question is on right way of returning newly created class from a function
(and thus, from class method or operator). As I currently see it, there are
two different ways to do that. One way is to create new class as a local
(automatic) variable in function and then to return it:



TClass AutoDummy (...) {

TClass newClass;

...

return newClass; // return class from the local stack

}



The other way is to create new class dynamically with the operator 'new' and
then to return new class from a function. This would require caller to
invoke delete on this class afterwards.



TClass DynamicDummy (...) {

TClass *newClass;



newClass = new TClass;

...

return *newClass; // new class is dynamically allocated

}



(Ignore the aspect of whether it should be returned by address or value).


You cannot ignore that aspect. If your function creates some local objects (on the stack) it must return it by value. If it allocates an object using new (on the heap) it must return its address, not a copy of the object. That would cause a memory leak. So never write a function like your DynamicDummy.

HTH
Heinz

BTW - functions do not create classes. You create them. Functions only create instances of classes.

Jul 23 '05 #2
In the first case you are not returning something on your stack, but a
copy of it. Compiler will call a copy constructor to copy newClass on
the stack to the place where resulting TClass should reside, so
everything will be fine.

Milan Gornik wrote:
Hello to all,

My question is on right way of returning newly created class from a function
(and thus, from class method or operator). As I currently see it, there are
two different ways to do that. One way is to create new class as a local
(automatic) variable in function and then to return it:

TClass AutoDummy (...) {

TClass newClass;

...

return newClass; // return class from the local stack

}

The other way is to create new class dynamically with the operator 'new' and
then to return new class from a function. This would require caller to
invoke delete on this class afterwards.

TClass DynamicDummy (...) {

TClass *newClass;

newClass = new TClass;

...

return *newClass; // new class is dynamically allocated

}

(Ignore the aspect of whether it should be returned by address or value).

While I was programming in C and I needed to instantiate something new in a
function, I would instantiate it dynamically and return pointer.
Furthermore, I read in comp.lang.c FAQ by Steve Summit that function should
never return pointer to items allocated on stack. That seems okay, caller
should not rely on content of stack that is released when function is done.
But, my lecturers on college create new classes locally and return them from
functions. In book 'Data Structures with C++ and STL' by W. Ford and W.
Topp, I saw examples which do this by creating a new anonymous class. I'm
interested what is the right way to do this, in both the matter of validity
and accurate programming style?

Thanks in advance,

Milan Gornik (mgornik dot eunet dot yu)



Jul 23 '05 #3

Thank you for your replies, Heinz and Yuriy.

I noticed afterwards that I made quite a big mistake with second example. I
tried to illustrate something else and than returned dereferenced pointer,
thus losing a chance to delete object afterwards. And I wrote 'class' many
times referring to object, instead. Never mind, I got good answers. Thanks
again!
"Yuriy Solodkyy" <so*****@tamu.p ut_edu_here> wrote in message
news:d2******** **@news.tamu.ed u...
In the first case you are not returning something on your stack, but a
copy of it. Compiler will call a copy constructor to copy newClass on
the stack to the place where resulting TClass should reside, so
everything will be fine.

Milan Gornik wrote:
Hello to all,

My question is on right way of returning newly created class from a function (and thus, from class method or operator). As I currently see it, there are two different ways to do that. One way is to create new class as a local
(automatic) variable in function and then to return it:

TClass AutoDummy (...) {

TClass newClass;

...

return newClass; // return class from the local stack

}

The other way is to create new class dynamically with the operator 'new' and then to return new class from a function. This would require caller to
invoke delete on this class afterwards.

TClass DynamicDummy (...) {

TClass *newClass;

newClass = new TClass;

...

return *newClass; // new class is dynamically allocated

}

(Ignore the aspect of whether it should be returned by address or value).
While I was programming in C and I needed to instantiate something new in a function, I would instantiate it dynamically and return pointer.
Furthermore, I read in comp.lang.c FAQ by Steve Summit that function should never return pointer to items allocated on stack. That seems okay, caller should not rely on content of stack that is released when function is done. But, my lecturers on college create new classes locally and return them from functions. In book 'Data Structures with C++ and STL' by W. Ford and W.
Topp, I saw examples which do this by creating a new anonymous class. I'm interested what is the right way to do this, in both the matter of validity and accurate programming style?

Thanks in advance,

Milan Gornik (mgornik dot eunet dot yu)


Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
14011
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers
3
4494
by: Jochen Zeischka | last post by:
I'm puzzled. When compiling this: template<class ValRes, class Val1, class Val2> Veld<ValRes>& mult(Veld<ValRes>& res, const Veld<Val1>& v1, const Veld<Val2>& v2) { // something return res; } the compiler says:
4
3804
by: Shailesh Humbad | last post by:
If a class has no constructor/destructor, is not part of an inheritance heirarchy, is not a template, and only contains members of integral types, then is it okay to allocate it off the heap? Is this bad style? For example: class myClass { public: int myInt;
18
2125
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
5
3077
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the function below is returning a pointer to pointers who are GUID. I am trying to write a wrapper to use in my VB code and what I would prefer to do is be...
11
1880
by: Justin Naidl | last post by:
class Foo { protected: char foo_stuff; public: char* get_foo_stuff(); } Given the above example. What I want to know is the "proper/standard" way
10
2564
by: junky_fellow | last post by:
What is the correct way of dynamically allocating a 2d array ? I am doing it the following way. Is this correct ? #include <stdlib.h> int main(void) { int (*arr)(3); arr = malloc(sizeof(*arr) * 4); /* I want to dynamically allocate
23
2922
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or method. QUOTE ENDS HERE I have never heard anyone else say that it is a problem for a function
6
5167
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t = malloc(n*sizeof(r)) and (to a degree) by the surrounding error checking.
0
7911
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8200
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7954
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8215
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6610
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3836
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1448
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.