473,406 Members | 2,847 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,406 software developers and data experts.

string object initialization


Hello
I am not sure why my compiler will not initialize
string e1("sam");
and will initialize
string e1 = "sam";

here is my code and the error.

thanks alot

********************code********************
#include <iostream>
#include <string>

using namespace std;

typedef struct
{
string firstname;
string lastname;
int age;
}
employees;

int main(){
employees e1, e2;
e1.firstname = "sam";
e1.lastname = "Jesse";
e1.age=11;

e2.firstname ("sam2");
e2.lastname("Jesse2");
e2.age(22);

cout << "employee e1\n\t" << e1.firstname << "\n\t"
<< e1.lastname << "\n\t" << e1.age << endl;
cout << "employee e2\n\t" << e2.firstname << "\n\t"
<< e2.lastname << "\n\t" << e2.age << endl;
}
********************Error********************
cd /home/sam/Exercies/ThinkingInC++/Vol1/C03/15/
make -k
g++ -g -c -o main.o main.cpp
main.cpp: In function `int main()':
main.cpp:20: error: no match for call to `(std::string) (const char[5])'
main.cpp:21: error: no match for call to `(std::string) (const char[7])'
main.cpp:22: error: call to non-function `employees::age'
make: *** [main.o] Error 1
make: Target `proj1' not remade because of errors.

Compilation exited abnormally with code 2 at Thu Jul 28 16:46:34
Jul 28 '05 #1
8 4167

"Baloff" <wa****@wash.edu> schrieb im Newsbeitrag
news:87************@wash.edu...

Hello
I am not sure why my compiler will not initialize
string e1("sam");
and will initialize
string e1 = "sam";

here is my code and the error.

thanks alot

********************code********************
#include <iostream>
#include <string>

using namespace std;

typedef struct
{
string firstname;
string lastname;
int age;
}
employees;

int main(){
employees e1, e2;
e1.firstname = "sam";
e1.lastname = "Jesse";
e1.age=11;

e2.firstname ("sam2");
e2.lastname("Jesse2");
e2.age(22);
These statements do not initialize, I think. As your error messages say,
operators/functions of string/int are called with these three statements.

cout << "employee e1\n\t" << e1.firstname << "\n\t"
<< e1.lastname << "\n\t" << e1.age << endl;
cout << "employee e2\n\t" << e2.firstname << "\n\t"
<< e2.lastname << "\n\t" << e2.age << endl;
}
********************Error********************
cd /home/sam/Exercies/ThinkingInC++/Vol1/C03/15/
make -k
g++ -g -c -o main.o main.cpp
main.cpp: In function `int main()':
main.cpp:20: error: no match for call to `(std::string) (const char[5])'
main.cpp:21: error: no match for call to `(std::string) (const char[7])'
main.cpp:22: error: call to non-function `employees::age'
make: *** [main.o] Error 1
make: Target `proj1' not remade because of errors.

Compilation exited abnormally with code 2 at Thu Jul 28 16:46:34

Jul 28 '05 #2
>> e2.firstname ("sam2");
e2.lastname("Jesse2"); It is not a string initialization, it is calling a function firstname()
with parameter "sam2" and no such function exists in struct employees.
In C++, You can't call consturctor in this way. string e1("sam");

It is perfectly fine. It is constructing the object by calling
constructor. But in object e2 , string is already constructed when u
write employees e2; with default constructor of string. and you are
thinking again calling a different constructor at same object.

In this case How will compiler differentiate whether u r calling a
function or constructor?So simply, It is not allowed in C++.

to call constructor of memeber objects, use initialization list of
your container. For example:
struct employees
{
string firstname;
string lastname;
int age;
employess() : firstname("Upashu2"),lastname("Balooff"),age(22) {
//////
} ////defining default constructor of
employees which call constructors
///////////////////////////////////////of member objects to initialize
them.
};

Jul 28 '05 #3
Also,
struct employees
{
string firstname;
string lastname;
int age;
employess() : firstname("Upashu2"),lastname("Balooff"),age(22) { }
///default construcot
employess(char* f,char* l, int a) : firstname(f),lastname(l),age(a)
{
//////
} //defining overloaded consturcotr
};

employess e2("jammes2", "jasse2",22);

Jul 28 '05 #4
"upashu2" <up*****@rediffmail.com> writes:
Also,
struct employees
{
string firstname;
string lastname;
int age;
employess() : firstname("Upashu2"),lastname("Balooff"),age(22) { }
///default construcot
employess(char* f,char* l, int a) : firstname(f),lastname(l),age(a)
{
//////
} //defining overloaded consturcotr
};

employess e2("jammes2", "jasse2",22);


now, what is more effecent, to have a constructor
inside the struct and do e1.firstname("some-name") or use the assigning
operator (=) with no constructor in the struct?

thanks
Jul 28 '05 #5
>> to have a constructor
inside the struct and do e1.firstname("some-name") You cann't do e1.firstname("......"); read my prevoius post.post #3
What u can do is employees e1("......"); see my post #4.
employess(char* f,char* l, int a) : firstname(f),lastname(l),age(a) {} Using iniatialization list in constructor call the copy constructor of
object (here for strings) .employess(char* f,char* l, int a) { firstname = f; lastname =l; age =a;}
ORemployees e1; e1.firstname = "....."

