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

Introduction To Classes

Uploaded by

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

Introduction To Classes

Uploaded by

bilalisb999
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Introduction to Classes

Muhammad Zulqarnain

Department of Computer Science,


Capital University of Sciences and technology Islamabad
Campus
But binary is hard (for humans) to work with…
Objects
An object is an identifiable entity with some characteristics,
state and behavior. Understanding the concept of objects is
much easier when we consider real-life examples around us
because an object is simply a real-world entity.
Class
A class is a group of objects that share
common properties and behavior.
What exactly is Object-oriented Programming?

• A new way of thinking about programming


• Organise your solution in terms of the objects/entities that
exist in the real world
• For example, in a Library Management System, you would
think about what objects there are in an actual library and
what each object should do
• Library member, books, librarian, etc…
• You then map your design to code
• We will learn in the remainder of this course how to
translate this object-oriented design to code
Classes
Classes in OOP
 Classes are constructs/templates that define objects
of the same type.
 A class has variables (members/data fields) and
functions.
 An object is one instance of a class;
 Just like “int number = 4” is one instance of
the type “int”.
 Here, int is the type from which you can create
many instances.
 A class is essentially a user-defined data type.
 It may also contain its own functions.
Class in C++ - Example
Class Data Members and Member Functions
• The data items within a class are called
data members or data fields or instance
variables

• Member functions are functions that are


included within a class. Also known as
instance functions.

• Classes contain a special function called a


constructor that is called when an object is
created.
Object Creation/Instantiation

• A constructor is invoked when an object is created.

• The syntax to create an object is:


ClassName objectName;
e.g. Student myStudent;

• This automatically invokes the no-arg constructor of the class


Student. (Constructors can also take arguments; we will look
at them later).

• We have created or instantiated an object called myStudent.


Object Member Access Operator
• After object creation, its data and functions can be
accessed (invoked) using:
• The . operator, also known as the object member access
operator.

• objectName.dataField references a data field in the


object (e.g. myStudent.name)

• objectName.function( ) invokes a function on


the object (e.g. myStudent.print())
A Simple Program – Object Creation
class Circle
C1 Object Instance
{
private:
double radius;
: C1
public:
Circle() radius: 5.0
{ radius = 5.0; }
double getArea( ) Allocate memory
{ return radius * radius * 3.14159; } for radius
};
int main()
{
Circle C1;
C1.radius = 10;
cout<<“Area of circle = “<<C1.getArea( );
}
Data Encapsulation

• A key feature of OOP is data hiding


• data is concealed within a class so that it cannot be accessed
mistakenly by functions outside the class.

• To prevent direct modification of class attributes (outside


the class), the primary mechanism for hiding data is to put
it in a class and make it private using private keyword.
This is also known as data field encapsulation.
Hidden from Whom?

• Data hiding means hiding data from parts of the program


that don’t need to access it. More specifically, one class’s
data is hidden from other classes.

• Data hiding is designed to protect well-intentioned


programmers from mistakes.
Access Modifiers/Specifier
• Access modifiers are used to set access levels for
variables, methods, and constructors.
• private, public, and protected
• In C++, default accessibility is private.
• The default constructor (provided by compiler) is always public.
Member Access Specifiers
• Programmer can specify a constructor to be private (no use) or public
• public
• Presents clients with a view of the services the class provides (i.e.,
interface)
• Data and member functions are accessible (outside class)

• private
• Default access mode
• Data only accessible to member functions and friends
• private members only accessible through the public class
interface using public member functions

• protected
• Accessible within the class they are declared, and derived classes.
• Not accessible to friends.
Member Functions

• Inline functions:
• are defined within the body of the class definition.

