Class: Control Structures: Classes and Objects: Specifying A Class, Defining Member Functions, C++
Class: Control Structures: Classes and Objects: Specifying A Class, Defining Member Functions, C++
Module - II
Control Structures: Classes and Objects: Specifying a class, defining member functions, C++
program with class, private member functions, arrays within class, memory allocation for
objects, static data members, static member functions, arrays of objects, returning objects.
Functions in C++: Main function, function prototyping, call by references, return by references,
inline functions, default arguments.
---------------------------------------------------------------------------------------------------------------------
C++ incorporates all these extensions in another user defined type called as class.
Class
A class is a user defined data type that binds the data and its associated functions together.
Generally a class specification has two parts:
Class declaration
Class function definitions
Class declaration describes the type and scope of its members. The class function
definitions describe how the class functions are implemented.
class class_name
{
private:
Variable declarations;
Function declarations;
public:
Variable declarations;
Functions declarations;
};
EID 201: OOPS With C++ Lecture Notes: MODULE II
The key word 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. Not that these keywords are followed by a colon. If both
the labels are missing, then, by default, all the members are private.
The class members that have been declared as private can be accessed from only within the class
and public members can be accessed from outside the class. The variables declared inside the
class are known as data members and the functions are known as member functions. The binding
of data and functions together into a single class type variable is referred as encapsulation.
class student
int rno;
char name[10];
public:
void get();
void put();
};
The above specification specify that name of class is student. It includes rno and name as private
data member and get() and put() as public member functions.
EID 201: OOPS With C++ Lecture Notes: MODULE II
Creating Objects
Once a class has been declared, the variables can be created using the class name. The class
variables are known as objects. The declaration of an object is similar to that of a variable of any
basic data type. The necessary memory space is allocated to an object at this stage. The object is
used to access the members of the class. We may declare more than one object in one statement.
Example: Student S1, S2, S3; // S1, S2, and S3 are three objects of type Student.
public:
void get();
void put();
}s1,s2;
The private members of the class can be accessed only by public members and are not accessible
by the object.
The public member function are accessed by object as
object-name.funtion-name(actual-arguments);
Accessing a data member depends only on the access control of that data member. If it’s public,
then the data member can be easily accessed using the direct member access (.) operator with the
object of that class. If, the data member is defined as private or protected, then we cannot access
EID 201: OOPS With C++ Lecture Notes: MODULE II
the data variables directly. Then we will have to create special public member functions to
access, use or initialize the private and protected data members.
object-name.member-name;
We can define the member functions either inside of the class or outside of the class definitions.
If the member function are defined within class specification then they are defined as ordinary
functions.
In case of outside of the class definition, we should use scope resolution operator (::)along with
membership lable i.e., class name.
Member function 1
Member function 2
#include<iostream.h>
class student
{
private:
int rno;
char name[10];
float marks;
public:
void get()
{
cout<<"\n enter the student details: ";
cout<<"\n enter rno,name,marks:";
cin>>rno>>name>>marks;
}
void put();
};
void student::put()
{
cout<<"\n name : "<<name<<endl;
cout<<"roll no: "<<rno<<endl;
cout<<"marks: "<<marks<<endl;
}
void main()
{
student s;
s.get();
s.put();
}
EID 201: OOPS With C++ Lecture Notes: MODULE II
A member function which is declared in private section of a class is known as private member
function. A private member function can only be called by another member function its class.
Even an object cannot invoke a private function using the dot operator from outside.
return b;
}
main()
{
maximum A;
A.read();
A.print();
}
cout<<"value of b: "<<b;
cout<<"average is : "<<avg();
}
int average::avg()
{
return (a+b)/2;
}
main()
{
average A;
A.read();
A.print();
}
It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
It is visible only within the class, but its life time is the entire program.
Static variables are normally used to maintain values common to the entire class.
The type and scope of each static member variable must be defined outside class definition.
The static data members are defined outside the class specification as
data-type class-name::var-name=initial value;
EID 201: OOPS With C++ Lecture Notes: MODULE II
This is necessary because the static data members are stored separately rather than as a part of an
object. Since they are associated with the class itself rather than with object, they are also known
as class variables.
Sample Program:
Class Item
{
static int count;
Public:
void display()
{
cout<<”Count = “<< ++count<<endl;
}
};
int Item :: count;
int main()
{
Item A;
A.display();
A.display();
return 0;
}
Output:
Count=1
Count=2
the scope resolution operator (::). A static member function can only access static data member,
other static member functions and any other functions from outside the class. Static member
functions have a class scope and they do not have access to this pointer of the class.
Example:
Class Item
{
static int count;
public:
static void display()
{ cout<<”Count = “<< ++count<<endl;
}
};
Int Item::count;
int main()
{
Item::display();
Item::display();
return 0;
}
Array of Objects
An array can be of any data type including structure. Similarly, we can also have arrays of
variables that are of the type class. Such variables are called arrays of objects. For example:
class Employee
{
char name[20];
float age;
public:
void getdata();
void display();
};
Int main()
{Employee SBI[3];
Employee foreman[4];
---
Return 0;
}
The identifier Employee is a user defined data type and can be used to create objects that relate
to different categories of the employees. For example
Returning Objects
A function can not only receive objects as arguments but also can return them. The below
example illustrates how an object can be created and returned to another function.
EID 201: OOPS With C++ Lecture Notes: MODULE II
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r; imag = i
};
void setComplex(void)
{
cout << "Enter real and imaginary parts";
cin >> this->real; // cin>>real;
cin >> this->imag; // cin>>image; }
Complex add(const Complex & c)
{
Complex comp;
comp.real = this->real + c.real;
comp.imag = this->imag + c.imag;
return comp;
}
void printComplex(void)
{
cout << "Real : " << this->real << endl;
cout<< "Imaginary" << this->imag << endl;}
};
Function:
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
Dividing a program into functions is one of the major principles of top-down, structured
EID 201: OOPS With C++ Lecture Notes: MODULE II
programming. Another advantage of using functions is that it is possible to reduce the size of a
program by calling and using them at different places in the program.
Example:
int show( int n, int m)
{
int k;
k= n + m;
cout<<”The value of k = “<<k<<endl;
}
Function Prototype:
Function prototype is one of the major improvements added to c++. This prototype describes the
function interface to the compiler by giving details scuch as the number and type of arguments
and the type of return values. It is declaration statement in the calling program and is of the
following form:
Call by value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument. By default, C++ programming uses call by
value to pass arguments.
Example:
void swap(int x, int y)
{ int temp;
EID 201: OOPS With C++ Lecture Notes: MODULE II
Call by reference
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the parameter affect the passed
argument.
Example:
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
Return by reference
In C++ Programming, you can pass values by reference but also you can return a value by
reference. Consider the following function:
The above function return type is int&, it means that the function returns reference to x or
reference to y and the function call can appear on the left-hand side of an assignment statement.
That is, the statement max(a,b) = -1; is legal and assign -1 to a if it is large otherwise -1 to b.
Inline Function
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the function is
called at compile time. Any change to an inline function could require the program to be
recompiled because compiler would need to replace all the code once again otherwise it will
continue with old functionality. For example:
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main( )
{ cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
Some of the situations where inline expansion may not work are:
For functions returning values, if a loop, a switch, or a goto exists.
For functions not returning values, if a return statement exists.
If functions contain static variables.
If inline functions are recursive.
Default Arguments
EID 201: OOPS With C++ Lecture Notes: MODULE II
A default argument is a value provided in function declaration that is automatically assigned with
default value by the compiler if caller of the function doesn’t provide a value for the argument.
For example:
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
#include<iostream>
using namespace std;
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
/* Drier program to test above function*/
int main()
{ cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Const Arguments: The constant variable can be declared using const keyword. The const
keyword makes variable value stable. The constant variable should be initialized while declaring.
The const keyword can be used with: Variables, Pointers, Function arguments and return types,
Class Data members, Class Member functions and Objects. For example:
int x=5;
const int a = 10; // the value of a is constant. a++ is illegal
const int * v=&x; or int const * v=&x; // pointer to constant. *v=2 is illegal
(These type of pointers are the one which cannot change the value they are pointing to)
int * const w = &x; // constant pointer. W++ is illegal
(These type of pointers are the one which cannot change address they are pointing to)
const int * const z = &x; // constant pointer to a constant.
Main()
EID 201: OOPS With C++ Lecture Notes: MODULE II
{
Complex a, b, c, d;
cout << "Enter first complex no " << endl;
a.setComplex();
cout << "Enter second complex no"<< endl;
b.setComplex();
/* Adding two complex numbers */
cout << "Addition of a and b : " << endl;
c = a.add(b);
c.printComplex();
return 0;
}
Pointers to Members
It is possible to take the address of a member of a class and assign it to a pointer. The address of
a member can be obtained by applying the operator & to a “full qualified” class member name. A
class member pointer can be declared using the operator ::* with the class name.
For example:
class A
{
private:
int m;
EID 201: OOPS With C++ Lecture Notes: MODULE II
Public:
A( )
{
m = 5;
}
Void show() { cout<<”a=”<<a<<endl;}
}`
int main()
{
A a;
int A::*ip = &A::m; //pointer to data member
void (A::*pf)(void) = &A::show; //pointer to fun
cout<<a.*ip<<endl;
(a.*pf)( ); // calling show() using pf
}
We can define a pointer to the member m as follows:
int A::* ip = &A:: m;
In the above statement, A::* means “pointer-to-member of A class”.
The phrase &A::m means the “address of the m member of A Class”