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

Unit 3 - Classes and Objects

The document provides an overview of classes and objects in C++. It defines classes as user-defined data types that can contain both data members and member functions. Objects are instances of a class and access the class's data members and functions. The document discusses class declaration syntax, access modifiers, constructors and destructors. It provides examples of defining classes and accessing members through objects.

Uploaded by

Anupam Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Unit 3 - Classes and Objects

The document provides an overview of classes and objects in C++. It defines classes as user-defined data types that can contain both data members and member functions. Objects are instances of a class and access the class's data members and functions. The document discusses class declaration syntax, access modifiers, constructors and destructors. It provides examples of defining classes and accessing members through objects.

Uploaded by

Anupam Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

CLASSES AND

OBJECTS
Review of Structures
◦Structures are user defined derived data types
◦Structures, unlike arrays, can hold different data types at
the same time
◦ Declaration syntax: struct structName
{
data_type var1;
data_type var2;
………
}; Prepared by Sherin Joshi
Review of Structures
◦The declaration is usually made outside the main body
◦eg: struct Person
{
int roll;
float weight;
char gender;
string name;
}; //to create variables in declaration → }p1,p2;
Prepared by Sherin Joshi
Review of Structures
◦Syntax to create structure variable: structName strVar;
◦Then, by the help of the dot (.) operator, any member
of the structure can be accessed
◦Syntax: strVar.var1 = someValue;
◦eg: struct Person p1;
p1.roll = 15;

Prepared by Sherin Joshi


Review of Structures
◦We can also define a structure within another structure
(nested structure)
◦Syntax: struct Internal struct External
{ {
int a; int b;
//some members //other members
}; struct Internal intern;
};
Prepared by Sherin Joshi
Review of Structures
◦In main( ),
struct External ext;
ext.b = 7;
ext.intern.a = 24;

Prepared by Sherin Joshi


Review of Structures
◦eg: struct Human {
string name;
struct DOB
{
int year, month, day;
};
DOB birthday;
};
Prepared by Sherin Joshi
Classwork
Create a structure called “Student” with 5 members.
Input the information of 10 students and then display the
entered information.

Prepared by Sherin Joshi


Class
◦Class is a user defined data type
◦Class has both data members and member functions
that work on those data members
◦A class is a collection of objects of similar type
◦Class allows the data (and functions) to be hidden, if
necessary, from external use
◦Data hiding is done through access modifiers

Prepared by Sherin Joshi


Class
◦ By default, data members are ‘private’ (mode of
visibility/access modifier)
◦Class provides a blueprint for object creation
◦Once a class has been defined, we can create any
number of objects belonging to that class

Prepared by Sherin Joshi


Object
◦Objects are basic run-time entities of an object oriented
system
◦Program objects must be chosen such that they match
closely with real world objects
◦An object is a instance of a class
◦In simple terms, objects are variable of type class

Prepared by Sherin Joshi


Object

Prepared by Sherin Joshi


Class and Object

Prepared by Sherin Joshi


Class Declaration
class className //’class’ is a keyword used to define a class
{
private: //access modifier/visibility mode
//data members and member functions
protected:
//data members and member functions
public:
//data members and member functions
};
Prepared by Sherin Joshi
Class
◦Variables declared inside a class are called data
members
◦Functions declared inside a class are called member
functions
◦The keyword class is necessary to create a class

◦An object of a class can be created as:


className obj1, obj2,…, objN;
Prepared by Sherin Joshi
Access Modifiers
◦Data hiding inside a class is implemented using access
modifiers
◦There are three access modifiers:
◦private
◦public
◦protected

Prepared by Sherin Joshi


Access Modifiers
◦private
◦ The data members and methods inside private are
accessible by only the member functions of that class
and friend class
◦protected
◦ The data members and methods in this scope are
accessible by the member functions of that class,
friend of that class and also by the methods of derived
class
Prepared by Sherin Joshi
Access Modifiers
◦public
◦ The data members and methods inside public are
accessible by methods of that class, friend class,
derived class and from outside the class via objects

Prepared by Sherin Joshi


//Demonstration of a class

#include <iostream>
using namespace std;

class Student
{
private:
int roll;
char name[20];

Prepared by Sherin Joshi


public:
void getData( ) //member function
{ //defined inside class
cout << "Enter roll no : ";
cin >> roll;
cout << endl << "Enter name : ";
cin.ignore( );
cin.get(name, 20);
}
void showData( );
};
Prepared by Sherin Joshi
void Student :: showData( ) //member function defined
{ //outside class using scope
//resolution operator (::)
cout << endl << "Roll number : " << roll;
cout << endl << "Name : " << name;
}
int main( ) {
Student st;
st.getData( );
st.showData( );
return 0; }
Prepared by Sherin Joshi
Class and Object
◦Members of a class can be accessed via an object with
the help of a dot (.) operator
objName.memberVar;
objName.memberFunc( );