• Out-of-line functions:
• are declared within the body of the class definition and defined
outside.
Member Functions
Separating Declaration from Implementation
class Circle
{
private:
double radius;

public:
Circle(double r)
{ radius = r; }
double getArea( ); // Not implemented yet
};
double Circle::getArea()
{ return this->radius * radius * 3.14159; }
void main()
{
Circle C1(99.0);
cout<<“Area of circle = “<<C1.getArea();
}
1 // Fig. 6.3: fig06_03.cpp
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // Time abstract data type (ADT) definition
9 class Time {
10 public:
11 Time(); // constructor
12 void setTime( int, int, int ); // set hour, minute, second
13 void printMilitary(); // print military time format
14 void printStandard(); // print standard time format
15 private:
16 int hour; // 0 – 23
17 int minute; // 0 – 59
18 int second; // 0 – 59
19 };
20 Note the :: preceding
21 // Time constructor initializes each data member to zero. the function names.
22 // Ensures all Time objects start in a consistent state.
23 Time::Time() { hour = minute = second = 0; }
24
25 // Set a new Time value using military time. Perform validity
26 // checks on the data values. Set invalid values to zero.
27 void Time::setTime( int h, int m, int s )
28 {
29 hour = ( h >= 0 && h < 24 ) ? h : 0;
30 minute = ( m >= 0 && m < 60 ) ? m : 0;
31 second = ( s >= 0 && s < 60 ) ? s : 0;
33
34 // Print Time in military format
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute;
39 }
40
41 // Print Time in standard format
42 void Time::printStandard()
43 {
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
45 << ":" << ( minute < 10 ? "0" : "" ) << minute
46 << ":" << ( second < 10 ? "0" : "" ) << second
47 << ( hour < 12 ? " AM" : " PM" );
48 }
49
Private Member Functions

• Private Member Functions:


• Only accessible (callable) from member functions of the class

• No direct access possible (with object instance of the class)

• Can be: inline / out-of-line


Private Member
Function
(out-of-line)
const Member Functions
• const Member Functions: Read-only functions that
cannot modify object’s data members.

returnType functionName() const


