Constructor and Destructor in C++ - BunksAllowed

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

Community

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.


#include <iostream> using namespace std; class Test { int x, y; }; int main() { Test t1; Test t2(); return 0; }
Parameterized Constructor
#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; }
Constructor Overloading
#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; } };




Happy Exploring!

No comments:

Post a Comment

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