0% found this document useful (0 votes)
56 views

Class: Control Structures: Classes and Objects: Specifying A Class, Defining Member Functions, C++

This document provides an overview of control structures, classes and objects in C++. It discusses class declarations and definitions, creating objects, accessing class members, defining member functions inside and outside classes, private member functions, nesting member functions, static data members, and static member functions. The key points are: 1) A class binds data and associated functions together, with declarations describing types and scopes of members and definitions implementing functions. 2) Objects are created using the class name to access members, with memory allocated separately for each object's members. 3) Private members can only be accessed by other class members, while public members can be accessed by objects. 4) Member functions can be defined inside or outside classes

Uploaded by

Akhil Akhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Class: Control Structures: Classes and Objects: Specifying A Class, Defining Member Functions, C++

This document provides an overview of control structures, classes and objects in C++. It discusses class declarations and definitions, creating objects, accessing class members, defining member functions inside and outside classes, private member functions, nesting member functions, static data members, and static member functions. The key points are: 1) A class binds data and associated functions together, with declarations describing types and scopes of members and definitions implementing functions. 2) Objects are created using the class name to access members, with memory allocated separately for each object's members. 3) Private members can only be accessed by other class members, while public members can be accessed by objects. 4) Member functions can be defined inside or outside classes

Uploaded by

Akhil Akhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

EID 201: OOPS With C++ Lecture Notes: MODULE II

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.

The General form of a class declaration

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.

Example for class specification:

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.

Objects can also be declared at the end of class specification as


class student
{
int rno;
char name[10];

public:

void get();

void put();

}s1,s2;

Accessing class members

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;

Defining member functions

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.

Syntax for defining the member function within class specification

return-type function-name ( arguments if any)


{
Body of the function
}

In case of outside of the class definition, we should use scope resolution operator (::)along with
membership lable i.e., class name.

Syntax for defining the member functions outside of the class:

return-type class-name :: function-name (arguments if any)


{
Body of the function
}
EID 201: OOPS With C++ Lecture Notes: MODULE II

Memory allocation for objects


The memory space for objects is allocated when they are declared and not when the class is
specified. The member functions are created and placed in the memory space only once when
they are defined as a part of a class specification. Since all the objects belonging to that class use
the same member functions, no separate space is allocated for member functions when the
objects are created. Only space for member variables is allocated separately for each object.
Separate memory locations for the objects are essential, because the member variables will hold
different data values for different objects

Common for all objects

Member function 1

Member function 2

object 1 object2 object3

data member 1 data member 1 data member 1

data member 2 data member2 data member 2

Memory created when objects defined


EID 201: OOPS With C++ Lecture Notes: MODULE II

Simple C++ Program

#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

Private member functions

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.

Sample program illustrating private member function


#include<iostream.h>
class maximum
{
int a,b;
int max();//private member function
public:
void read();
void print();
};
void maximum::read()
{
cout<<"\n enter a and b: ";
cin>>a>>b;
}
void maximum::print()
{
cout<<"value of a: "<<a;
cout<<"value of b: "<<b;
cout<<"maximum value is : "<<max();
}
int maximum::max()
{
if(a>b)
return a;
EID 201: OOPS With C++ Lecture Notes: MODULE II

return b;
}
main()
{
maximum A;
A.read();
A.print();
}

Nesting of member functions


A member function that is called within another member function is known as nesting of member
functions.

Sample program illustrating nesting of member function


#include<iostream.h>
class average
{
int a,b;
public:
void read();
void print();
int avg();
};
void average::read()
{
cout<<"\n enter a and b: ";
cin>>a>>b;
}
void average::print()
{
cout<<"value of a: "<<a;
EID 201: OOPS With C++ Lecture Notes: MODULE II

cout<<"value of b: "<<b;
cout<<"average is : "<<avg();
}
int average::avg()
{
return (a+b)/2;
}
main()
{
average A;
A.read();
A.print();
}

Static Data member and its characteristics


A data member of a class can be qualified as static. The properties of a static member variable
are similar to that of a C static variable.

The properties of static data member are:

 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

Static Member Function and its characteristics


We can define class member function as static using static keyword that makes member function
as independent of any particular object of the class. A static member function can be called even
if no objects of the class exist and the static functions are accessed using only the class name and
EID 201: OOPS With C++ Lecture Notes: MODULE II

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;
}

Arrays within a Class


The arrays can be used as member variables in a class. The array variable a[ ] declared as
a private member of the class sample can be used in the member functions, like any other
array variable. For example, the following class definition is valid.
Class sample
{
int a[10]; // array within a class.
Public:
Void setval();
Vpod display();
};
EID 201: OOPS With C++ Lecture Notes: MODULE II

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

Employee SBI[3]; // SBI contains 3-objects i.e, SBI[0],


SBI[1]
// and SBI[2]
Employee foreman[5]; //foreman contain 5 objects i.e.,
foreman[0], foreman[1], . . . ,foreman[4].

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:

Type function-name (argument-list if any);

Example: float volume(int x, float y, float z);


Note:each argument variable must be declared independently inside the parentheses. A combined
declaration like float volume(int x, float y, z); is illegal.

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

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
return; }

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:

int &max(int &x, int &y)


{
if (x>y) return x;
else return y;
}
EID 201: OOPS With C++ Lecture Notes: MODULE II

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;
}

Const Member Functions


If a member function does not alter any data in the class, then we may declare it as a const
member function as follows.
 void mul(int, int ) const;
 double getbalence( ) const;
The qualifier const is appended to the function prototypes in both declaration and definition.
The compiler will generate an error message if such function tries to alter the data values.

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”

You might also like