2 Classes and Objects


 




Features Of OOPs:
  • Data Abstraction: data abstraction helps represents information in terms of its interface with the user.
  • Data Encapsulation: means that the physical representation of data is surrounded.  User of data need not see the implementation, but deal with the data only in terms of its logical picture (abstraction).
  •  Information Hiding: the keywords private and public in class determine the accessibility of class member.   Variables and functions from public section can be accessed by any function of the program but a program can access the private members of a class only by using the public member function of the class this insulation of data members from direct access in a program is called information hdiding. For e.g.
private:
 char name [120];
 int age, runs, higest, tests;
 float average, calc avg (void)
public:
      void get stats(void);
void average(void);
};
keyword class is used to define class template.  Player is the class tag (name).  Variables in private section ‘ name, age, runs, highest, tests, and avg can be accessed only by the member functions of the class.  calcavg( ), getstats( ), and showstats( ) can be called from program directly but calcavg( ) can be called only from member functions of the class getstats( ) and showstats( ).

Classes and Objects:  
In C++ once a class has been defined several objects of that type can be declared.  An object of a particular class be declared just like a structure variable is declared using tag.  E.g.
            Player rangi, tiger;
Where rangi and tiger are two objects of the class player.  The keyword class is optional and can be omitted.  Both objects have their own set of member variables.  Once an object is declared, its public members can be accessed using dot(.) operator with the object name e.g.
rangi.getstats( );
tiger.showstats( );

public and private members:  
Class members can either be declared in public or in private sections of the class.  data members of a class are normally declared in the private section.  Member functions having interface between object and program are declared in public section.  The  Member  functions which may have been broken down further or those which do not have interface are declared in private section.  By default all members of class are private.

Member functions of class:  
Is declared in class template must be define its return value and the list of arguments.  Definition of member function differs from ordinary function.  The header of a member function uses scope resolution operator(::)to specify the class to which it belongs.  E.g
                        void player :: getstats(void)
{
……. Arguments,
……
}
here the function getstats( ) belongs to the class player.

Example 1
Class player{
private:
            char Name [120];
int age;
int runs;
int highest;
int tests;
float average;
float calcavg(void);
};
float player:: calavg(void)
{
return(runs/tests);
}
void player:: showstats(void)
{
printf(“\n Name is:%s”,name);
printf(“\n Runs are:%d”,runs);
………….
……..
}
void player::getstats(void)
{
printf(“\n  Enter Name ”);
scanf(“\n %s”,name);
printf(“\n Enter Runs are:”);
scanf(“\n %d”,runs);
……
……
average= calcavg( );
}
int main(void)
{
player sachin. Steve;

sachin.getstats( );
steve.getstats( );
sachin.showstats( );
steve.showstats( );
}

