C++ | Introduction to constructors

Introduction

This is a tutorial on how to use constructors in c++. The program is given below for constructors. The program is extendable. Go enjoy the program. Lets begin………………….

Program for constructors in c++


#include<iostream.h>
#include<conio.h>
//declare class
class sum
{
int a,b,add;
public:
sum (int x,int y)
{
a=x;
b=y;
}
void addno(void)
{
add = a+ b;
cout<<"Sum ="<<add;
}
};
//void main
void main()
{
//clear the screen.
clrscr();
//declare variable type int
float a,b;
//Input the two numbers
cout<<"Enter two nos."<<endl;
cin>>a>>b;
//initialize constructor
sum x(a,b);
//Call functions
x.addno();
//get character
getch();
}

Output

Enter two nos.
1
4
Sum =5

How it works

  1. You enter two nos.
  2. Sum is calculated and printed.

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of c++ which can be used in any program….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Declare two classes.
  3. Declare constructor.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Declare x as constructor and pass parameters to it if there.
  7. Call the functions.

At the end

You learnt creating the C++ program for constructors in c++. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: