5-Introduction to Classes-1
5-Introduction to Classes-1
(COMP-112)
ClassName objectName;
public: : C1
Circle()
radius: 5.0
{ radius = 5.0; }
double getArea( )
{ return radius * radius * 3.14159; } Allocate memory
}; for radius
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea( );
}
Local Classes
• Local classes: A local class is declared within a function
definition.
• Out-of-line functions:
• are declared within the body of the class
definition and defined outside.
Inline/Out-of-Line Member
Functions
returnType ClassName::MemberFunctionName( ){
…
}
Member Functions
Separating Declaration from Implementation
class Circle
{
private: Class must define a
double radius; no-argument
public: constructor too….
Circle(double radius)
{ this->radius = radius; }
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
• 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
Data Hiding - Data Field 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.
public: : C1
Circle()
radius: 5.0
{ radius = 5.0; }
double getArea()
{ return radius * radius * 3.14159; } Allocate memory
}; for radius
void main()
{
Circle C1;
//C1.radius = 10; can’t access private member outside the class
cout<<“Area of circle = “<<C1.getArea();
}
A Simple Program – Default Constructor
class Circle
{ C1 Object Instance
private:
double radius;
public:
//Default Constructor : C1
Circle()
//
{ No Constructor
} Here
radius: Any Value
double getArea()
{ return radius * radius * 3.14159; } Allocate memory
}; 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:
Circle( ) {} : C1
Circle(double rad)
radius: 9.0
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; } Allocate memory
}; 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();
}
Output of the following Program?
class Circle
{
private:
double radius;
public:
Circle( ) { }
Circle(double rad)
{ radius = rad; }
double getArea()
{ return radius * radius * 3.14159; }
};
void main()
{
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
const Member Functions
• const Member Functions: Read-only functions cannot
modify object’s data members
Constant Functions
class Circle
{
private:
double radius;
public:
Circle ()
{ radius = 1; }
Circle(double rad)
{ radius = rad; } const member
double getArea() const function cannot
{ return radius * radius * 3.14159; } update/change
}; object’s data
void main()
{
Circle C2(8.0);
Circle C1;
cout<<“Area of circle = “<<C1.getArea();
}
Accessors and Mutators(Getters &
Setters)
• Accessors: member function only reads/gets value
from a class’s member variable but does not change it.
• Mutators: member function that stores a value in
member variable
const Objects
• const Object: Read-only objects
• Header files
• Contains class definitions and function prototypes
• Source-code files
• Contains member function definitions
1 // Fig. 6.5: time1.h
2 // Declaration of the Time class.
3 // Member functions are defined in time1.cpp
Objects
10 // Time abstract data type definition
11 class Time {
defaults are applied in the order the
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
• Destructors
• Are member function of class
• Perform termination housekeeping before the system reclaims the object’s
memory
• Name is tilde (~) followed by the class name (i.e., ~Time)
• Receives no parameters, returns no value
• One destructor per class (no overloading)
• Destructors cannot be declared const, static
• A destructor can be declared virtual or pure virtual
Destructors
When Constructors and Destructors Are Called
Constructors and destructors called automatically
• Order depends on scope of objects
1. Global scope objects
• Constructors called before any other function (including main)
• Destructors called when main terminates (or exit function
called)
• Destructors not called if program terminates with abort
Date *dates[31];
Date::Date(Date &date)
{
// no need to check passed date arg
month = date.month;
day = date.day;
year = date.year;
}
Uses of the Copy Constructor
• Implicitly called in 3 situations:
1. defining a new object from an existing object
2. passing an object by value
3. returning an object by value
Copy Constructor: Defining a New Object
Date d1(02,28,2020);
• static Variables
• Default Initialization: 0 or Null (for pointers)
• Initialization: user defined value
• Initialization is made just once, at compile time.
• Accessibility: Private or Public
Public static Class Variables
• Can be accessed using Class name:
cout<<Employee::count;
• Static functions:
• Can access: static data and static
functions
• Cannot access: non-static data, non-
static functions, and this pointer
Public static Class Functions
•Can be invoked using class’s any
object:
cout<<e1.getCount();
5
6 class Employee {
7 public:
8 Employee( const char*, const char* ); // constructor
9 ~Employee(); // destructor
10 const char *getFirstName() const; // return first name
11 const char *getLastName() const; // return last name
12
13 // static member function
14 static int getCount(); // return # objects instantiated
15
16 private:
static member function and
variable declared.
17 char *firstName;
18 char *lastName;
19
20 // static data member
21 static int count; // number of objects instantiated
22 };
23
25 // Fig. 7.9: employ1.cpp
26 // Member function definitions for class Employee
27 #include <iostream>
28
29 using std::cout;
30 using std::endl; static data member count and
31 function getCount( ) initialized at
32 #include <cstring> file scope (required).
33 #include <cassert>
34 #include "employ1.h"
35
36 // Initialize the static data member
37 int Employee::count = 0;
38
39 // Define the static member function that
40 // returns the number of employee objects instantiated.
41 int Employee::getCount() { return count; } Note the use of
42 assert to test for
43 // Constructor dynamically allocates space for the
memory allocation.
44 // first and last name and uses strcpy to copy
45 // the first and last names into the object
46 Employee::Employee( const char *first, const char *last )
47 {
48 firstName = new char[ strlen( first ) + 1 ];
49 assert( firstName != 0 ); // ensure memory allocated
50 strcpy( firstName, first ); static data member
51 count changed when a
52 lastName = new char[ strlen( last ) + 1 ];
53 assert( lastName != 0 ); // ensure memory allocated
constructor/destructor
54 strcpy( lastName, last ); called.
55
56 ++count; // increment static count of employees
57 cout << "Employee constructor for " << firstName
58 << ' ' << lastName << " called." << endl;
59 }
60
61 // Destructor deallocates dynamically allocated memory
62 Employee::~Employee() static data member count
63 { changed when a
64 cout << "~Employee() called for " << firstName constructor/destructor called.
65 << ' ' << lastName << endl;
66 delete [] firstName; // recapture memory
67 delete [] lastName; // recapture memory Count decremented
68 --count; // decrement static count of employees
because of
69 } destructor calls from
70 delete.
71 // Return first name of employee
72 const char *Employee::getFirstName() const
73 {
74 // Const before return type prevents client from modifying
75 // private data. Client should copy returned string before
76 // destructor deletes storage to prevent undefined pointer.
77 return firstName;
78 }
79
80 // Return last name of employee
81 const char *Employee::getLastName() const
82 {
83 // Const before return type prevents client from modifying
84 // private data. Client should copy returned string before
85 // destructor deletes storage to prevent undefined pointer.
86 return lastName;
87 }
88 // Fig. 7.9: fig07_09.cpp
89 // Driver to test the employee class
90 #include <iostream> If no Employee objects exist
91 count incremented because of getCount must be accessed
92 using std::cout; constructor calls from new. using the class name and (::).
93 using std::endl;
94
95 #include "employ1.h"
96 Number of employees before instantiation is 0
97 int main()
98 {
99 cout << "Number of employees before instantiation is "
100 << Employee::getCount() << endl; // use class name
e2Ptr->getCount() or Employee::getCount() would
101 also work.
102 Employee *e1Ptr = new Employee( "Susan", "Baker" );
103 Employee *e2Ptr = new Employee( "Robert", "Jones" );
104 Number of employees after instantiation is 2
105 cout << "Number of employees after instantiation is "
106 << e1Ptr->getCount();
107 Employee constructor for Susan Baker called.
108 cout << "\n\nEmployee 1: " Employee constructor for Robert Jones called.
109 << e1Ptr->getFirstName()
110 << " " << e1Ptr->getLastName() Employee 1: Susan Baker
111 << "\nEmployee 2: " Employee 2: Robert Jones
112 << e2Ptr->getFirstName()
113 << " " << e2Ptr->getLastName() << "\n\n";
114
115 delete e1Ptr; // recapture memory ~Employee() called for Susan Baker
116 e1Ptr = 0; ~Employee() called for Robert Jones
117 delete e2Ptr; // recapture memory
118 e2Ptr = 0;
119
122
123 return 0;
count back to zero.
124 }
128
129 return 0;
130 }
• HR Manager
• Head of Department
• Print spooler
• Window Managers
• Digital Filters
• Accounting Systems
•…
Design Solution
• Defines a getInstance( ) operation that lets clients access
its unique instance
• Responsible for creating its own unique instance
Singleton
-static uniqueinstance
Singleton data
… -Singleton()
return uniqueinstance; +static getInstance()
Singleton methods…
Implementation
• Declare all of class’s constructors private
• prevent other classes from directly creating an instance of this
class
return DB;
}
...
};
Database* Database::DB=NULL;
Singleton Consequences