You are on page 1of 18

Department: Computer Science & Technology Semester: 4th

Subject: Object Oriented Programming


Presented by Philip Lepcha, Darjeeling Polytechnic, Kurseong
_________________________________________________________

Objects & Classes:


2.1 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.
2.2 Class specifiers and their uses, distinction
between structure (struct) of C and Class.

Specifying a Class
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 creating a new abstract data type that can be treated like any other
build-in data type.
Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
The class declaration describes the type scope of its members. The class function
definitions describe how the class functions are implemented.
The general form of a class declaration is:

class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

class is a keyword, class_name is the user defined name, private and public are the
access specifiers e.g

class student

private:
int roll_no;

char name[20];

int marks;

public:

void getdata(void);

void putdata(void);

};

Member Functions of Classes in C++


Member functions can be defined in two places:
 Outside the class definition
 Inside the class definition

 Outside the class definition


The general form of a member function definition is:
return type class_name :: function_name(argument decleration)
{
Function body
}
The membership label class_name :: tells the compiler that the function_name
belongs to the class_name. :: is called the scope resolution operator.
 Inside the member function
Another method of defining a member function is to replace the declaration
with the actual function definition inside the class.
When a function is defined inside the class it is treated as inline function.
For example:
class Cube

public:

int side;

/*

Declaring function getVolume


with no argument and return type int.

*/

int getVolume();

};

If we define the function inside class then we don't not need to declare it first, we can directly
define the function.

class Cube

public:

int side;

int getVolume()

return side*side*side; //returns volume of cube

};

But if we plan to define the member function outside the class definition then we
must declare the function inside class definition and then define it outside.
class Cube

public:

int side;

int getVolume();

// member function defined outside class definition

int Cube :: getVolume()

return side*side*side;

}
Array within a Class
The array can be used as member variables in a class. The following class definition
is valid.

const int size=10;

class array
{
int a[size];
public:
void setval(void);
void display(void);
};

The array variable a[] declared as private member of the class array can be used in
the member function, like any other array variable. We can perform any operations
on it. For instance, in the above class definition, the member function setval() sets
the value of element of the array a[], and display() function displays the values.
Similarly, we may use other member functions to perform any other operation on the
array values.

Example:

#include<iostream>
#include<conio.h>

const int size=5;

class student
{
int roll_no;
int marks[size];

public:
void getdata ();
void tot_marks ();
};

void student :: getdata ()


