473,761 Members | 8,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with constructor call of a string class

Hello experts,

I have the following code me.

=cat mystring.h
#include<iostre am>
using namespace std;

class mystring
{
char* p;
int capacity;
int len;
enum {DEF_SIZE = 100};
public:
// Constructors
mystring();
mystring(int size);
mystring(const char* str);

// Iniializer
void init(int size = DEF_SIZE);

//Destructor
~mystring();

//Copy Constructor
mystring(mystri ng&);

//Assignment Operator
mystring& operator = (mystring&);

//Display String
void display();

};

=cat mystring.cpp
#include<iostre am>
using namespace std;

#include "mystring.h "

//Constructors
mystring::mystr ing()
{
cout << "Default Constructor" << endl;
init();
len = 0;
}

mystring::mystr ing(int size)
{
cout << "Constructo r having size" << endl;
init(size);
len = 0;
}

mystring::mystr ing(const char* str)
{
cout << "Constructo r with string argument" << endl;
int length = strlen(str);
init(length + 1);
len = length + 1;
strcpy(p, str);
}

void mystring::init( int size)
{
p = new char[size];
capacity = size;
}

mystring::~myst ring()
{
cout << "Destructor " << endl;
delete p;
p = NULL;
}
mystring::mystr ing(mystring& other)
{
cout << "Copy Constructor" << endl;
delete p;
p = new char[strlen(other.p) + 1];
strcpy(p,other. p);
}

mystring& mystring::opera tor=(mystring& other)
{
cout << "Assignment Operator" << endl;
if(this == &other)
return *this;
delete p;
p = new char[strlen(other.p) +1];
strcpy(p,other. p);
return *this;
}

void mystring::displ ay()
{
cout << *p << endl;
cout << "Length of string is " << len << endl;
cout << "Capacity of the string is " << capacity << endl;
}

=cat str.cpp
#include<iostre am>
using namespace std;
#include "mystring.h "

int main()
{
mystring s = "Nitin";
return 0;
}

Compiling this gives error.

=g++ mystring.cpp str.cpp
str.cpp: In function `int main()':
str.cpp:7: no matching function for call to
`mystring::myst ring(mystring)'
mystring.h:24: candidates are: mystring::mystr ing(mystring&)
mystring.h:15: mystring::mystr ing(const char*)
mystring.h:14: mystring::mystr ing(int)
str.cpp:7: initializing temporary from result of
`mystring::myst ring(const
char*)'

Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?

Thanks in advance.

Feb 6 '07 #1
7 2710
* dragoncoder:
>
Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?
A temporary (the actual argument) can't be bound to a reference to
non-const.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 6 '07 #2
the form for a copy constructor uses the const key word. When you use
the = operator, it calls the copy constructor. Since you don't have a
mystring(const mystring&) constructor, the compiler doesn't really
know what your copy constructor is.

On Feb 6, 9:45 am, "dragoncode r" <pktiw...@gmail .comwrote:
Hello experts,

I have the following code me.

=cat mystring.h
#include<iostre am>
using namespace std;

class mystring
{
char* p;
int capacity;
int len;
enum {DEF_SIZE = 100};
public:
// Constructors
mystring();
mystring(int size);
mystring(const char* str);

// Iniializer
void init(int size = DEF_SIZE);

//Destructor
~mystring();

//Copy Constructor
mystring(mystri ng&);

//Assignment Operator
mystring& operator = (mystring&);

//Display String
void display();

};

=cat mystring.cpp
#include<iostre am>
using namespace std;

#include "mystring.h "

//Constructors
mystring::mystr ing()
{
cout << "Default Constructor" << endl;
init();
len = 0;

}

mystring::mystr ing(int size)
{
cout << "Constructo r having size" << endl;
init(size);
len = 0;

}

mystring::mystr ing(const char* str)
{
cout << "Constructo r with string argument" << endl;
int length = strlen(str);
init(length + 1);
len = length + 1;
strcpy(p, str);

}

void mystring::init( int size)
{
p = new char[size];
capacity = size;

}

mystring::~myst ring()
{
cout << "Destructor " << endl;
delete p;
p = NULL;}

mystring::mystr ing(mystring& other)
{
cout << "Copy Constructor" << endl;
delete p;
p = new char[strlen(other.p) + 1];
strcpy(p,other. p);

}

mystring& mystring::opera tor=(mystring& other)
{
cout << "Assignment Operator" << endl;
if(this == &other)
return *this;
delete p;
p = new char[strlen(other.p) +1];
strcpy(p,other. p);
return *this;

}

void mystring::displ ay()
{
cout << *p << endl;
cout << "Length of string is " << len << endl;
cout << "Capacity of the string is " << capacity << endl;

}

=cat str.cpp
#include<iostre am>
using namespace std;
#include "mystring.h "

int main()
{
mystring s = "Nitin";
return 0;

}

Compiling this gives error.

=g++ mystring.cpp str.cpp
str.cpp: In function `int main()':
str.cpp:7: no matching function for call to
`mystring::myst ring(mystring)'
mystring.h:24: candidates are: mystring::mystr ing(mystring&)
mystring.h:15: mystring::mystr ing(const char*)
mystring.h:14: mystring::mystr ing(int)
str.cpp:7: initializing temporary from result of
`mystring::myst ring(const
char*)'

Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?

