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.