Can someone explain this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<iostream>

using namespace std;

class String
{
	public:
		int num;
		String();
		String(int);
		String(const String& str);
		~String();
		String& operator = (const String& str);
		private:
			char* arr;
			int len;
			
};

String::String()
{
	arr=0;
	len=0;
	num=0;
}

String::String(const String& str)
{
	len= str.len;
	arr = new char[len+1];
	for (int i = 0; i < len; i++)
	{
		arr[i]=str.arr[i];
	}
	arr[len]='\0';
}

String::String(int a)
{
	num=a;
}

String::~String()
{
	if (arr)
	{
		delete[] arr;
		arr=0;
	}
}

String& String::operator = (const String& str)
{
	if (this != &str)
	{
		if (arr)
		{
			delete[] arr;
			arr = 0;
		}
		len = str.len;
		arr = new char[len+1];
		for (int i = 0;i<len;i++)
		{
			arr[i] = str.arr[i];
		}
		arr[len] = '\0';
	}
	return *this;
}

int main()
{
String str;
String bf(12);
str=bf;
cout<<str.num<<endl;

}

int main()
{
???
}


can someone explain this code to me and tell me what should be written in the main body
This code is using Object Oriented Paradigm of C++ language and above code has a class named 'String' and all other functions are class member functions with some special cases of functions.
Above code creates a new user-defined data type just like pre defined data types 'int, double, float etc. . .' and overloads the assignment operation for the data type 'String' or you should say class.

If you do not know what is OOP, then you should first start OOP learning on this website.

http://www.cplusplus.com/doc/tutorial/classes/

start from the link and begin learning. Farther you'll go, more you'll understand.
Last edited on
One more thing, a program cannot have more than one main it. The below main function is invalid and you should remove that main function
what should be written in the main body

That code has main() defined twice, at lines 72 and 81,which is not valid. Get rid of the second block, lines 81 to 84.
The class has bugs. The constructor at line 38 doesn't initialize arr or len. The constructor at line 27 and the assignment operator at line 52 don't initialize a. These bugs mean that the main() that you've defined won't do what you expect:
1
2
3
4
5
6
7
int main()
{
String str;       // str.num = 0
String bf(12);  // bf.arr and bf.len uninitialized.
str=bf;            // str gets the uninitialized bf.arr and bf.len, and doesn't get bf.num
cout<<str.num<<endl;  // prints 0 because str.num is still 0 changed.
}


what should be written in the main body

The main() function is the one that runs when you execute the program. You haven't said what the program should do so I don't know what should be written there.
Topic archived. No new replies allowed.