Saturday 24 October 2015

Class

# include<iostream>
using namespace std;
class cal
{
//Data Members
int a,b,add,sub,mil,divide;
public:
cal()//Constructor
{
a=b=add=sub=mil=divide=0;
}
//Functions
void addition()
{

 add=a+b;
cout<<"The total is"<<add<<endl;

}
void subtraction()
{

if(a>b)
{
sub==a-b;
}
else
{
sub=b-a;
}
cout<<"Subtraction result  is" <<sub<<endl;

}
void multiplication ()
{

mil=a*b;
cout<<"Multiply is "<<mil<<endl;

}
void division()
{

if(a>b)
divide=a/b;
else
divide=b/a;

cout<<"The Divisior is  "<<divide<<endl;
}
};
void main()
{
cal c;
cout<<"Enter First number"<<endl;
cin>>c.a;
cout<<"Enter Second Number"<<endl;
cin>>c.b;

c.addition();
c.subtraction();
c.multiplication ();
c.division();

}
In this program we will discuss what is class and why we need it??

Class:

class in C++ is a user defined type or data structure declared with keyword class that has data and functions (also called methods) as its members whose access is governed by the three access specifiers privateprotected or public (by default access to members of a class is private). A class (declared with keyword class) in C++ differs from a structure (declared with keyword struct) as by default, members are private in a class while they are public in a structure. The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class. Instances of these data types are known as objects and can contain member variablesconstantsmember functions, and overloaded operators defined by the programmer.

Syntax:

class
{
//Generally,Data Members are kept private ,so that they can only be access inside of class
Data Members;
//Generally functions are kept public so that they can be used outside of the class.
Functions

};

In this program,we are making a simple calculator.There is one class named cal having some data members and some functions(Which are accessed outside of class using object) ....

Constructor:
Constructor is a function which is automatically called by object,when object is initialized ,In constructor we can initialized variables and other related things if require,If the Constructor is not defined,C++ can make constructor itself but body is empty.It is normally used to initialized  variables.



Note that,Here data members are not declared private but they cant accessed outside of class because until we can define any access identifier ,any variable or function will be by-default private,

Any Suggestions or help ,plz comment.
Thanks


0 comments: