473,320 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

returning an array from a class via a method.

36
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 5274
RedSon
5,000 Expert 4TB
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 Expert Mod 8TB
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
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 Expert 1GB
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
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 Expert 1GB
( 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
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...
4
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++...
5
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...
10
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. ...
0
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
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...
3
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"...
3
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...
2
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.