C++ | Using Static variables in class

Note:- If you are looking for simple program of bill(not using class), please see this.

C++  | Creating a bill

else continue here……

Introduction

This tutorial is to use static variables in class. The program is given below that creates the bill using class with a static variable. The program is extendable.  Go enjoy the program. Lets begin………

Program to create a bill using class with static variable.

#include<iostream.h>
#include<conio.h>
//declare class
class bill
{
int ino,qty,rate,amt;
static int totamt;
public:
void getdata(void)
{
cout<<“Enter the item no.:”;
cin>>ino;
cout<<“Enter the qty:”;
cin>>qty;
cout<<“Enter the rate:”;
cin>>rate;
}
void calamt(void)
{
amt=qty*rate;
}
void print(void)
{
cout<<ino<<“\t”<<qty<<“\t”<<rate<<“\t”<<amt<<endl;
totamt=totamt=amt;
}
static void totprint(void)
{
cout<<“Total = “<<totamt<<endl;
}
};
//static int totamt
int bill::totamt;
void main()
{
//clear the screen.
clrscr();
//declare x as bill
bill x[3];
int i;
//Input loop.
for(i=0;i<3;i++)
{
x[i].getdata();
x[i].calamt();
}
//Title
cout<<“I.no \t Qty \t Rate \t Amt”<<endl;
//Output loop.
for(i=0;i<3;i++)
x[i].print();
//A line
cout<<“—————–“<<endl;
bill::totprint();
//get character
getch();
}

Output

Enter the item no.:1
Enter the qty:2
Enter the rate:3
Enter the item no.:2
Enter the qty:3
Enter the rate:4
Enter the item no.:3
Enter the qty:1
Enter the rate:5
I.no.    Qty   Rate    Amt
1          2       3        6
2          3       4        12
3          1       5        5
———————-
Total = 23

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 class.
  3. Declare the static variable.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Declare the x as your class name in arrays.
  7. Add input loop and call two functions.
  8. Add output loop and call print function.
  9. At last call the static function.

At the end

You learnt creating the C++ program for Using Static variables in class in c++. So now enjoy the program.

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s