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

Unit 3 Classes and Objects

The document discusses classes and objects in C++. Some key points: 1) A class defines the data representation and behavior of an object through data members and member functions. 2) Data members represent the properties of an object, while member functions define its behaviors. 3) Objects are instances of a class that allocate memory dynamically. They can access both public and private class members. 4) Constructors initialize objects and are automatically called upon object creation. Parameterized constructors allow passing arguments.

Uploaded by

Nabin Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Unit 3 Classes and Objects

The document discusses classes and objects in C++. Some key points: 1) A class defines the data representation and behavior of an object through data members and member functions. 2) Data members represent the properties of an object, while member functions define its behaviors. 3) Objects are instances of a class that allocate memory dynamically. They can access both public and private class members. 4) Constructors initialize objects and are automatically called upon object creation. Parameterized constructors allow passing arguments.

Uploaded by

Nabin Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Classes and Objects

Unit -3
Classes
 A class is a fundamental building block of OOP
 It is user defined data type that encapsulates data members
(variables) and member functions (methods) into a single unit.
 The data members represent the state/properties/attributes of the
class
 The member functions define its behavior or actions
 Keyword class is used during declaration of class
 class Class_Name{
 private:
 variable declarations;
 function declarations;
 public:
 variable declarations;
 function declarations;
 }
 The members that have been declared as private can be accessed
only from within the class
 The public members can be accessed from within or outside the class
 The use of keywords private is optional by default
 The variables declared inside the class are known as data members
and the functions are known as members
 Only the member functions can have access to the private data
members and private functions
 However, the public members can be accessed from the outside the
class
 The binding of data and functions together into a single class type
variable is referred to as encapsulation
 Syntax:-
 class item

 {

 int member;

 float cost;

 public:
 void setdata (int a ,float b);
 void getdata (void);

 The class item contains two data members and two function members, the data
 members are private by default while both the functions are public by declaration
 The function setdata() can be used to assign values to the member variables
member and cost, and getdata() for displaying their values
 These functions provide the only access to the data members from outside the
class
Data Members
 The variables declared inside the class are known as
data members and the functions are known as
member functions
 Only member functions can have access to private
data members and private functions
 However, the public members (both functions and
data) can be accessed from outside the class
Accessing Class Members
 Private data of class can be only accessed
through the member function of that class
 Format for calling member function:
 object_name.function_name(actual args);
 For e.g.
Defining member functions
 Can be defined in two places:
 Inside the class
 Outside the class
 Member functions declared inside a class have to
defined separately outside the class
 We use scope resolution operator (::) for defining
member function outside the class
 Member function definition syntax:
 return_type class_name::function_name(argument declaration){
 // function body
 }
 The membership label class_name:: tells the
compiler that the function_name belongs to the
class class_name
 It also means that the scope of the function is
restricted to the class_name specified in the
header line
Creating Objects
 The creation of class does not define any objects
but the class only specifies what they will contain
 Once the class has been declared, we can create
variable of that type using the class name
 In c++ the class variables are known as objects
 In the above example item i creates a variable of type Item
 Hence x is called an object of type Item
Access specifiers/Access Modifiers
in C++
 Access modifiers are used to implement an
important feature of OOP known as data hiding
 There are three types of access modifiers available
in c++ :
 Public
 Private
 Protected
 Public :
 All the class members declared under public will
be available to everyone
 The data members and member functions
declared public can be accessed by other classes
too
 The public members of class can be accessed
from anywhere in the program using the direct
member access operator (.) with the object of that
class
 Private :
 The class members declared as private can be
accessed only by the functions inside the class
 They are not allowed to be accessed directly
by any object or function outside the class
 Only the member functions or friend functions
are allowed to access the private data
members of a class
 Protected :
 Protected access modifier is similar to that of
private access
 The difference is that the class member
declared as protected is inaccessible outside
the class but can be accessed by any subclass
(derived class)
Memory Allocation for Objects
 Before using member of a class it is necessary to
allocate the required memory space to that
member
 The memory space is allocated only when an
object of class is declared not when data members
are declared inside class
 Hence objects create space for data
 On the other hand, the memory space for the member
functions is allocated only once when the class is defined
 That is, there is only single copy of each member function
which is shared among all the objects

getData() setData()

book book book


title 1 price title 2 price title 3 price

Memory allocation for the objects of the class Book


Array of objects
 We can have arrays of variables that are of type class
 Such variables are called array of objects
 Eg. employee manager[3] // array of manager
 employee cashier[2] // array of cashier
 Here array manager contains three objects I.e
manager[0],manager[1],manager[2]
Static Data Members
 When we declare a normal variable inside a class like int a = 0,
different copies of data members are created with the associated
objects
 In some cases when we need a common data member that should
be same for all the objects.
 To do so we need static data members.
 Static member is a variable which is declared with the static
keyword, it is also known as class member thus only single copy of
variable is created for all objects.
 Declaration
 static data_type member_name;
 Definition
 Should be defined outside class following this syntax:
 data_type class_name::member_name = value;
 Example :
 Program to calculate area and perimeter by user input data using the concept of class and object

 Program to convert usd to npr or npr to usd using the concept of class and object

 Write a C++ program to calculate the area of triangle, rectangle and circle using constructor overloading. The program should be menu
driven.

 Create a C++ class for player object with the following attributes player no., name, number of matches and number of goals done in each
match. The number of matches varies for each player. Write parameterized constructor which initializes player no., name, number of
subjects and creates array for number of goals and number of matches dynamically.

 Write a suitable program to demonstrate the destructor.

 Write a C++ program to find the area of circle using class circle which have following details:

 a. Accept radius from the user

 b. Calculate the area

 c. Display the result

 Define a class to represent a bank account. Include the following members:

 Data members:

 1) Name of the depositor

 2) Account number

 3) Type of account