This results first constructing the string object (firstname, lastname)
with their default constructor. after that when u assign the value
using "=" , it calls overladed assignment operator to copy the value
from rightside object to leftside object. it will take Two steps to
initialize the object.

In your case , if u don't want to define the constructor, simply use
employees e1; e1.firstname ="...."; Don't think to write
e1.firstname(....) even by mistake , It is syntax of function call,
not initalization, you will never found such statements in C++ anywhere.

Jul 28 '05 #6
"Baloff" <wa****@wash.edu> wrote in message
news:87************@wash.edu...
int main(){
employees e1, e2;
At this point, all members of e1 and e2 have been initialized.
e1.firstname = "sam";
e1.lastname = "Jesse";
e1.age=11;
All of the above are assignments.
e2.firstname ("sam2");
e2.lastname("Jesse2");
e2.age(22);


Tho you think you are initializing, the objects are already
initialized above. You cannot initialize twice. That is why this syntax
is interpreted as a function call.

To answer your other question in a follow-up post: It is better to
have a constructor inside the struct, which initializes the strings
using the initializer list. The compiler might optimize your code above,
so it is just as fast, so the constructor with initializer-list might
not be faster with all compilers, but it will always be at least as fast
as the method above.

hth
--
jb

(reply address in rot13, unscramble first)
Jul 28 '05 #7
Baloff wrote:

"upashu2" <up*****@rediffmail.com> writes:
Also,
struct employees
{
string firstname;
string lastname;
int age;
employess() : firstname("Upashu2"),lastname("Balooff"),age(22) { }
///default construcot
employess(char* f,char* l, int a) : firstname(f),lastname(l),age(a)
{
//////
} //defining overloaded consturcotr
};

employess e2("jammes2", "jasse2",22);


now, what is more effecent, to have a constructor
inside the struct and do e1.firstname("some-name") or use the assigning
operator (=) with no constructor in the struct?


In general questions about efficiency can aonly be answered with:
you have to try it on your specific platform.

But in this case, think about the following.

If you do (in a version with no constructor in the struct)

employess e1;
e1.firstname = "jammes2";
e1.lastname = "jasse2";
e1.age = 22;

What is going on?
Well. First of all the e1 object comes into existence. For this the members
get initialized. In this specific case this means:
* firstname initializes to an empty string
* lastname initializes to an empty string
* age does nothing, since it is a builtin type
it contains a random value

Then the assignments are performed, which do
* change firstname from an empty string to "jammes2"
* change lastname from an empty string to "jasse2"
* age changes from some unspeficied random value to 22

Now contrast this with the version using a constructor in the struct.
When you do:
empoyess e2( "jammes2", "jasse2",22);
what is going on.

Well. First of all the e2 object comes into existence. For this the members
get intialized. In this specfic case this means:
* firstname instializes to "jammes2"
* lastname initializes to "jasse2"
* age initializes to 22

and that's it. Same end result.

Now compare both variants and answer the question:
Which of those 2 variants is likely to be more efficient
then the other?

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 28 '05 #8

"Baloff" <wa****@wash.edu> wrote in message news:87************@wash.edu...

Hello
I am not sure why my compiler will not initialize
string e1("sam");
and will initialize
string e1 = "sam";


You are not requesting an initialization with e1.firstname("sam2") above.
That is, until you provide the ctor that will carry out such initialization.
Since you haven't provided a ctor with parameters, the compiler is looking
for a function that matches that signature.

However, you can create a class that initializes its members through
parameters in the ctor. Note the initialization lists.

<snip>

#include <string>

class Employees
{
std::string firstname;
std::string lastname;
int age;
public:
Employees()
: firstname("unknown"), lastname("unknown"), age(0) { }
Employees(std::string fn, std::string ln, int n)
: firstname(fn), lastname(ln), age(n) { }
~Employees() { }

};

int main()
{
Employees e1("George", "Smith", 30);
}
Jul 28 '05 #9

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

Similar topics

106
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the...
2
by: Nathan | last post by:
Is there a way to convert a string to a CipherMessage? I am calling a function that decrypts a CipherMessage and returns the value. The only problem is when I want to use an encrypted value stored...
9
by: Steven T. Hatton | last post by:
This is from the draft of the previous version of the Standard: http://www.kuzbass.ru:8086/docs/isocpp/expr.html 2- A literal is a primary expression. Its type depends on its form...
8
by: KRoy | last post by:
I have a password stored in the Registry encrypted using System.Security.Cryptography DES Algorithm. I supplied it a password and a Initialization Vector. I am trying to decrypt it using the...
14
by: gustavo | last post by:
I was looking at the Sendmail's source code, and i've got confused about this kind of initialization: ------------------------ struct prival PrivacyValues = { { "public", PRIV_PUBLIC }, {...
7
by: xllx.relient.xllx | last post by:
Q1: What happens when you apply parenthesis to the class type name? Is the constructor for the class called and returns an object?, or what? in main...: MyClass(); // end
4
by: wesbland | last post by:
>From my understanding, when a string is stored in VB.NET and you look at it in the debugger, it has a quote on both sides to signify that it is a string as opposed to a char or int or whatever. ...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...

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.