Thanks in advance.


Feb 6 '07 #3
* mike:
the form for a copy constructor uses the const key word. When you use
the = operator, it calls the copy constructor. Since you don't have a
mystring(const mystring&) constructor, the compiler doesn't really
know what your copy constructor is.
First, please don't top-post in this newsgroup -- see the FAQ.

Now, there are an infinite number of possible copy constructor signatures.

However, with one formal argument there are only four, corresponding to
the four possible combinations of having or not having 'volatile' and
'const'. Of these four, two have 'const', and two don't. As an example
of a copy constructor with non-const argument, check out std::auto_ptr.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 6 '07 #4
On Feb 6, 11:53 am, "Alf P. Steinbach" <a...@start.now rote:
* dragoncoder:
Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?

A temporary (the actual argument) can't be bound to a reference to
non-const.
I am sorry I still don't get it. Where is the copy constructor
involved here? I am trying to call the constructor with the "const
char*" argument. Please explain.

Feb 6 '07 #5
* dragoncoder:
On Feb 6, 11:53 am, "Alf P. Steinbach" <a...@start.now rote:
>* dragoncoder:
>>Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?
A temporary (the actual argument) can't be bound to a reference to
non-const.

I am sorry I still don't get it. Where is the copy constructor
involved here? I am trying to call the constructor with the "const
char*" argument. Please explain.
Except for possible optimization, which doesn't affect the requirements
on the string class, the statement

mystring s = "Nitin";

is equivalent to

mystring temp( "Nitin" );
mystring s( temp );

for some unique name 'temp'.

Repeat: even though just about any compiler optimizes away the
temporary, i.e. you don't get an actual copy constructor call, the copy
constructor must be available to do the job as if no optimization.

...

OK, lets go through the rest of the code, also.

=cat mystring.h
#include<iostre am>
Not necessary since iostreams aren't used in the header.

using namespace std;
Never have 'using namespace std;' in a header.

class mystring
{
char* p;
int capacity;
int len;
enum {DEF_SIZE = 100};
Reserve all uppercase identifiers for macros.

public:
// Constructors
mystring();
mystring(int size);
Naming: here you probably mean capacity, not size.

mystring(const char* str);

// Iniializer
void init(int size = DEF_SIZE);
Should not be public.

//Destructor
~mystring();

//Copy Constructor
mystring(mystri ng&);
Needs 'const' for the argument.

//Assignment Operator
mystring& operator = (mystring&);
Needs 'const' for the argument.

//Display String
void display();
OK as a debugging aid while developing the class, but after that, will
bind use of the class to some particular i/o environment, so ungood.
>
};

=cat mystring.cpp
#include<iostre am>
using namespace std;

#include "mystring.h "
It's a good idea to include the module header as the very first thing in
the implementation file (not after anything else, except comments), to
make more sure that it includes everything necessary.
//Constructors
mystring::mystr ing()
{
cout << "Default Constructor" << endl;
init();
len = 0;
}

mystring::mystr ing(int size)
{
cout << "Constructo r having size" << endl;
init(size);
len = 0;
}

mystring::mystr ing(const char* str)
{
cout << "Constructo r with string argument" << endl;
int length = strlen(str);
init(length + 1);
len = length + 1;
Although 'len' doesn't seem to be used for anything, if it's meant to
represent the length of the string then surely it should be 'length',
not 'length+1'.

strcpy(p, str);
}

