473,804 Members | 3,308 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning an array from a class via a method.

36 New Member
This is a pretty specific problem, so I'm not posting the whole program. ( but I can if you really need it )
I have a good understanding of what's wrong, I just can't figure out how to combat it.

Basically, I was fooling around with copy constructors, and overloaded assignment operators, and I ran into an array return problem.

I made a method to return a character array from a class:

Expand|Select|Wrap|Line Numbers
  1. class entry
  2. {
  3.   char name[20];
  4. public:
  5.   char show_name(){return *name;}   // I tried both  'name',  &  'name[]',  but 
  6.                                     // neither worked.
  7.   // other code -- inconsequential right now. 
  8. }
  9.  
Then, I made my objects, and used the CC/OAO:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   entry object1("Object 1", 25.50);  // Initializes the character array, and a float.
  4.  
  5.   entry object2 = object1;  // Using overloaded assignment operator.
  6.  
  7.   entry object3(object2);  // Using copy constructor.
  8.  
  9. // Here's where the problem comes into play:
  10. //   ( code has been extremely condensed )
  11.  
  12.   std::cout << object2.show_name() << "\n";
  13.   std::cout << object3.show_name() << "\n";
  14.  
  15.   return 0;
  16. }
  17.  
The result of the 'cout':

O
O

As you can imagine, I am a bit perplexed.

I know the copy constructor, and overloaded assignment operators worked,
because I made another method to display the values from the method:

void show(){cout << name << "\n";}

It displayed fine. However, I want to get the array out of the class.

I tried using 'strcpy' to put the value into a new array, a pointer with new memory, etc.
I know someone out there is going to suggest vectors, but I haven't gotten that far in my learning.

( I'm also working on my C-style string abilities,
so that's why I didn't use a C++ string object there. )

I appreciate any help.

Lates,
-*Soneji
May 30 '07 #1
6 5311
RedSon
5,000 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. class entry
  2. {
  3.   char name[20];
  4. public:
  5.   char show_name(){return *name;}   // I tried both  'name',  &  'name[]',  but 
  6.                                     // neither worked.
  7.   // other code -- inconsequential right now. 
  8. }
  9.  
Your method must have a proper return type, if you want to return a pointer then you should say so in your method declaration. You can also see if there is a generic pointer macro definition like LPVOID.
May 30 '07 #2
weaknessforcats
9,208 Recognized Expert Moderator Expert
Functions return a type. An array is not a type. Rather it is a bunch of some type.

You can return the address of the array, however.

Expand|Select|Wrap|Line Numbers
  1. class entry
  2. {
  3.   char name[20];
  4. public:
  5.    char* show_name(){return name;}  
  6.   //...
  7. };
  8.  
However, this is extremely bad design. The reason is that you expose your private array. That means it can be changed without needing to use a member function. It also requires that the object not be deleted until all of the returned pointers are out of scope. Otherwise, when this entry object goes out of scope, the name array dies with it and all the exposed pointers are now invalid.
You will crash shortly thereafter and, unfortunately, the location of the crash will be far, far away from the cause.

This class should be using a string and the method should return a copy of it:

Expand|Select|Wrap|Line Numbers
  1. class entry
  2. {
  3.      string name
  4.    public:
  5.      string show_name(){return *name;} 
  6.      //etc... 
  7. };
  8.  
May 30 '07 #3
Soneji
36 New Member
Thanks for the answers!

I can't believe I missed that. I thought, at one time I had added the asterisk to
the return type, but it still wouldn't compile.

I tested it, and I was right. BUT! After removing the dereference from the returned
name ( return *name; <-- That one ) it ran perfectly!

I really appreciate the answers.

Also, thanks for the warning about using the array this way.

It didn't occur to me that the array could be altered after it was returned, but
as soon as I saw your post, it hit me like a ton of bricks. ( This, of course, raises a new question though )

The scope problem has me a bit worried. This is another thing I didn't think about. ( This also leads into the new question... )


My new question(s): Given the new information I now have ( thanks again, to you two ), would it be better not to use arrays inside a class at all?

Or, at the very least, should I relegate them to public access?

But, even if I only use them with public access, this still doesn't address the scope issue.
Is there any way to effectively use an array in a class without leaving an inordinate amount of out-of-scope pointers roaming my program?

*sigh* It can be so confusing. Maybe I should have chosen Python, or Perl as my first language. ( I'll get to them. I swear! )

Thanks again for the help RedSon, and weaknessforcats . I really appreciate it!

Lates,

-*Soneji

P.S. I know I should have used a string, but I understand them very well, and I still need some work on my arrays. ( obviously :) )
May 30 '07 #4
AdrianH
1,251 Recognized Expert Top Contributor
Thanks for the answers!

I can't believe I missed that. I thought, at one time I had added the asterisk to
the return type, but it still wouldn't compile.

I tested it, and I was right. BUT! After removing the dereference from the returned
name ( return *name; <-- That one ) it ran perfectly!

I really appreciate the answers.

Also, thanks for the warning about using the array this way.