Objects as function arguments
 We can pass any type of arguments and any number of arguments within the
member functions
 In c++ we can also pass an object as an argument within the member
function of class
 Useful when we want to initialize all data members of an object with another
object
 We can pass objects and assign the values of supplied object to the current
object
 Useful in large or complex projects as we have seen before in message
passing
Here,

 object r is passed as
object argument in
member function send()

 send() function receives


Receiver's object as
argument and call it’s
receive() method
Returning object from function in c++
 A function can return objects either by value or by
reference
 When an object is returned by value, a temporary
object is created within the function which holds the
return value
 This value is further assigned to another object in the
calling function
Returing Object By Value
Returing Object By
Reference
Constructor
 A special type of member function that initializes
objects of a class
 In c++ constructor is automatically called when
object is created
 Constructor have same exact name as the class and
it does not have any return value, not even void
Why constructor is needed?
 To initialize number of data member for objects
which only needs the default value. E.g we have
100s of objects with data member as age which
needs the initialization of 0 as its initial value.
 If we want some code to be executed
immediately after object is created, we can place
the code inside the body of the constructor.
Types of constructor
 Default Constructor
 Parameterized Constructor
Default Constructor
 A constructor which does not take any argument
(It has not parameters)
 Example:
 class Hello {
 Hello ( ) {

 }
 }; No
arguments
Parameterized constructor
 Arguments are passed to the constructor
 To initialize and object when it is created
 To create parameterized constructor is same as creating parameterized function
 Example:
 class Hello {
 int age;
 int roll;

 Hello (int a, int r ) {


 age = a;
 roll = r;

 }
 };
Characteristics of constructor
 Name same as class name
 Should be declared as public
 They are called automatically when objects are
created
 They don’t have return type, not even void
 They can have default arguments
 We cannot refer to their address
Friend Function
 If a function is defined as a friend function then
private and protected data of a class can be
accessed using the function
 We can create friend function by using the friend
keyword
 Friend function should be declared inside the class
(either in public section or private section)
 Declaration
 class class_name{
 friend return_type function_name(args);
 }
 Definition
 return_type function_name(args){

 }
 Note: no friend keyword is used in definition
 Characteristics of friend function
 It takes object as arguments
 It is called like a normal function without object
 It is not in scope of class in which it is declared
 It can be declared either in public or private scope
 It has full access to private members of class
Destructor
 A member function which destructs or deletes
an object
 When is it called?
 An object of class goes out of scope
 Object is explicitly deleted using delete keyword
 Note:
 Destructor have same name as a class name but they don’t
take any arguments and don’t return anything.
 There can be only one destructor in a class with classname
preceded by ~
 Destructor is used for :
 Performing cleanup task
 Deallocate any resources that object might have acquired
 Eg
 class ClassName {
 public:
 // Constructor
 ClassName() {
 // Constructor code
 }

 // Destructor
 ~ClassName() {
 // Destructor code
 }
 };

You might also like