{
cout<<"\nEnter roll no: ";
cin>>roll_no;

for(int i=0; i<size; i++)


{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
int main()
{
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
return 0;
}

OUTPUT:
Enter roll no.: 101
Enter marks in subject 1: 55
Enter marks in subject 2: 80
Enter marks in subject 3: 73
Enter marks in subject 4: 60
Enter marks in subject 5: 84
Total marks=352

Creating Objects
The declaration of a class does not create an object but only specifies what it will
contain. For example the declaration of the class array above does not create an
object of array. Once the class has been declared we can create variables of that
type by using the class name like any other built in type variable

e.g array a1,a2,a3;

here a1,a2,a3 are the objects of the class array.

Memory Allocation for Object of Class


Once you define class it will not allocate memory space for the data member of the
class. The memory allocation for the data member of the class is performed
separately each time when an object of the class is created.
Since member functions defined inside class remains same for all objects, only
memory allocation of member function is performed at the time of defining the class.
Thus memory allocation is performed separately for different object of the same
class. All the data members of each object will have separate memory space.

The memory allocation of class members is shown below:

Hence data member of the class can contain different value for the different object,
memory allocation is performed separately for each data member for different object
at the time of creating an object.
Member function remains common for all object. Memory allocation is done only
once for member function at the time of defining it.

Static Data Member


Static data members are class members that are declared using the static keyword.
There is only one copy of the static data member in the class, even if there are many
class objects. This is because all the objects share the static data member. The
static data member is always initialized to zero when the first class object is created.
The syntax of the static data members is given as follows −

static data_type data_member_name;

In the above syntax, static keyword is used. The data_type is the C++ data type such
as int, float etc. The data_member_name is the name provided to the data member.
A program that demonstrates the static data members in C++ is given as follows –
#include <iostream>

#include<string.h>

using namespace std;

class Student {

private:

int rollNo;

char name[10];

int marks;

public:

static int objectCount;

Student() {

objectCount++;

void getdata() {

cout << "Enter roll number: "<<endl;

cin >> rollNo;

cout << "Enter name: "<<endl;

cin >> name;

cout << "Enter marks: "<<endl;

cin >> marks;

void putdata() {

cout<<"Roll Number = "<< rollNo <<endl;

cout<<"Name = "<< name <<endl;

cout<<"Marks = "<< marks <<endl;

cout<<endl;
}

};

int Student::objectCount = 0;

int main(void) {

Student s1;

s1.getdata();

s1.putdata();

Student s2;

s2.getdata();

s2.putdata();

Student s3;

s3.getdata();

s3.putdata();

cout << "Total objects created = " << Student::objectCount <<


endl;

return 0;

The output of the above program is as follows −

Enter roll number: 1


Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78

Enter roll number: 2


Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55

Enter roll number: 3


Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3

Static Function Members

By declaring a function member as static, you make it 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 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 the
this pointer of the class. You could use a static member function to determine
whether some objects of the class have been created or not.
Example:
#include <iostream>

using namespace std;

class Box
{
public:
static int objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;

// Increase every time object is created


objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void)
{
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1


Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects after creating object.


cout << "Final Stage Count: " << Box::getCount() << endl;

return 0;
}

OUTPUT:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

Array of Objects
Like array of other user-defined data types, an array of type class can also be
created. The array of type class contains the objects of the class as its individual
elements. Thus, an array of a class type is also known as an array of objects. An
array of objects is declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is
class_name array_name [size] ;
Example : A program to demonstrate the concept of array of objects

#include<iostream>
using namespace std;
class books
{
char title[30];
float price;
public :
void getdata();
void putdata();
};
void books :: getdata ()
{
cout<<"Title:”;
Cin>>title;
cout<<"Price:”;
cin>>price;

}
void books :: putdata ()
{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n”;
const int size=3 ;
}
int main ()
{
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details o£ book "<<(i+1)<<"\n";
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}
The output of the program is

Enter details of book 1


Title: c++
Price: 325
Enter details of book 2
Title: DBMS
Price:. 455
Enter details of book 3
Title: Java
Price: 255
Book 1
Title: c++
Price: 325
Book 2
Title: DBMS
Price: 455
Book 3
Title: Java
Price: 255
Objects as Function arguments
The objects of a class can be passed as arguments to member functions as well as
nonmember functions either by value or by reference. When an object is passed by
value, a copy of the actual object is created inside the function. This copy is
destroyed when the function terminates. Moreover, any changes made to the copy of
the object inside the function are not reflected in the actual object. On the other
hand, in pass by reference, only a reference to that object (not the entire object) is
passed to the function. Thus, the changes made to the object within the function are
also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its
data members can be accessed inside the function using the object name and the
dot operator. However, the data members of the calling object can be directly
accessed inside the function without using the object name and the dot operator.
To understand how objects are passed and accessed within a member function,
consider this example.
#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata();
void putdata();
void sum_weight(weight,weight);
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight wl,weight w2)
{
gram = wl.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=wl.kilogram+w2.kilogram;
}
int main ()
{
weight wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}

Storage Classes in C++


Storage Classes are used to describe the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to trace the
existence of a particular variable during the runtime of a program. To specify the
storage class for a variable, the following syntax is to be followed:
Syntax:
storage_class var_data_type var_name;

C++ uses 5 storage classes, namely:


1. auto
2. register
3. extern
4. static
5. mutable

The auto Storage Class


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can
only be used within functions, i.e., local variables.

. The register Storage Class


The register storage class is used to define local variables that should be stored in
a register instead of RAM. This means that the variable has a maximum size equal
to the register size (usually one word) and can't have the unary '&' operator applied
to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C++, when static is used on a class data member, it causes only one copy of that
member to be shared by all objects of its class.
#include <iostream>

// Function declaration
void func(void);

static int count = 10; /* Global variable */

main() {
while(count--) {
func();
}
return 0;
}

// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is
visible to ALL the program files. When you use 'extern' the variable cannot be
initialized as all it does is point the variable name at a storage location that has
been previously defined.
When you have multiple files and you define a global variable or function, which will
be used in other files also, then extern will be used in another file to give reference
of defined variable or function. Just for understanding extern is used to declare a
global variable or function in another file.
The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.
First File: main.cpp
#include <iostream>
int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}

Second File: support.cpp


#include <iostream>
extern int count;

void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile
these two files as follows −
$g++ main.cpp support.cpp -o write
This will produce write executable program, try to execute write and check the
result as follows −
$./write
5

The mutable Storage Class


The mutable storage class specifier is used only on a class data member to make it
modifiable even though the member is part of an object declared as const. You
cannot use the mutable specifier with names declared as static or const, or reference
members..

class A

public:

A() : x(4), y(5) { };

mutable int x;

int y;

};

int main()

const A var2;

var2.x = 345;

// var2.y = 2345;

In the above example the compiler would not allow the assignment var2.y = 2345
because var2 has been declared as const. The compiler will allow the assignment
var2.x = 345 because A::x has been declared as mutable .
Distinction between structures in C and Class

C structures cannot have member function while C++ class always has.

C structures must have at least one data member in it to compile. C++ class can be
empty. It is possible to have a C++ class without member variables and member
functions.

Static member variables are not allowed in C structures. C++ can have static
members.

You might also like