Unit II
Unit II
Unit II
UNIT-II:
*private
*public
• The object can not be access the private variables and function
directly.
• It can be accessed only by the public member function.
Syntax:
class class-name
{
Private:
Declaration of variables;
Declaration of functions;
Public:
declaration of variables;
declaration of functions;
};
Example:
#include<iostream.h>
#include<conio.h>
Class add
{
Private;
int x,y,z;
Public:
Void sum()
{
Cin>>x>>y;
z=x+y;
}
void display()
{
cout<<z;
}
};
void main()
{
add a1;
a1.sum();
a1.display();
getch();
}
Declaring object:
• The declaration of object is same as declaration of variables.
• Object are created when the memory is allocated.
Accessing class members:
• The object can be accessed the public member variable and function
using the operator.
Syntax:
Object name[operator] member name;
Example:
a1.add();
a1.add();
Public keyword
• The member variable and function can be accessed when it is declared as public.
Example:
#include<iostream.h>
#include<conio.h>
Class add
{
Public:
int x,y,z;
void sum()
{
z=x+y;
}
void display()
{
cout<<z;
} };
void main()
{
add a1.;
a1.x=10;
a1.y=20;
a1.sum();
a1.display();
getch();
}
};
Void add::sum()
{
cin>>x>>y;
z=x+y;
}
void add::display()
{
count<<z;
}
void main()
{
add a1.;
a1.sum();
a1.display();
getch();
}
Member function inside the class
#include<iostream.h>
#include<conio.h>
Class employee
{
Private:
int eno,ename,des,sal,bpay,hra,ma,pf;
Public:
Void get _employee()
{
Cout<<“Enter the employee no”;
Cin>>eno;
Cout<<“Enter the employee name”;
Cin>>ename;
Cout<<“Enter the designation”;
Cin>>des;
Cout<<“Enter the Salary”;
Cin>>salary;
Cout<<“Enter the basic pay”;
Cin>>bpay;
}
Void total_salary()
{
Salary=hra+bp+ma-pf
}
Void print_details()
{
Cout<<“The employee no is:”;
Cout<<eno;
Cout<<“The employee name is:”;
Cout<<ename;
Cout<<“Designation is:”;
Cout<<des;
Cout<<“Salary :”;
Cout<<salary;
Cout<<“Basic pay is:”;
Cout<<bpay;
}
};
Void main()
{
Employee E1;
E1.get_employee();
E1.total_salary();
E1.print_details();
getch();
}
Static member Variables & Functions
int main()
number::count();
number::display();
number::count();
number::display();
}
Static Private member Function
• The static public member variable can be initialized outside the class
and also can be initialized in the main function.
• It can be initialized like a normal variable.
Example:
#include<iostream.h>
#include<conio.h>
int c=11;
Class bita
{
Public:
Static int c;
};
int bita::c=22;
void main()
{
clrscr();
int c=33;
cout<<“\n class member c=“<<bita::c;
cout<<“\n global variable c=“<<::c;
cout<<“\n local variable c=“<<c;
}
Output:c=22
c=11
c=33
Static Object
3. Pass by address
A.a1;
B.b1;
a1.getA();
b1.getB();
a1.show(b1);
}
Overloading member function
DESTRUCTOR
• All constructors are defined with the same name as the class.
sum s1=sum(3,4);
s1.display();
sum s2=sum(5.5,10.5);
s2.display();
}
Copy Constructor
• The constructor can accept argument of any data type including
user-defined data type.