◦eg: obj1.getname( );
objPerson.name;

Prepared by Sherin Joshi


Class and Object
◦Member functions can also be defined outside the class
with the help of a scope resolution operator (::)
◦The syntax used for this is:
ret_type className :: funcName(list_of_args)
{
………
…..…..
}
Prepared by Sherin Joshi
Nested Class
Syntax: class className1 {
public:
//data
//methods
class className2 {
//data
//methods
};
};
Prepared by Sherin Joshi
Example: class Info {
public:
char name[25];
int roll;
void setall( );
class DOB {
public:
int year, month, day;
void setdob( );
}db;
};
Prepared by Sherin Joshi
Defining the member functions:
void Info :: setall( ) {
………
}
void Info :: DOB :: setdob( ) {
………
}
Calling the member functions:
Info obj;
obj.setall( );
obj.db.setdob( );
Prepared by Sherin Joshi
Classwork
Create a class named “CPU” with data members price
and Processor. “Processor” is itself a class with data
members cores and manufacturer. Include getter and
setter functions in each class. Create an object of CPU
and input the required information using the setter. Then,
display the entered information using the getter.

Prepared by Sherin Joshi


Constructors
◦Sometimes we need to set some properties of a class
whenever an instance of it is created
◦This is achieved with the help of constructors
◦Constructor is a special member function that has the
following characteristics
◦It should have the same name as that of class
◦There should be no return type, not even void

Prepared by Sherin Joshi


Constructors
◦Constructors are automatically called whenever any
instance of the class is created (by default)
◦They are usually placed in the public access
◦Since they can take arguments, constructors can be
overloaded
◦Constructors with arguments are called parameterized
constructors
◦Like other C++ functions, they can also have default
arguments
Prepared by Sherin Joshi
Syntax:
class className
{
…….
public:
…….
className( ) //default constructor
{
……. //initializing class object
}
};
Prepared by Sherin Joshi
Destructors
◦Destructors are special member functions having same
name as that of the class except that they start with a
tilde(~) character
◦They are automatically called when the class goes out
of existence
◦Destructors can also be explicitly called using object
and a dot(.) operator
◦They have no return types, not even void

Prepared by Sherin Joshi


Destructors
◦They also can’t have any argument, and hence can’t
be overloaded
◦Destructors are basically used for automatic removal of
class variables from the memory heap when they are
no longer needed
◦Syntax: ~className( ) {
………. //some codes
}
Prepared by Sherin Joshi
◦Example:
class Test
{
private:
………
public:
………
Test( ); //constructor
~Test( ); //destructor
}

Prepared by Sherin Joshi


//Demonstration of constructor and destructor
#include <iostream>
using namespace std;

class Student
{
private:
int roll;
int age;
int marks;

Prepared by Sherin Joshi


public:
Student( ); //default constructor
~Student( ); //destructor
void read( );
void display( );
};

Student :: Student( ) //constructor definition


{
roll = 0, age = 0, marks = 0;
cout << “Constructor has been called”;
}
Prepared by Sherin Joshi
void Student :: read( ) { //member function definition
cout << “Enter roll number: ”;
cin >> roll;
cout << “Enter age: ”;
cin >> age;
cout << “Enter marks: ”;
cin >> marks;
}
void Student : : display( ) { //member function definition
cout << endl << “Roll: ” << roll << “Age: ”;
cout << age << endl << “Marks: ” << marks;
} Prepared by Sherin Joshi
Student :: ~Student( ) {
cout << endl << “Destructor has been called”;
}
int main( ) {
Student obj; //Constructor called automatically
obj.display( ); //Values initialized by constructors displayed
obj.read( );
obj.display( );
return 0;
} //Destructor called automatically
// [we can also explicitly call it: obj.~Student( );]
Prepared by Sherin Joshi
Parameterized Constructors
◦Constructors can have arguments; ones with arguments
are called parameterized constructors
◦ Example:
class Test {
…….
public:
Test( ) { ……… } //Default Constructor
Test(int x, int y) { ……… }//Parameterized Constructor
//(Overloaded)
……… };
Prepared by Sherin Joshi
Parameterized Constructors
◦Passing parameters while instantiating a class:
className obj(par1, par2, …., parN);
◦Example:
Test t1(4,7);

◦When exact match of arguments in not found, implicit


conversions take place so as to match the parameters
with the parameterized constructor definition
Prepared by Sherin Joshi
Parameterized Constructors
◦Parameterized constructors can also have default arguments
//Declaration inside class (eg, class Check)
Check(int v1 = 100, int v2 = 200);
OR, Check(int = 100, int = 200);

◦They can be defined inside or outside the class


