473,799 Members | 3,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner question(s): Passing string into method

How do you pass a string into a function and set the contents of an internal
string field to be the contents of the string passed into the Set method?

My attempt at doing this below doesn't work and produces errors such as
"class 'User' has an illegal zero-sized array" and "'=' : cannot convert
from 'char[]' to char[]'".

/* User.h */
class User
{
public:
void SetUserID(int u);
void SetName(char n[]);

private:
int user_id;
char name[];
};
/* END CLASS DEFINITION User */
#endif /* __USER__ */
/* User.cpp */
#include "User.h"

void User::SetUserID (int u)
{
user_id = u;
}
void User::SetName(c har n[])
{
name = n;
}

P.S. How do you re-initialise an object e.g. in Java it's "new
ObjectName()", what's the C++ syntax?
Oct 13 '05 #1
4 3452
Hi,

--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"James" <ja***@hotmail. com> wrote in message
news:uq******** ******@newsfe2-gui.ntli.net...
How do you pass a string into a function and set the contents of an
internal string field to be the contents of the string passed into the Set
method?

My attempt at doing this below doesn't work and produces errors such as
"class 'User' has an illegal zero-sized array" and "'=' : cannot convert
from 'char[]' to char[]'".

/* User.h */
class User
{
public:
void SetUserID(int u); ------> void SetName(char *n);
private:
int user_id; ------> char *name; };
/* END CLASS DEFINITION User */
#endif /* __USER__ */
/* User.cpp */
#include "User.h"

void User::SetUserID (int u)
{
user_id = u;
} //> void User::SetName(c har n[])
------>void User::SetName(c har *n)
{
name = n;
}

Just pass a pointer to char. However be careful with above code since 'name'
now points to the same memory as the pointer you passed in your routine. You
are more likely to want to do the following:

void User::SetName(c har *n)
{
// Delete any possibly previously allocated name or do nothing if name is
0
delete[] name;
name = new char[ strlen( n ) + 1 ];
strcpy( name, n );
// DON' T forget to add delete[] name in the destructor and initialize
name with 0 in the constructor
}

Or what I prefer just use the STL string class

#include <string>
using namespace std;

void User::SetName( const string& Name )
{
this->name = Name;
}

Regards, Ron AF Greve P.S. How do you re-initialise an object e.g. in Java it's "new
ObjectName()", what's the C++ syntax?

Oct 13 '05 #2

"James" <ja***@hotmail. com> wrote in message
news:uq******** ******@newsfe2-gui.ntli.net...
How do you pass a string into a function and set the contents of an
internal string field to be the contents of the string passed into the Set
method?

My attempt at doing this below doesn't work and produces errors such as
"class 'User' has an illegal zero-sized array" and "'=' : cannot convert
from 'char[]' to char[]'".

/* User.h */
#include <string>
class User
{
public:
void SetUserID(int u);
void SetName(char n[]);
void SetName(const std::string& n);

private:
int user_id;
char name[];
std::string name;
};
/* END CLASS DEFINITION User */
#endif /* __USER__ */
I'll assume this '#endif' matches an '#ifdef'
or '#ifndef' which you didn't include here.
But note that identifiers beginning with
two underscores are reserved to the implementation,
you should choose a different name.


/* User.cpp */
#include "User.h"
#include <string>

void User::SetUserID (int u)
{
user_id = u;
}
void User::SetName(c har n[])
void User::SetName(c onst std::string& n)
{
name = n;
}

P.S. How do you re-initialise an object e.g. in Java it's "new
ObjectName()", what's the C++ syntax?


In C++ 're-initialize' has no meaning. An object can
be initialized with a value when it is created. After
that, its value can only be changed via assignment.
Initialization and assignment are not the same thing.

int i = 42; /* create and initialize 'i' */
i = 0; /* change value of 'i' */

-Mike
Oct 13 '05 #3
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:HF******** *******@newsrea d1.news.pas.ear thlink.net...
<snip!>

Thanks guys.
Oct 13 '05 #4
Hi

James wrote:
How do you pass a string into a function and set the contents of an
internal string field to be the contents of the string passed into the Set
method?
Just use a std::string.

#include <string>

class User
{
public:
void SetName(const std::string& n) { name = n; }
// or maybe (std::string n) for now...

private:
std::string name;
};
P.S. How do you re-initialise an object e.g. in Java it's "new
ObjectName()", what's the C++ syntax?


Pardon? AFAIK you cannot re-initialize any object in Java, as little as you
can in C++. In Java as well as in C++, "new ClassName()" creates a new
object, just as the name says.

Markus

Oct 13 '05 #5

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

Similar topics

2
1994
by: Brian | last post by:
I am trying to work through a PHP book that I bought a year or so ago, "Essential PHP" by Christopher Cosentino. In the beginning of the book, after the Hello, World .php file, you get to a two-parter : a form that sends it's results to another .php file, that then displays those results. Nothing I have been able to do has gotten this type of passing to work. Checking the URL string for the second page, it properly shows the values :
1
2627
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
1
2842
by: Natalia DeBow | last post by:
Hi, I am working on a Windows-based client-server application. I am involved in the development of the remote client modules. I am using asynchronous delegates to obtain information from remote server and display this info on the UI. From doing some research, I know that the way my implementation works today is not thread-safe, because essentially my worker thread updates the UI, which is BAD. So, here I am trying to figure out how...
16
5438
by: dev | last post by:
Hello, How can the following code be converted to VB.Net? I am mostly interested in how to handle the StrPtr calls in the function. Private Declare Function PathRelativePathToW Lib "shlwapi.dll" _ (ByVal pszPath As Long, _ ByVal pszFrom As Long, _ ByVal dwAttrFrom As Long, _ ByVal pszTo As Long, _ ByVal dwAttrTo As Long) As Boolean
1
1918
by: hl | last post by:
Hi, I'm a beginner and need a little help with getting data back from a web service. I am using VB.Net and have added a web reference to a Wsdl that was provided to me. My reference.vb file that was generated has the following code at the end. <System.Xml.Serialization.SoapTypeAttribute("Map",
14
1848
by: Mr Newbie | last post by:
I am often in the situation where I want to act on the result of a function, but a simple boolean is not enough. For example, I may have a function called isAuthorised ( User, Action ) as ????? OK, this function may return a boolean, and if this is true, then no message back is really required, but if it fails then some supporting message needs to be returned to the calling code. As I see it there are a few options.
6
1444
by: Chris | last post by:
Hi all, I've recently discovered the joys of tag :) I have a ListView which is populated with strings from a List<>, and each ListView item is linked to the relevant object in List<> using Tag. The ListView is on a parent form, and I have a child form which adds items to List<>. So I pass the List<> by ref*, the relevant objects are created in the List<> and the ListView is updated in the parent form. I'm now trying to edit items in the...
5
4792
by: Jacky Luk | last post by:
import java.awt.Graphics; public class printtest extends java.applet.Applet { public void init() { } public void paint (Graphics g) {
6
1710
by: RSH | last post by:
I am still trying to grasp the use of real world Objects and how to conceptualize them using a business scenerio. What I have below is an outline that I am wrestling with trying to figure out a class structure:\ Top level Objects: Companies Employees
0
9688
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
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10490
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
10260
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10243
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7570
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
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3762
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.