{
//function body
}
Constant Functions
class Circle
{
private:
double radius;
public:
Circle ()
{ radius = 1; }
Circle(double rad)
const member
{ radius = rad; }
function cannot
double getArea() const
update/change
{ return radius * radius * 3.14159; }
object’s data
};
void main()
{
Circle C2(8.0);
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
Interface vs. Implementation
• Separating interface from implementation
• Makes it easier to modify programs

• Header files (.h)


• Contain class definitions and function prototypes

• Source-code files (.cpp)


• Contain member function definitions
1 // Fig. 6.5: time1.h
2 // Declaration of the Time class.
3 // Member functions are defined in time1.cpp
4
5 // prevent multiple inclusions of header file Dot ( . ) replaced with underscore ( _ ) in file name.

6 #ifndef TIME1_H
7 #define TIME1_H
If time1.h (TIME1_H) is not defined (#ifndef)
8 then it is loaded (#define TIME1_H). If TIME1_H
9 // Time abstract data type definition is already defined, then everything up to #endif is
ignored.
10 class Time { This prevents loading a header file multiple times.
11 public:
12 Time(); // constructor
13 void setTime( int, int, int ); // set hour, minute, second
14 void printMilitary(); // print military time format
15 void printStandard(); // print standard time format
16 private:
17 int hour; // 0 - 23
18 int minute; // 0 - 59
19 int second; // 0 - 59
20 };
21
22 #endif
23 // Fig. 6.5: time1.cpp
24 // Member function definitions for Time class.
25 #include <iostream>
26
27 using std::cout;
28 Source file uses #include to load the
29 #include "time1.h" header file
30
31 // Time constructor initializes each data member to zero.
32 // Ensures all Time objects start in a consistent state.
33 Time::Time() { hour = minute = second = 0; }
34
35 // Set a new Time value using military time. Perform validity
36 // checks on the data values. Set invalid values to zero.
37 void Time::setTime( int h, int m, int s )
38 {
39 hour = ( h >= 0 && h < 24 ) ? h : 0;
40 minute = ( m >= 0 && m < 60 ) ? m : 0;
41 second = ( s >= 0 && s < 60 ) ? s : 0; Source file contains
42 } function definitions
43
44 // Print Time in military format
45 void Time::printMilitary()
46 {
47 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
48 << ( minute < 10 ? "0" : "" ) << minute;
49 }
50
51 // Print time in standard format
52 void Time::printStandard()
53 {
54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
55 << ":" << ( minute < 10 ? "0" : "" ) << minute
56 << ":" << ( second < 10 ? "0" : "" ) << second
57 << ( hour < 12 ? " AM" : " PM" );
58 }
Accessors and Mutators #include <iostream>

(Getters & Setters) using namespace std;

class Employee {
• getter(Accessor): member private:
function gets value from a // Private attribute
int salary;
class’s member variable but
does not change it. public:
// Setter
void setSalary(int s) {
salary = s;
• Setters (Mutators):ember }
function that stores a value // Getter
int getSalary() {
in member variable. return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Access Modifier
Constructors and Destructors
Access Modifiers
• The access modifier determines how a class can be accessed.
• The designer of a class can apply an access modifier to the declaration of a
member (i.e. data member or member function) to control access to that
member.
• C++ uses three modifiers
• private
• protected
• public
• The declaration of data members and member functions in a class is by default
private.
• When there is no access modifier for a member, it is private by default.

32
Access Modifiers Contd…
• When a member is private, it can only be accessed inside the class.
• Member functions cannot be accessed directly for retrieving or changing.
• They can be accessed only through member functions.
• When a member is public, it can be accessed from anywhere (inside the same
class, inside the subclasses, and in the application).
• When a member is protected, it can be accessed inside the same class and inside
the subclass but cannot be accessed from anywhere.
• We will study subclasses later.

33
34
Access Modifiers for Data Members
• The modifiers for data members are normally set to private for
emphasis (although no modifier means private).
• This means that the data members are not accessible directly, they
must be accessed through the member functions.
• We can also set them to public or protected if we want.

35
Access Modifiers for Member Functions
• To operate on the data members, the application must use member
functions, which means that the declaration of member functions
usually must be set to public.
• Sometimes the modifier of a member function must be set to private,
such as when a member function must help other member functions
but is not allowed to be called by functions outside the class.

36
Example Private Data Member (P1)

37
Example Public Data Member (P2)

38
Example Protected Data Member (P3)

39
Example Private Member Function (P4)

40
Group Modifier Access
• We have used only one keyword, private, and one keyword, public, in
the whole class definition.
• This is referred to as group modification.
• A modifier is valid until we encounter a new one.

41
Constructors
• Constructor is a function in every class which is called when class
creates its object
• Helps in initializing data members of the class
• A class may have multiple constructors (constructor overloading;
makes it easy to construct objects with different initial data
values)
• A class may be declared without constructors. In this case, a no-
argument constructor with an empty body is implicitly declared
in the class and known as default constructor.
• Note: Default constructor is provided automatically only if no
constructors are explicitly declared in the class.
Constructors’ Properties

 Must have the same name as the class itself.

 Do not have a return type—not even void.

 Play the role of initializing objects.


A Simple Program – Default Constructor
class Circle
C1 Object Instance
{
private:
double radius;
public:
//Default Constructor
: C1
// No Constructor Here
Circle()
{ } radius: Any Value

double getArea()
Allocate memory
{ return radius * radius * 3.14159; } for radius
};
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
Object Construction with Arguments
 The syntax to declare an object using a constructor with
arguments is:

ClassName objectName(arguments);

 For example, the following declaration creates an object


named circle1 by invoking the Circle class’s
constructor with a specified radius 5.5.

Circle circle1(5.5);
A Simple Program – Constructor with Arguments
class Circle
C1 Object Instance
{
private:
double radius;
public: : C1
Circle( ) {}
Circle(double rad) radius: 9.0
{ radius = rad; }
double getArea()
Allocate memory
{ return radius * radius * 3.14159; } for radius
};
void main()
{
Circle C1(9.0);
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
What is Missing?
class Circle
{
private: Class must define a
double radius; no-argument
constructor too
public:
Circle(double radius) //No argument Constructor
{ this->radius = radius; } Circle() { radius = 1.0; }
double getArea( ); // Not implemented yet
};
double Circle::getArea()
{ return this->radius * radius * 3.14159; }
void main()
{
Circle C1(99.0);
cout<<“Area of circle = “<<C1.getArea();
}
Output of the Following Program?
class Circle
{
private:
double radius;

public:

Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
int main()
{
Circle C1(9.0);
cout<<“Area of circle = “<<C1.getArea();
}
Output of the Following Program?
class Circle
{
private:
double radius;

public:
Circle( ) { }

Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
int main()
{
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
Initializing
Objects Notice that default settings for the three
member variables are set in constructor
prototype. No names are needed; the
10 // Time abstract data type definition defaults are applied in the order the
11 class Time { variables are declared.
12 public:
13 Time( int = 0, int = 0, int = 0 ); // default constructor
14 void setTime( int, int, int ); // set hour, minute, second
15 void printMilitary(); // print military time format
16 void printStandard(); // print standard time format
17 private:
18 int hour; // 0 - 23
19 int minute; // 0 - 59
20 int second; // 0 - 59
21 };
22
23 #endif

Default Parameters in Constructor


70 Same constructor, used in overloaded style
71 int main()
72 {
73 Time t1, // all arguments defaulted
74 t2(2), // minute and second defaulted
75 t3(21, 34), // second defaulted
76 t4(12, 25, 42), // all values specified
77 t5(27, 74, 99); // all bad values specified
78
79 cout << "Constructed with:\n"
80 << "all arguments defaulted:\n ";
81 t1.printMilitary();
82 cout << "\n ";
83 t1.printStandard();
84
85 cout << "\nhour specified; minute and second defaulted:"
86 << "\n ";
87 t2.printMilitary();
88 cout << "\n ";
89 t2.printStandard();
90
91 cout << "\nhour and minute specified; second defaulted:"
92 << "\n ";
93 t3.printMilitary();
Constructorsrtors
• Constructor in C++ is a special method that is run automatically at the
time of object creation.
• It is used to initialize the data members of new objects generally.
• The constructor in C++ has the same name as the class.
• It constructs the values i.e. provides data for the object which is why it is
known as a constructor.
• Constructors do not return value, hence they do not have a return type.
In-line Constructors
class Demo
{
public:
Demo(){ //inline function
// Constructor
cout << "Welcome to the constructor!\n";
}
};
Out-of-line Constructors
class Demo
{
public:
Demo(); // Constructor
};
Demo::Demo() //out-of-line
{
cout << "Welcome to the constructor!\n";
}

OBJECT ORIENTED PROGRAMMING | MUHAMMAD ATIF SAEED (Associate Lecturer) | March 20, 2024
Defining the Constructor Within the Class

#include <iostream> cout << "Enter the RollNo:"; name << "\t" << fee;
using namespace std; cin >> rno; }
class student { cout << "Enter the Name:"; };
int rno; cin >> name; int main()
char name[50]; cout << "Enter the Fee:"; {
double fee; cin >> fee; student s; // constructor gets
public: } called automatically when

// constructor void display() // we create the object of


the class
student() {
s.display();
{ cout << endl << rno << "\t" <<
return 0;
Defining the Constructor outside the
Class
#include <iostream> // outside definition of constructor {
using namespace std; student::student() cout << endl << rno << "\t" <<
class student { { name << "\t" << fee;

int rno; cout << "Enter the RollNo:"; }

char name[50]; cin >> rno; // driver code

double fee; cout << "Enter the Name:"; int main()

public: cin >> name; {

// constructor declaration only cout << "Enter the Fee:"; student s;

student(); cin >> fee; s.display();

void display(); } return 0;

}; void student::display() }

OBJECT ORIENTED PROGRAMMING | MUHAMMAD ATIF SAEED (Associate Lecturer) | March 20, 2024
What Constructors Do
• Help in initializing class data members
• Employee( ) { id = 0; }

• Allocate memory for dynamic members


• Employee() {
• char* nameptr = new char[20];
• }

• Allocate any needed resources

SLIDE 09
• Such as to open files, etc.
Types of Constructor in C++

• Constructors can be classified based on in which situations they


are being used. There are 4 types of constructors in C++:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Move Constructor
Default Constructor

• A default constructor is a constructor that doesn’t take any


argument. It has no parameters. It is also called a zero-argument
constructor.
class construct { b = 20; // when the object is created
public: } construct c;
int a, b; }; cout << "a: " << c.a << endl <<
// Default Constructor int main() "b: " << c.b;

construct() { return 1;

{ // Default constructor called }

a = 10; automatically
Parameterized Constructor

• Parameterized Constructors make it possible to pass arguments to


constructors.
• Typically, these arguments help initialize an object when it is
created.
• To create a parameterized constructor, simply add parameters to it
the way you would to any other function.

SLIDE 12
• When you define the constructor’s body, use the parameters to
initialize the object.
Parameterized Constructor
class GFG { {
private: GFG obj1; // will not throw error
int data; GFG obj2(25);
public: cout << "First Object Data: " <<
// parameterized constructor with default obj1.getData() << endl;
values cout << "Second Object Data: " <<
GFG(int x = 0) { data = x; } obj2.getData()

int getData() { return data; } << endl;

}; return 0;

int main() }
Copy Constructor

• A copy constructor is a member function that initializes an object


using another object of the same class.
• In simple terms, a constructor which creates an object by
initializing it with an object of the same class, which has been
created previously is known as a copy constructor.

SLIDE 14
Copy Constructor
class Sample { Sample obj1(10);
int id; obj1.display();
public: cout << endl;
// parameterized constructor // creating an object of type Sample
Sample(int x) { id = x; } from the obj

void display() { cout << "ID=" << id; } Sample obj2(obj1); // or obj2=obj1;

}; obj2.display();

SLIDE 15
int main() return 0;

{ }
When Constructors and Destructors Are Called

Constructors and destructors called automatically


• Global scope objects
• Constructors called before any other function (including main)
• Destructors called when main terminates (or exit function called)

• Local scope objects


• Constructors called when objects are defined
• Destructors called when objects leave scope
Practice Question
Write a C++ program to calculate the total salary of an employee using Classes:
You must use the following formula to calculate the total salary of an employee:
Basic + HRA + TrasportAllowance + FBPAllowance + Bonus - ProvidentFund - Income Tax – Insurance
You have to declare a class named as Employee Create data member according to total salary of an employee Create a function
to initialize variables according to total salary of an employee.
You have to calculate total salary of an employee using function named as TotalSalary.
You must create three objects and initialize different data members accordingly.
For first object take the data member values as 7000.5, 1000.5,300.5,40.5,05.5, 06.5,07.5,08.5
For second object take the data member values as 6000.5, 0900.5,200.5,40.5,05.5, 06.5,07.5,08.5
For third object take the data member values as 5000.5, 0800.5,100.5,40.5,05.5, 06.5,07.5,08.5 Find the output of 3 different
employees' salary by access the member function YOUR OUTPUT SHOULD BE AS FOLLOWS Salary of employee 1:
8325 Salary of employee 2: 7125 Salary of employee 3: 5925
You have also need to show the maximum and average salary.
Practice Question
Create a class called Passenger that represents passengers of an airline company.
A passenger has the following attributes: passenger id (int), name (string), address
(string), telephone (string), date of birth (object of the class Date that will need to be
created.
A date is identified by three integers that represent the day, month, and year) The class
should have at least the following member functions:
• One or more constructors
• Necessary getters and setters

SLIDE 17
• A print function that prints information about a passenger
• A destructor

You might also like