//Definition outside class
Check :: Check(int v1, int v2)
{ var1 = v1, var2 = v2; }
Prepared by Sherin Joshi
Classwork
Write a program using class that finds the distance
between two points in an XY-plane. Your class should
include a default constructor to give (0, 0) as the default
(x, y) coordinate and a parameterized constructor to
give a default (x, y) coordinate of your choice. Also
include a destructor in your class.

Prepared by Sherin Joshi


Copy Constructor
◦A copy constructor is a member function which
initializes an object using another object of the same
class

◦A copy constructor has the following general prototype:

className(const className &old_object);

Prepared by Sherin Joshi


//Copy constructor demonstration
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x1, int y1) {
x = x1;
y = y1;
}
Prepared by Sherin Joshi
//Copy Constructor
Point(const Point &p1)
{
x = p1.x;
y = p1.y;
}
int getx( )
{ return x; }
int gety( )
{ return y; }
};
Prepared by Sherin Joshi
int main( )
{
Point p1(10, 15); //Normal Constructor Called
Point p2 = p1; //Copy Constructor Called
//or, Point p2(p1);
cout << “p1.x = ” << p1.getx( );
cout << “ , p1.y = ” << p1.gety( );
cout << endl << “p2.x = ” << p2.getx( );
cout << “ , p2.y = ” << p2.gety( );
return 0;
}
Prepared by Sherin Joshi
Default Copy Constructor
◦It is already built into all classes
◦In the above example, even if the definition/declaration for
“Point (const Point &p1)” was not written, the statements
Point p2 = p1; OR Point p2(p1);
would still work

◦This is because p1 and p2 are objects of the same class and


hence the compiler knows how to copy them member by
member
Prepared by Sherin Joshi
Objects as Function Arguments
//Demo of objects as function arguments
#include <iostream>
using namespace std;
class Time
{
private:
int hrs, min;

Prepared by Sherin Joshi


public:
Time( ) { hrs = 0, min = 0; }
Time(int h, int m)
{
hrs = h, min = m;
}
void add(Time t1, Time t2)
{
hrs = t1.hrs + t2.hrs + (t1.min + t2.min) / 60;
min = (t1.min + t2.min) % 60;
}
Prepared by Sherin Joshi
void display( ) {
cout << “Hours = ” << hrs << “ Minutes = ” << min;
}
};
int main( ) {
Time t1(5, 45);
Time t2(7, 25);
Time t3;
t3.add(t1, t2);
t3.display( );
return 0;
} Prepared by Sherin Joshi
Returning Objects from Functions
//Demo of returning object from function
#include <iostream>
using namespace std;
class Time
{
private:
int hrs, min;

Prepared by Sherin Joshi


public:
Time( ) { hrs = 0, min = 0; }
Time(int h, int m) {
hrs = h, min = m;
}
Time add(Time t) {
Time temp;
temp.hrs = hrs + t.hrs + (min + t.min) / 60;
temp.min = (min + t.min) % 60;
return temp:
}
Prepared by Sherin Joshi
void display( ) {
cout << “Hours = ” << hrs << “ Minutes = ” << min;
}
};
int main( ) {
Time t1(5, 45);
Time t2(7, 25);
Time t3;
t3 = t1.add(t2);
t3.display( );
return 0;
} Prepared by Sherin Joshi
The ‘new’ and ‘delete’ Operators
◦They are used for dynamic memory allocation
◦The ‘new’ operator obtains memory from the OS and
returns a pointer to its starting point
◦The ‘delete’ operator accompanies a new operator
◦The reason is, in cases where memory is reserved using
the new operator, the reserved memory will not be
freed by default even after it is no longer in use
◦So, delete operator is used to clear the memory
reserved by the new operator
Prepared by Sherin Joshi
//Example
#include <iostream>
#include <cstring>
using namespace std;
int main( ) {
char *str = “Hello World! How are you?”;
int len = strlen(str);
char* ptr = new char[len+1];
strcpy(ptr, str);
cout << “ptr = ” << ptr << endl;
delete[ ] ptr;
return 0; } Prepared by Sherin Joshi
The ‘new’ and ‘delete’ Operators
◦Using these operators for class:
MyClass *ptr = new MyClass;

◦eg: MyClass *obj = new MyClass;


◦This reserves sufficient memory on the memory heap
that is required by an object of ‘MyClass’
◦To delete: delete obj;

Prepared by Sherin Joshi


Pointers to Objects
//Using pointer to object
#include <iostream>
using namespace std;

class Student
{
private:
int roll;
string name;
Prepared by Sherin Joshi
public:
void setvalues( ) {
cout << endl << “Enter roll number: ”;
cin >> roll;
cout << endl << “Enter name: ”;
cin.ignore( );
getline(cin, name);
}
void getvalues( ) {
cout << endl << roll << “ , ” << name;
}
}; Prepared by Sherin Joshi
int main( )
{
Student s; //object of class Student
Student *sptr; //pointer to Student
sptr = &s;
sptr -> setvalues( ); //same as: s.setvalues( );
//cout << sptr -> roll; ----------- error
sptr -> getvalues( );
return 0;
}

