“Constructors & destructors” in C++ with class examples

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()”.

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;
}

>> Go to Next page for Constructors & destructors program >>