Notice the difference in both the codes in line "len = strlen(s);" in code 1: it is written before "strcpy(str,s)" and in code 2 its written after. What difference is it making? I ran my code in Dev C++ and i am getting different output. shouldnt the output be same in both cases?
Code 1:
#include <iostream>
#include <string.h>
using namespace std;
class String{
private:
char str[];
int len;
public:
String()
{
cout << "Default Constructor" << endl;
len = 0;
strcpy(str,"");
}
String(char s[])
{
cout << "parameterised constructor" << endl;
len = strlen(s);
strcpy(str,s);
}
void print()
{
cout << str << " len = " << this->len << " strlen = " << strlen(str) << endl;
}
};
int main()
{
String str2("Hello World");
str2.print();
return 0;
}
Output 1 :
parameterised constructor
Hello World len = 1819043144 strlen = 11
Code 2:
#include <iostream>
#include <string.h>
using namespace std;
class String{
private:
char str[];
int len;
public:
String()
{
cout << "Default Constructor" << endl;
len = 0;
strcpy(str,"");
}
String(char s[])
{
cout << "parameterised constructor" << endl;
strcpy(str,s);
len = strlen(s);
}
void print()
{
cout << str << " len = " << this->len << " strlen = " << strlen(str) << endl;
}
};
int main()
{
String str2("Hello World");
str2.print();
return 0;
}
Output 2 :
parameterised constructor
len = 11 strlen = 1