Prepared by Sherin Joshi


Static Data Members and Static
Member Functions
◦The keyword static is used for denoting static class
members
◦Static data are created only once and shared by all the
objects of the class, even if there are multiple instances
of the same class
◦They can be declared private, public, or protected
◦There are static member functions to access static data
members
Prepared by Sherin Joshi
Static Data Members and Static
Member Functions
◦Static members are initialized to zero when the first
object of their class is created
◦Useful when we have to access some data until any
object of the class is alive
◦ Static member functions can have access to other
static member functions and data members only (but
not other member functions)

Prepared by Sherin Joshi


Static Data Members and Static
Member Functions
◦But, other member functions can call static data
members and functions
◦type and scope of each static member variable must
be defined outside the class definition; this is necessary
because the static data members are stored separately
rather than as a part of an object
◦A static member function can be called using the class
name as:
className :: funcName; Prepared by Sherin Joshi
//Static data members and static member functions
#include <iostream>
using namespace std;
class Test {
private:
int code;
static int count;
public:
void setcode( ) {
code = ++count;
}
Prepared by Sherin Joshi
void showcode( );
static void showcount( );
};
int Test :: count;
void Test :: showcount( ) { //"static" keyword not
//required in definition
cout << "Count : " << count << endl;
}
void Test :: showcode( ) {
cout << "Object number : " << code << endl;
}
Prepared by Sherin Joshi
int main( ) {
Test t1,t2;
t1.setcode( );
t2.setcode( );
Test :: showcount( ); //Static function called through class
t2.showcount( ); //And also normally through objects
Test t3;
t3.setcode( );
Test :: showcount( );
t1.showcode( );
t2.showcode( );
t3.showcode( );
return 0; } Prepared by Sherin Joshi
Friend Function & Friend Class
◦Sometimes, apart from the need of data abstraction
and data hiding through class, we need to access the
private data members and member functions from
outside the class
◦These situations arise while designing large programs
when there is a need for maintenance and
modification
◦This need can be fulfilled through the use of friends
◦The keyword friend used is used to create a friend
function or friend class
Prepared by Sherin Joshi
Friend Function
◦A friend function is declared as:
friend ret_type func_name(list_of_args);
◦Friend functions can access all data members (private/
public/ protected) without any issue
◦Object of the class is passed as an argument in a friend
function
◦While defining a friend function, the keyword friend
before the return type is not needed; putting it is a
syntactical error
◦They can be declared in any region of the class
Prepared by Sherin Joshi
Friend Function

Prepared by Sherin Joshi


//Demonstration of a friend function
#include <iostream>
using namespace std;
class MyClass
{
private:
int a;
public:
void read( );
friend void display(MyClass obj);
};
Prepared by Sherin Joshi
void MyClass :: read( )
{
cout << "Enter value : ";
cin >> a;
}

void display(MyClass object)


{
cout << endl << "Value = " << object.a;
}

Prepared by Sherin Joshi


int main( )
{
MyClass ob;
ob.read( );
display(ob);
return 0;
}

//Using friend function, we displayed the private data ‘a’


//of the class ‘MyClass’

Prepared by Sherin Joshi


Friend Class
◦Sometimes, when data is to be communicated
between classes (i.e. message passing between classes
is to be done), friend class is defined

Prepared by Sherin Joshi


Declaration:
class Second; //forward declaration
class First
{
friend class Second; //creating friendship
private:
………
public:
………
protected:
………
};
Prepared by Sherin Joshi
Friend Class
◦In the above declaration, Second has been granted
friendship of First, but First has not been granted
friendship of Second
◦Here, any public method of Second can access the
private members of First
◦However, public methods of First cannot access the
private members of Second
◦For this to be possible, First should also be declared as a
friend of Second in its definition body
Prepared by Sherin Joshi
#include <iostream>
using namespace std; First Friendship Second
class Second;
class First {
friend class Second; //can be in any access modifier,
private: //writing ‘class’ is mandatory
int x,y,z;
public:
First( ) {
x=5,y=10,z=15;
}
}; Prepared by Sherin Joshi
class Second {
public:
void display(First obj) {
cout << "The sum = " << obj.x + obj.y + obj.z;
}
};
int main( ) {
First objfirst;
Second objsecond;
objsecond.display(objfirst);
return 0;
} Prepared by Sherin Joshi
Classwork
Using a friend function between classes, write a program
that adds the total capital of a joint venture company
of 3 partners.

Prepared by Sherin Joshi

You might also like