void mystring::init( int size)
{
p = new char[size];
capacity = size;
}

mystring::~myst ring()
{
cout << "Destructor " << endl;
delete p;
p = NULL;
Assignment of NULL unnecessary - the destructor call is the last thing
that ever happens with this object.

}
mystring::mystr ing(mystring& other)
{
cout << "Copy Constructor" << endl;
delete p;
p has not been initialized, so this is Undefined Behavior.

p = new char[strlen(other.p) + 1];
strcpy(p,other. p);
Fields of 'other' not copied.

}

mystring& mystring::opera tor=(mystring& other)
{
cout << "Assignment Operator" << endl;
if(this == &other)
return *this;
delete p;
p = new char[strlen(other.p) +1];
At this point you may get an exception. OK, it's not a practical
consideration, because when you run out of memory there's not much to do
except terminate. But as a general principle, strive to create
exception safe code -- here you'd leave the object with an invalid 'p'
member.

The 'swap' idiom for assignment helps with exception safe assignment.

strcpy(p,other. p);
return *this;
}

void mystring::displ ay()
{
cout << *p << endl;
cout << "Length of string is " << len << endl;
cout << "Capacity of the string is " << capacity << endl;
}

=cat str.cpp
#include<iostre am>
using namespace std;
#include "mystring.h "