It didn't occur to me that the array could be altered after it was returned, but
as soon as I saw your post, it hit me like a ton of bricks. ( This, of course, raises a new question though )
Memory management is a pain in the ass. Things like pointers require great care. A useful approch is to think of pointers as 'giving' an object, where as passing a reference is like 'lending' an object. That paradigm doesn't work so well for c-strings as they have to be pointers, in which case documentation or using the string class is the best bet.

Passing a string (or any object) is giving you the object, because it is copied.

For general use, a string object is best, using a c-string should be reserved for when you have decided that it is the best route to go because the design requires it (embedded app with limited memory). And in that case you need to think about life span.

A c-string should never be kept, but requested when needed, used and then the pointer discarded. Deletion should only be done by the 'owner' (i.e. the class that gave it) or else it can become confusing.

Much easier to deal with string objects.

The scope problem has me a bit worried. This is another thing I didn't think about. ( This also leads into the new question... )


My new question(s): Given the new information I now have ( thanks again, to you two ), would it be better not to use arrays inside a class at all?

Or, at the very least, should I relegate them to public access?

But, even if I only use them with public access, this still doesn't address the scope issue.
Is there any way to effectively use an array in a class without leaving an inordinate amount of out-of-scope pointers roaming my program?

*sigh* It can be so confusing. Maybe I should have chosen Python, or Perl as my first language. ( I'll get to them. I swear! )

Thanks again for the help RedSon, and weaknessforcats . I really appreciate it!

Lates,

-*Soneji

P.S. I know I should have used a string, but I understand them very well, and I still need some work on my arrays. ( obviously :) )
Again arrays are not exactly bad, they just require a lot of care (so much so that they can be bad if you don't establish proper protocols in your design).

The only reason to use them (and even then, you should think twice) is when you have very limited memory resources. Try using a vector instead.


Adrian
May 31 '07 #5
Soneji
36 New Member
I see. I'll keep that in mind. Strings it is! Thanks for the response Adrian.

Thanks for all the help everybody!

I always hate asking for help. I like to figure these things out myself,
and I try to exhaust all avenues that I can think of before I do ask.

( even though most of the time, the answer is simple. -- Like missing the asterisk this time. )

( plus, I have seen some forums, where the people that respond are real... ummm.... you know.... not nice. )

But everyone that has responded to the few question I have asked here on 'thescripts' has been very nice.
It's nice to see that in this day of "Keyboard Courage".

Thanks everyone! Hopefully one day ( soon ), I'll be one of the people helping,
instead of being helped.

All the best,

-*Soneji
May 31 '07 #6
AdrianH
1,251 Recognized Expert Top Contributor
( plus, I have seen some forums, where the people that respond are real... ummm.... you know.... not nice. )

But everyone that has responded to the few question I have asked here on 'thescripts' has been very nice.
It's nice to see that in this day of "Keyboard Courage".

Thanks everyone! Hopefully one day ( soon ), I'll be one of the people helping,
instead of being helped.

All the best,

-*Soneji
Most of the time we are nice. The only times that we might not be is when users whine that all they want is the code, or start posting the question from the text and figure we are an answer machine.

And even then we try and be civil. ;)


Adrian
May 31 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
14037
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
4
1680
by: mchoya | last post by:
I'm so frustrated. I'm beginning school next week and I have been working on a simple program for several days now without being able to complete it. (Though I have brushed up on a lot of C++ while trying.) I realize this code is long but, I'm not sure of any other way to display the issue. The header file and ?implementation file work. (This assignment was building on another in which I created the header and implementation with a...
5
3115
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 able to return an array of GUID. I remember (not sure) that the concept of arrays does not really...
10
10298
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
0
1339
by: Mrozik | last post by:
after parsing WSDL definition of java WebService, C# proxy class contains data strutures (I'm using RPC\encoded): public class DateString { /// <remarks/> public string value; }
5
19604
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return an Array instead of an ArrayList. Now I get the message when I try to run just my webservice...
3
2880
by: Sinex | last post by:
Hi, I have the following type definition in my wsdl. <xs:complexType name="employeeType"> <xs:all> <xs:element name="FirstName" type="xs:string" /> <xs:element name="LastName" type="xs:string" /> </xs:all> </xs:complexType>
3
1754
by: Peter Oliphant | last post by:
Below are the definitions of two classes. VList creates two static integer arrays (v_0, v_1), creates an array of pointers to these arrays (vlist), and has a public method to return a pointer to the corresponding integer array based on its index into vlist (Element( index )) . MyClass contains an instance of VList, and then tries to call Element(1) and get a pointer to the appropriate integer list (v_1). But what comes out the debugger...
2
1878
by: FutureShock | last post by:
I am using a registration class to process a registration form and need some opinions on returning error messages. I am self referring the page on submit. I would like to send each form field to the class for processing (validating, sanitizing, etc..) So far no problem. Now I am throwing ideas around on how best to check for error messages to the users.
0
9706
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10571
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10075
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9143
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5520
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.