Introduction To Classes
Introduction To Classes
Muhammad Zulqarnain
• 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
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>
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
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);
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
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
}; 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; }
SLIDE 09
• Such as to open files, etc.
Types of Constructor in C++
construct() { return 1;
a = 10; automatically
Parameterized Constructor
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()
}; return 0;
int main() }
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
SLIDE 17
• A print function that prints information about a passenger
• A destructor