forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic_Constructor.cpp
More file actions
99 lines (90 loc) · 1.81 KB
/
Dynamic_Constructor.cpp
File metadata and controls
99 lines (90 loc) · 1.81 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<iostream>
#include<string.h>
using namespace std;
//Dyanamic Constructor
class String
{
//here no access specifier is mentioned,By default it will be private.
char *name;
//Here we want to store string within name;
int length; //To maintain string length
public:
/*
Default constructor*/
String()
{
//When we are trying to create an object without passing parameters
length=0;
name=new char[length+1];
//name=new char[1];
/*
name=""; \0
*/
}
String(char *s)
{
//Parameterized constructor
/*char name[100] for C language
*/
length=strlen(s);
//we are calculating the length of the string or parameter
name=new char[length+1]; //+1 for NULL chatacter "\0
strcpy(name,s);
}
void display()
{
cout<<name<<"\n";
}
void join(String &a,String &b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name, a.name); //strcpy is used to copy string
strcat(name, b.name);
// strcpy(a,b) b will be copied to a
// strcat(a,b) it is used to concatenate 2 strings result a=a+b
}
};
/*
Ritam\0 -->6
Poulami\0 -->8
RitamPoulami\0 -->13
*/
int main()
{
char *first="Ritam"; //we are declaring a string
String name1(first);
/*
here we are passing Ritam as parameter
for the object name1.ti will evoke
the parameterized constructor.
String(char*s)
{
....
}
*/
String name2("Poulami");
String name3("Paramita");
String s1,s2;
/*
It will call default constructor.
s1.length=0
s1.name="";
s2.length=0
s2.name="";
*/
s1.join(name1,name2);
/*
Approach--->
strcat(name1,name2);
Means, name1=name1+name2+\0
*/
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
return 0;
}