C++ constructors & destructors: It is a basic concept in C++ programming language. This C++ class example codes are all about “How to use C++ class constructor and destructor?”
If a function has the name as classes’ name, then it is said to be a constructor. It is used to initialize the values. For example, in this program a class name is “ConDes”. There will be an exact method in the same name called “ConDes(int pi)”. So that this particular method is called as basic constructor with an argument.
If a tilde symbol is available in front of the constructor means it is said to be a destructor in terms of programming language. It will destroy the previously created constructors and its values. For example, constructor name is “ConDes()” means the destructor will be “~ConDes()”.
- [SEE: C Program Tutorials] & [IT Companies Details]
Here you can find 3 simple and effective programs that describes about Constructors and destructors. 3 programs models are,
- With single parameter,
- With 2 arguments,
- Constructor & destructor program,
C++ Constructor with single parameter:
This program code is all about CPP constructor with a single parameter feature. Example code is given below.
#include<iostream.h> #include<conio.h> //Class definition class Ex { int i; public: Ex(int Janu) // Constructor { i= Janu; } int inpi() // Function definition { return i; } }; int main() { clrscr(); Ex O1=99; // passes 99 to Janu cout<<O1.inpi(); getch(); return 0; }
Related: Operator Overloading: C++ program for SET operations
C++ Constructor with 2 parameters:
#include<iostream.h> #include<conio.h> // Class definition class ConDes { int x, y; public: ConDes(int k, int a) //Constructor with parameters { x=k; y=a; } void Display() // Method definition { cout<<x<<" "<<y; } }; int main() { clrscr(); ConDes O1(2,7); O1.Display(); getch(); return 0; }
Constructors & destructors in C++:
#include <iostream.h> #include <conio.h> // Class definition class ConDes { public: // Access specifier int W1; ConDes(int Pi); // Constructor ~ConDes(); // Destructor } GObj1(1),Gobj2(2); ConDes::ConDes(int Pi) { cout<<"\n Beginning:"<<Pi<<"\n"; W1=Pi; } ConDes::~ConDes() { cout<<"Destructing:"<<W1; cout<<"\n"; } int main() { clrscr(); ConDes LocObj1(3); cout<<"Karthikh Venkat - Students3k.com \n"; ConDes LocObj2(4); getch(); return 0; }
Output of this Program:
Beginning: 1
Beginning: 2
Beginning: 3
Karthikh Venkat - Students3k.com
Beginning: 4
Destructing: 4
Destructing: 3
Destructing: 2
Destructing: 1
Note: Based on the computer system’s environment and compiler models the result will be varied.