int main()
{
mystring s = "Nitin";
return 0;
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 6 '07 #6
On Feb 6, 3:34 pm, "Alf P. Steinbach" <a...@start.now rote:
* dragoncoder:
On Feb 6, 11:53 am, "Alf P. Steinbach" <a...@start.now rote:
* dragoncoder:
>Changing the parameter of the copy constructor to "const mystring&"
solves the problem. Can someone please explain how it makes a
difference ?
A temporary (the actual argument) can't be bound to a reference to
non-const.
I am sorry I still don't get it. Where is the copy constructor
involved here? I am trying to call the constructor with the "const
char*" argument. Please explain.

Except for possible optimization, which doesn't affect the requirements
on the string class, the statement

mystring s = "Nitin";

is equivalent to

mystring temp( "Nitin" );
mystring s( temp );

for some unique name 'temp'.

Repeat: even though just about any compiler optimizes away the
temporary, i.e. you don't get an actual copy constructor call, the copy
constructor must be available to do the job as if no optimization.

...

OK, lets go through the rest of the code, also.
=cat mystring.h
#include<iostre am>

Not necessary since iostreams aren't used in the header.
using namespace std;

Never have 'using namespace std;' in a header.
class mystring
{
char* p;
int capacity;
int len;
enum {DEF_SIZE = 100};

Reserve all uppercase identifiers for macros.
public:
// Constructors
mystring();
mystring(int size);

Naming: here you probably mean capacity, not size.
mystring(const char* str);
// Iniializer
void init(int size = DEF_SIZE);

Should not be public.
//Destructor
~mystring();
//Copy Constructor
mystring(mystri ng&);

Needs 'const' for the argument.
//Assignment Operator
mystring& operator = (mystring&);

Needs 'const' for the argument.
//Display String
void display();

OK as a debugging aid while developing the class, but after that, will
bind use of the class to some particular i/o environment, so ungood.
};
=cat mystring.cpp
#include<iostre am>
using namespace std;
#include "mystring.h "

It's a good idea to include the module header as the very first thing in
the implementation file (not after anything else, except comments), to
make more sure that it includes everything necessary.


//Constructors
mystring::mystr ing()
{
cout << "Default Constructor" << endl;
init();
len = 0;
}
mystring::mystr ing(int size)
{
cout << "Constructo r having size" << endl;
init(size);
len = 0;
}
mystring::mystr ing(const char* str)
{
cout << "Constructo r with string argument" << endl;
int length = strlen(str);
init(length + 1);
len = length + 1;

Although 'len' doesn't seem to be used for anything, if it's meant to
represent the length of the string then surely it should be 'length',
not 'length+1'.
strcpy(p, str);
}
void mystring::init( int size)
{
p = new char[size];
capacity = size;
}
mystring::~myst ring()
{
cout << "Destructor " << endl;
delete p;
p = NULL;

Assignment of NULL unnecessary - the destructor call is the last thing
that ever happens with this object.
}
mystring::mystr ing(mystring& other)
{
cout << "Copy Constructor" << endl;
delete p;

p has not been initialized, so this is Undefined Behavior.
p = new char[strlen(other.p) + 1];
strcpy(p,other. p);

Fields of 'other' not copied.
}
mystring& mystring::opera tor=(mystring& other)
{
cout << "Assignment Operator" << endl;
if(this == &other)
return *this;
delete p;
p = new char[strlen(other.p) +1];

At this point you may get an exception. OK, it's not a practical
consideration, because when you run out of memory there's not much to do
except terminate. But as a general principle, strive to create
exception safe code -- here you'd leave the object with an invalid 'p'
member.

The 'swap' idiom for assignment helps with exception safe assignment.


strcpy(p,other. p);
return *this;
}
void mystring::displ ay()
{
cout << *p << endl;
cout << "Length of string is " << len << endl;
cout << "Capacity of the string is " << capacity << endl;
}
=cat str.cpp
#include<iostre am>
using namespace std;
#include "mystring.h "
int main()
{
mystring s = "Nitin";
return 0;
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
one more thing
use delete [] p instead of delete p

Feb 6 '07 #7
mike wrote:
the form for a copy constructor uses the const key word.
Not necessarily. Any function that can take a reference
to a single argument of the type of the class is a copy constructor
regardless of the cv-qualification.

When you use
the = operator, it calls the copy constructor.
The = operator in his case does not use the copy constructor.

The = in the first line of his main function is NOT an operator.
It's the syntax for initialization.
Feb 8 '07 #8

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

Similar topics

2
991
by: Martin Jensen | last post by:
Hi I have a problem with Qt. My class definition is this: class Button : public QObject, public Tk_Object { Q_OBJECT public: Button() {} Button(Tk_Object &p); ~Button();
4
1400
by: Gama Franco | last post by:
Hi, I've been developing this API, but now I get stuck in a compiling error and I'm out of ideas. Some comments are welcome. The hierarchy is bases in three classes, and I will explain it bellow in detail. The three classes are: 1 - IFolderManager -> abstract base class
2
1505
by: max_sang | last post by:
Hello I have a nasty problem... take a look at this code: struct Parser { Parser(const string& s) { ... tokenizes s into pieces... } template <class T> to(size_t idx); private: vector<string> tokens_; // holds the pieces of s };
4
2067
by: Greg | last post by:
Is it possible to call a constructor from within a constructor I mean Class A { public A(string getModifiedVal) { .........
7
1522
by: Sergey Poberezovskiy | last post by:
Hi, I created two base forms: frmList and frmDetail, compiled them into a dll, and then want to use in my new project. The problem: When I created new inherited form, say frmClients, I cannot load the form in design view - the IDE complains with "Argument 'Path' is Nothing or empty." error. It does not stop however the project to compile, and even
30
4601
by: dbuchanan | last post by:
ComboBox databindng Problem == How the ComboBox is setup and used: My comboBox is populated by a lookup table. The ValueMember is the lookup table's Id and the DisplayMember is the text from a corresponding field in the lookup table. In my data table we store the ID in what I will call the 'key' field. == Description of the desired operation:
9
3269
by: esakal | last post by:
Hello, I'm programming an application based on CAB infrastructure in the client side (c# .net 2005) Since my application must be sequencally, i wrote all the code in the UI thread. my problem occurs when i try to show a progress bar. The screen freezes. I know i'm not the first one to ask about it. but i'm looking
9
3593
by: David | last post by:
Hi all, I posted my question two days ago, and tried to solve this problem. but until now I didn't solve that. and I cut my codes so maybe this time it is more readable. ///////////////////////////////////////////////////// #ifndef MYCLASS_H_ #define MYCLASS_H_
1
1582
by: aboalnodom | last post by:
hello guys, i hope any one will help in this i am designing a web application, the page i am workin on its the default.aspx it contains dropdownboxes the first 4 to choose the type and the second for to choose the value of the type when you choose a type a dropdownlist will be filled of values that related of that type. and when you choose a second type , it will also will filled the value that related of the second type, and it will...
0
9554
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
10136
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
9988
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
9923
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,...
0
8813
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...
0
6640
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();...
1
3911
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
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.