Constructor and Destructor in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Constructor and Destructor in C++

Share This

A constructor is used to allocate the memory for the newly created object. A constructor has the same name with the class.

If a class does not have any constructor, the default constructor is provided.

In the following code we have shown how to create objects of a class.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
class Test {
int x, y;
};
int main() {
Test t1;
Test t2();
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Parameterized Constructor
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
#include <iostream>
using namespace std;
class Test {
int x, y;
public:
Test(int x, int y) {
this -> x = x;
this -> y = y;
}
void print() {
cout << x << " " << y << endl;
}
};
int main() {
Test t1(5, 7);
t1.print();
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Constructor Overloading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
class Test {
int x, y;
public:
Test(int x) {
this -> x = x;
this -> y = 0;
}
Test(int x, int y) {
this -> x = x;
this -> y = y;
}
void print() {
cout << x << " " << y << endl;
}
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX




Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.