Académique Documents
Professionnel Documents
Culture Documents
com)
22
Syllabus
Specifying a class, Defining member functions, Arrays within a class, Creating objects,
memory allocation for objects, static data & member function, Arrays of objects, objects as
function argument.
Class and Object
Q1.What is class? How they are defined ?Describe them
Ans. A class is a way to bind the data and its associated functions together. It allows the
data (and functions) to be hidden, if necessary, from external use. When defining a
class, we are a new abstract data type that can be treated like any other built-in data
type. Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
The class declaration describes the type and scope of its members.
The class functions definitions describe below the class functions are implemented.
The general form of a class declaration is:
class class_name
{
private:
variable declarations;
//data members
function declarations; //member function
public:
variable declarations;
function declaration;
//data member
// member Function
};
The class declaration is similar to a struct declaration. The keyword class
specifies, that what follows is an abstract data of type class_name. The body of a class is
enclosed within braces and terminated by a semicolon. The class body contains the
declaration of variables and functions. These functions and variables are collectively
called class members. They are usually grouped under two sections, namely, private and
public to denote which of the members are private and which of them are public. The
keywords private and public are known as visibility labels. These keywords are followed
by a colon.
The class members that have been declared as private can be accessed only from
within the class. On the other hand, public members can be accessed from outside the
class also. The data hiding (using private declaration) is the key feature of objectoriented programming. The use of the keyword private is optional. By default, the
members of a class are private. If both the labels are missing, then, by default, all the
1
#include <iostream>
int n = 12;
int main()
{
int n = 13;
cout << ::n << endl;
cout << n << endl;
}
// A global variable
// A local variable
// Print the global variable: 12
// Print the local variable: 13
Q4. Describe how to access the class member (data member and member function)
Ans.The class body contains the declaration of variables and functions. These functions
and variables are collectively called class members. They are usually grouped under two
sections,
2
//data member
// member Function
};
Object
Object is software construct which binds
5
2
3.
4.
5.
6.
=
=
=
=
=
=
=
100;
100;
100;
100;
100;
100;
100;
9
This function takes three arguments, of which the last one has a default of twelve. The
programmer may call this function in two ways:
result = MyFunc(1, 2, 3);
result = MyFunc(1, 2);
In the first case the value for the argument called c is specified as normal. In the
second one, the argument is omitted, and the default value of 12 will be used instead.
There is no means to know if the argument has been specified by the caller or if
the default value was used.Also important point is that always trailing arguments can
have default values.Defaut argument are to be added from right to left only.We cannot
provide default argument value in middle of the argument list.
int add(int a , int b , int c=20);
// legal declaration
int add(int a =20 , int j);
// illegal declaration
int add(int a , int b=30, int c);
// illegal declaration
int add(int a=2 , int j =3 , int c);
// illegal declaration
Example
Class Simple_Interest
{
int principle_Amount;
float rate_of_interest;
int numer_of_year;
float sint;
public :
void getData(int pa , int noy , int ri=0.115)
{
principle_Amount = pa;
rate_of_interest = ri;
16
This variable is known as object. This variable will be the type of class declared. To
create at object you need to write
Classname objectname;
in the function main()
After creating objectname object, all data members are member functions declared in
class gets initialised and member functions can be called with the statement
objectname.function();
For Example this is class
Class student
{
private :
int roll;
int mark1, mark2;
float average;
public:
void getData()
{ ---------- }
void calculate()
{------------}
void displayData()
{------------}
}
Declaration of Object
Student S1 , S2[10] , *S3 ;
S1 is object of class student.
S2[100] is array of 10 object of class student.
S3 is pointer to an object of class student.
18
A1 object
Class abc
{
int a;
int b;
public:
void getdata( );
void disp( );
} a1, a2;
display
getdata
Count
r1
r2
r3
output
1
2
2
3
22
23
Array of Objects
Q35.How an array of object can be created demonstrate with c++ program
Ans.Similar to Array of structure in C, we also can have array of variables (objects) that
are of type class. Naturally, these variables are known as arrays of objects.
As we create the object using class name, we need to write array variable name along
with size of array along with class name.
Consider a following example :
class product
{
char model[20];
float price;
public;
void readdata();
void dispdata();
};
This is a class with name product, to create array of this class type, we can
write.
product telephones[10];
or
product entertainment[5];
Graphical representation
telephone(0)
telephone(1)
-------
telephone(9)
model
price
model
price
------- model
model
readata()
dispdata()
readata()
dispdata()
------- readata()
dispdata()
function is likely to be called a number of times in the program, a lot of extra time in executing a
series of instruction such as jumping to the function, saving registers, pushing arguments into
the stack and returning to the calling function out . when a function is small, a substantial
percentage of execution may be spent in such overheads. One solution to this problem may be
to use macro definition known as the pre processor macro. The major drawback of macro is that
they are not really function and therefore error checking does not occur at the time of
compilation.
C++ has different solutions i.e. a new feature called as inline function. This is a function
expanded in one line and when it is invoked. In inline function the error checking is possible. It
also has a return type. & the compiler replaces this function call with the corresponding
function code instead of jumping to the function memory location.
Syntax
Inline <return type> function name (arg)
28
Q41.Describe how function defined outside the class can be made INLINE.
Demonstrate with program code.
Ans.One of main objective of OOP is to separate the details of implementation from the
class definition.It is therefore good practice to define the member function outside the
class.
One can define a member function outside the class definition and still make it
inline by just using the keyword or qualifier inline in the header line if the function
definition.It is as demonstrated in the program below
Example
/*
Inline Member Functions */
#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
int a;
public :
// inline member functions
void setdata(int x)
{
a = x;
}
void print_square()
{
cout << "sqr(a) = " << a*a << "\n";
29
31
return t;
}
};
void main()
{
time t;
t.ss=t1.ss+t2.ss;
t.mm=t1.mm+t2.mm+t.ss/60;
t.ss=t.ss%60;
t.hh=t1.hh+t2.hh+t.mm/60;
t.mm=t1.mm+t2.mm+1;
int r;
r.getd();
r.disp();
getch();
Create a class distance having data members feet & inches add two distance & display the
resultant distance in proper format. Initialize the objects with proper feets & inches.
Class distance
{
int feet,inch;
public:
void getd(int f, int I)
{
feet=f;
inch=I;
}
void display()
{
cout<<<<inch<<;
}
distance cal(distance a, distance b)
{
distance t;
int i=0;
t.inch=a.inch+b.inch;
while(t.inch>12)
{
t.inch=t.inch-12;
i++;
}
t.feet=a.feet+b.feet;
return(t);
}
};
void main()
{
distance a,b,c;
a.getd(10,10);
b.getd(5,10);
c=c.cal(a, b);
c.disp();
}
32
Program-2
Maintain the record of students and give the total marks for 3 subjects and calculate the
average for each student and displays the contents on screen.
#include <stdio.h>
#include <string.h>
struct class
{
int roll_no;
char name[15];
int m1, m2, m3;
} c[10];
main( )
{
int total, I;
float avg;
for(I=O; I<=9; I++)
{
printf(\n enter roll no, name and marks of three subjects for %d student=);
scanf(%d %s %d %d %d %d, &roll _no, &name[I], &m1[I], &m2[I], &m3[I]);
}
for (I=0; I<=9; I++)
{
total=c[I]m1 + c[I]m2 + c[I]m3;
avg = total / 3;
printf(\n roll no=%d name=%s marks of three subjects= %d %d %d total=%d avg=
%f,
roll_no[I],c[I].name, c[I].m1, c[I].m2, c[I].m3, total, avg);
}
getch( );
}
Although it is normal practice to place all the data members in private section in member
function in public section. But some situation may require certain function hidden in main
function such as detecting an account number in customer file or increase the salary of
employee are events of serious consequences.Such function should be restricted from the
outside access.
Class emp
{
int ecode;
char name[10];
float sal;
void update sal();
public:
void input();
void disp();
return(cir)
}e1;
33
void display()
{
cout <<\n Principle Amount =<<
principle_amount ;
36
Write a program to declare a class rectangle having data member length and
breadth.Accept this data form one object and display area and perimeter of
rectangle
Ans./* Program to find area of rectangle & Perimeter */
#include<iostream.h>
#include<conio.h>
class rectangle
{
private :
int len, br;
public:
void area_peri( );
//prototype declaration, to be defined
void getdata ( )
{
cout<<endl<<"Enter length and breadth ";
cin>>len>>br;
}
void setdata (int l, int b )
{
len = l;
br = b;
}
void displaydata( )
{
cout<<endl<<"length = "<<len;
cout<<endl<<"breadth = "<<br;
}
37
Write a program to declare class time having data member as hrs , min , sec.
write a constructor to accept data and use display function for two object
Ans.
Class Time
{
private :
int hrs , min , sec;
public :
Time()
{
cout << \n Enter the Hours = ;
cin>>hrs;
cout << \n Enter the Minute =;
cin>>min;
cout << \nEnter the seconds =;
cin>>sec;
}
void displayTime()
{
cout <<\n Time in HH:MM:SS Format;
cout<<hrs<<:<<min<<:<<sec;
}
38
public :
void getStudent()
{
cout << \n Enter the name = ;
cin>>name;
cout << \n Enter the Roll No.=;
cin>>roll;
}
void display()
{
cout <<\n Name =<<name;
cout<<\n Roll Number =<<roll;
}
};
void main()
{
student s1 , s2 , s3 , s4;;
s1.getStudent();
s2.getStudent();
s3.getStudent();
s4.getStudent();
s1.display();
s2.display();
39
Write C++ program two read two numbers and find sum, diff., product and
division using different member function for each.
Ans.
class operations
{
int num1 , num2;
public:
void getNumbers(int n1, int n2)
{
num1 = n1;
num2 = n2;
}
void Addition()
{
int num3;
40
42
b. How many ways we can define member function in class? Give its syntax.
Ans.Refer Q.No.
c. Declare a class simple interes having data member as pricniple amount rate of
interest , number of year.The constructor will have default value of rate of
interest as 11.5%.Accept this data for two object.Calcualte and display simple
interest for each object
Ans.Refer Q.No.
d. Write a program to declare a class rectangle having data member length and
breadth.Accept this data form one object and display area and perimeter of
rectangle
Ans.Refer Q.No.
e. Write a program to declare class time having data member as hrs , min , sec.
write a constructor to accept data and use display function for two object
Ans.Refer Q.No.
43
b. Write syntax for defining member function outside the class definition.
Ans.Refer Q.No.
c. Write program to calculate area of square and area of rectangle.
Ans.Refer Q.No.
d. Write C++ program two read two numbers and find sum, duff., product and
division using different member function for each.
Ans.Refer Q.No.
e. Explain the concept object as function argument
Ans.Refer Q.No.
44
46