Member functions in the class specifier:  
can be defined as:
class String
{
private:
char str[100];
public:
void putstr(void)
{
printf(“%s”,str);
}

Constructors and destructors:
A class contains private and public section containing member data items or member functions.  Class members from public section can be accessed directly from anywhere in the program while class members from private section can be accessed only from other members of the same class.

Constructors:  
A constructor is a member function that is executed whenever an object is created.  The constructor function has to have the same name as that of the class.  This is to how the compiler knows that it is the constructor function and to make calls to it whenever an object is created.

The constructor is defined just like any other function.  Name of the class is written with the scope operator and name of function.  Function header does not have a return type.  The actual function body and the rest of program are the same.

Using a Constructor:  
The function is called at the time of declaration of an object.  There are three ways of creating and initializing an object.  The first way is to call the constructor explicitly.
E.g.
Box  BigBos   =          Boxclass(1,1, 25, 79);

This statement creates an object with the name bigbox and initialize data members with the parameters passed to constructor function.  Second way is to call constructor implicitly.
E.g.
            Boxclass BigBox (1, 1, 25, 79);
And last way is the direct assignment of data items to the object name.  This approach works only if there is one data members in the class.


E.g.
class counter                                       
{
private:
            int count;
public:
            counter(int c)
{
count =c;
};
            };
counter ctr = 0;

Here object ctr is initialize by zero value at declaration time which is actual assigned value to its data member count.

Once constructor for a class has been declared and defined the program must use it.  Or objects can be not be declared without initializing them.  Sometimes data member of an object may not require initialization.  May be they have to be accepted from the user later.  The key to defining an uninitialized object is to have a constructor with default arguments.  E.g.
class counter
{
private:
            int count;
public:
            counter (int c = 0 )
{
count = c;
};
                        };
destructors:
When an object gets out of existence or when its scope is over a destructor a special member function of class can be defined to be called automatically.  Destructor has the same name of the class preceded with a (~) tiled symbol.  It has no return type and no arguments.  The compiler generates a call to a destructor when an object expires.  It used to clear up the mess from an object.  It becomes necessary when class constructor use new operator, otherwise destructor can be given as an empty function.  E.g.
            BoxClass:: ~Boxclass(void)
{         }
           
Example 2
#include<string.h>
#include<stdio.h>
class string{
private:
            char *cptr;
            int size;

public:
            string (char *s);                       // constructor
            ~string (void);                         //destructor
            void putstr(void);
   };
void main (void)
{
string   s1(“Hello World……\n”);
string   s2= “Welcome to My Home\n”;
string   s3=string (“If you like Welcome Again!!!\n”);
s1.putstr;
s2.putstr( );
s3.putstr( );
}
string::string(char *s)                          //constructor called
{
size = strlen(s);
cptr = new char[size+1];
strcpy (cptr, s);
}
string::~string(void)                            //destructor called
{
delete cptr
}
void string::putstr(void)
{
printf(“%s”,cptr);
}
Object can be passed to a function and returned back like a normal variables.  When an object is passed by content, compiler creates another object as formal variable, in called function and copies all data members from actual variable to it.

Pointers to Objects:  
Declaring a pointer to an object of a particular class is same as declaring a pointer to variable of any other data type.  A pointer variable containing the address of an object is said to be pointing to that object.  Pointers to objects can be used to make a call by address or for dynamic memory allocation.  A pointer to an object uses the arrow operator to access its members.  A pointer to an object has only one word of memory.  It has to be made to point to an already existing object or allocated memory using new. 

Example 3
String str;                    // object
String *sp;                   // pointer to an object
Sp = &str;                    // assign address of an existing object
Sp =new string;           // allocate memory with (new).

Example:
#include<stdio.h>

class person{
private:
            char name[60];
public:
            void getname(void);
void putname(void);
                };
            void main(void)
{
person Jazz;
Jazz.getname( );
Jazz.putname( );
Person *boss;              // pointer to object
boss = new person;      // allocate memory
bossàgetname( );
bossàputname( );
}
void person::getname(void)
{
printf(“\n Enter Name”);
gets(name);
}
void person::putname(void)
{
printf(“Name is %s\n”, name);
}

The this pointer:  
The keyword this gives the address of the object which was used to invoke the member function.  Whenever a member function is called, the compiler assigns the address of the object, which invoked the function, to the this pointer, this pointer can be used just like other object pointer, arrow operator  can be used with this to access the members of that object.  E.g.
class what{
private:
            int Jumbo;
public:
            void print(void);
};
void what::print(void)
{
printf(“%d”,Jumbo);
printf(“%d\n”, thisàJumbo);
}
this pointer is generally used to return the object which invoked the member function.


Arrayes of Obects:
Several objects can be declared of a particular class.  also an array of objects can be declared and used just like an array of any other data type.       

Example 4
#include<stdio.h>
#include<string.h>
class student{
private:
            int roll_num;
            char name[26];
int marks[6];
float percent;
            public:
                        int getdetails(void);
                        void printdetails(void);
};
int main (void){
students records[50];
int x =0;
clrscr( );
while (Records [x++].getdetails( ));
clrscr( );
printf(“\n Roll Number\t Name\t\t\t Percent\n”);
for(int y=0; y<x=1; ++y){
records[y].printdetails( );
}
int student::getdatails(void){
int ctr, total=0;
printf(“\n Roll no (0 to quit)”);
scanf*”%d”, &roll_num);
if(roll_num==0);
return(0);
scanf(“%s”,name);
printf(“Marks”);
for(ctr =0; ctr<=5; ++ctr){
printf(“Subject No %d”, ctr+1);
scanf(“%d”,&marks[ctr]);
total +=marks[ctr];
}
percent = total/6;
return(1);
}
void student::printdetails(void)
{
printf(“\n %-5d\t\t%-25s\t\t%5.2f”,roll_num,name,percent);
}

 

Practical Session 2

Example 1(Bank Transaction)
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
class model {
private:
int ac_no,amt;
char name[15],ac_type;
int balance,cur_bal;
int calc(int,int);
char query( );
public:
void getdata(void);
void dispdata(void);
};
void model::getdata(void){
printf("\n Enter acc number :");
scanf("%d",&ac_no);
printf("\n Enter the Name :");
scanf("%s",&name);
printf("\n Enter initial Balance :");
scanf("%d",&balance);
printf("\n Enter amount :");
scanf("%d",&amt);
fflush(stdin);
ac_type=query( );
cur_bal =calc(balance,amt);
}
char model::query( ){
char tran;
printf("\n Enter trans type ");
scanf("%c",&tran);
return tran;
}
int model::calc(int,int){
int a;
if(ac_type=='W')
a= balance-amt;
else if(ac_type=='D')
a=balance+amt;
return a;
}
void model::dispdata(void){
printf("\n Your account number %d :",ac_no);
printf("\n Your Account type %c :",ac_type);
printf("\n Your Current balance %d:",cur_bal);
}
 void main(void){
clrscr( );
model ac1;
ac1.getdata( );
ac1.dispdata( );
getch( );
}
Example 2(Salesman’s Commission Calculation)
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
class sales{
private:
int salcd;
char salname[15];
int rate,qty,sal_value;
int salary,comm;
int calc(int sal_value);
public:
void getdata(void);
void dispdata(void);
};
void sales::getdata(void){
printf("\n Enter Salesman Code ");
scanf("%d",&salcd);
printf("\n Enter Salesman Name ");
scanf("%s",&salname);
printf("\n Enter Product Rate ");
scanf("%d",&rate);
printf("\n Enter Qunatity ");
scanf("%d",&qty);
fflush(stdin);
sal_value =qty*rate;
salary = calc(sal_value);
}
int sales::calc(int sal_value){
if(sal_value>5000 && sal_value<10000)
comm = 0.05*sal_value;
if(sal_value>10000 && sal_value<15000)
comm = 0.06 * sal_value;
salary = 2500 + comm;
return salary;
}
void sales::dispdata(void){
printf("\n Salesman's Code  :%d",salcd);
printf("\n Salesman's Name  :%s",salname);
printf("\n Quantity of Product  :%d",qty);
printf("\n Salesman's Salary  :%d",salary);
printf("\n Salesman's Commission  :%d",comm);
 }
void main(void){
clrscr( );
sales sal;
sal.getdata( );
sal.dispdata( );
getch( );
}
Example 3(Printing Student Report)
#include<iostream.h>
#include<conio.h>
const int MMarks =600;
class student {
private:
char name[11];
int marks;
public:
void read( );
void show( );
};
void student::read( ){
cout<<"\n\n Enter Name : ";
cin>>name;
cout<<"\n Enter Marks: ";
cin>>marks;
}
void student::show( ){
cout<<"\t";
cout<<name;
cout<<"\t\t";
cout<<marks;
cout<<"\t\t";
cout<<int(float(marks)/MMarks *100);
}
void main( ){
clrscr( );
int i,c;
student *s;
cout<<"\n How many Students  : ";
cin>>c;
s= new student[c];
for(i=0;i<c;i++){
cout<<"\n Enter Student "<<i+1<<" Details";
s[i].read( );
}
cout<<"\n \t\t\t\tStudent Report";
cout<<"\n \t\t-------------------------------------";
cout.width(3);
cout<<"\nR#";

cout<<"\tStudent";
cout<<"\t\tMarks";
cout<<"\t\tPercent"<<endl;
for(i=0;i<c;i++){
cout.width(3);
cout<<i+1;
s[i].show( );
cout<<endl;
}
getch( );
}
Example 4(Calling an Object by Setting initial values)
#include<iostream.h>
#include<conio.h>
class myclass{
static int count;
int number;
public:
            void set(int num){
            number=num;
            ++count;
            }
            void show( ){
            cout<<"\n Number of calls made to set by any object:  "<<count;
            }
            };
            int myclass::count=0;
void main( ){
clrscr( );
myclass obj1;
obj1.show( );
obj1.set(100);
obj1.show( );
myclass obj2,obj3;
obj2.set(200);
obj2.show( );
obj3.set(500);
obj3.show( );
getch( );
}

Example 5(Constructor and Destructor)
#include<iostream.h>
#include<conio.h>
class nano{
public:
nano( );
~nano( );
};
 nano::nano( ){
cout<<"\n Called Constructor Nano  ";
}
nano::~nano( ){
cout<<"\n Called Destructor Nano   ";
};
class mano{
public:
mano( );
~mano( );
};
mano::mano( ){
cout<<"\n Called Constructor Mano  ";
}
mano::~mano( ){
cout<<"\n Called Destructor Mano   ";
}
void main( ){
clrscr( );
mano b,b1;
nano a;
cout<<"\n Terminating Program ";
getch( );
}
Example 6
#include<iostream.h>
#include<string.h>
#include<conio.h>
class date{
private:
            int day;
            int month;
            int year;
public:
            void set(int dayn,int monthn,int yearn){
            day =dayn;
            month=monthn;
            year=yearn;
            }
            void show( )
            {
            cout<<day<<"-"<<month<<"-"<<year;
            }
};
void main( ){
clrscr( );
date d1,d2,d3;
d1.set(26,3,1999);
d2.set(23,4,2000);

d3.set(7,4,2002);
cout<<"\n Date of birth of first Son : ";
d1.show( );
cout<<"\n Date of birth of second Son : ";
d2.show( );
cout<<"\n Date of birth of third Son : ";
d3.show( );
getch( );
}
Example 7(Program to Convert Distance)
#include<iostream.h>
#include<conio.h>
class distance{
private:
            float feet;
            float inches;
public:
            void init(float ft,float in){
                        feet =ft;
                        inches=in;
            }
            void read( ){
            cout<<"\n Enter Feet    : ";
            cin>>feet;
            cout<<"\n Enter Inches  : ";
            cin>>inches;
            }
            void show( )    {
            cout<<"\n\n Feet "<<inches<<"\'";
            }
            void add(distance d,distance d1)
            {
            feet   = d.feet   + d1.feet;
            inches = d.inches + d1.inches;
            if(inches>12.00)
            {
            feet  = feet+1.0;
            inches= inches-12.00;
            }
    }
};
void main( ){
clrscr( );
distance d,d1,d2;
d1.init(11.00,6.25);
d.read( );
cout<<"\n Distance d is : ";
d.show( );
cout<<"\n Distance d1 is : ";

d1.show( );
d2.add(d,d1);
cout<<"\tn Distance d + d1 is : ";
d2.show( );
getch( );
}
Example 8(Simple Class Program)
#include<iostream.h>
#include<string.h>
#include<conio.h>
class student{
private:
int rollno;
char name[20];
public:
void set_data(int rollno_n,char *name_n){
rollno=rollno_n;
strcpy(name,name_n);
}
void outdata( ){
cout<<"\n Roll No  "<<rollno;
cout<<"\n Name     "<<name;
}
};
void main( ){
student s1,s2;
s1.set_data(1,"Samidha  ");
s2.set_data(11,"Samir   ");
cout<<"\n Students Detail ";
s1.outdata( );
s2.outdata( );
getch( );
}
Example 9
#include<iostream.h>
#include<conio.h>
class part
{
private:
int modelnum,partnum;
float cost;
public:
void setpart(int mn,int pn,float c)
{
modelnum=mn;
partnum=pn;
cost=c;
}
void showpart( )

{
cout<<"\n Model  : "<<modelnum;

cout<<"\t Number : "<<partnum;
cout<<"\t Cost   : "<<cost;
            }
};
void main( )
{
clrscr( );
part p1,p2;
p1.setpart(1995,23,1250.50);
p2.setpart(1999,28,1350.50);
cout<<"\n\t\t\t First Part Details";
cout<<"\n\t\t------------------------------------\n";
p1.showpart( );
cout<<"\n\n\t\t\t Second Part Details";
cout<<"\n\t\t------------------------------------\n";
p2.showpart( );
getch( );
}
Example 10(Constructor Program)
#include<iostream.h>
#include<string.h>
#include<conio.h>
class vector
{
private:
            int *v;
            int size;
public:
            vector(int v_size)
{
            size = v_size;
            v = new int[v_size];
            }
            vector(vector &v2);
            ~vector( ){
            delete v;
            }
            void show( );
            int &elem(int i)
{
            if (i>=size)      
{
            cout<<"\n Error :Out of Range ";
            return size;
            }
            else{

            return v[i];
            }
            }
            };
vector::vector(vector &v2)
{
cout<<"\n Copy Constructor Invoked ";
size = v2.size;
v = new int[v2.size];
for(int i=0;i<v2.size;i++)
{
v[i] = v2.v[i];
            }
}
void vector::show( )
{
for(int i=0;i<size;i++)
{
cout<<elem(i)<<",";
            }
}
void main( )
{
clrscr( );
int i;
vector v1(5),v2(5),v3(5);
for(i=0;i<5;i++){
v2.elem(i)=i+1;
v1=v2;
vector v3 = v2;
cout<<"\n Vectors V1 : ";
v1.show( );
cout<<"\n Vectors V2 : ";
v2.show( );
cout<<"\n Vectors V3 : ";
v3.show( );
}
getch( );
}

Top

No comments:

Post a Comment