SlideShare a Scribd company logo
1 of 14
class Increment
{
public:
Increment( int c = 0, int i = 1 ); // default constructor
// function addIncrement definition
void addIncrement()
{
count += increment;
} // end function addIncrement
void print() const; // prints count and increment
private:
int count;
const int increment; // const data member
}; // end class Increment
Class ‘Increment’
Increment::Increment( int c, int i )
{
count = c; // allowed because count is not constant
increment = i; // ERROR: Cannot modify a const object
} // end constructor Increment
‘const’ Data Member
Initializer
Increment::Increment( int c, int i )
: count( c ), // initializer for non-const member
increment( i ) // required initializer for const member
{
// empty body
} // end constructor Increment
class Time
{
public:
Time( int = 0, int = 0, int = 0 ); // default constructor
// set functions
void setTime( int, int, int ); // set time
void setHour( int ); // set hour
void setMinute( int ); // set minute
void setSecond( int ); // set second
// get functions (normally declared const)
int getHour() const; // return hour
int getMinute() const; // return minute
int getSecond() const; // return second
// print functions (normally declared const)
void printUniversal() const; // print universal time
void printStandard(); // print standard time (should be const)
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}; // end class Time
Class Time
class Time
{
public:
Time( int = 0, int = 0, int = 0 ); // default constructor
// set functions
void setTime( int, int, int ); // set time
void setHour( int ); // set hour
void setMinute( int ); // set minute
void setSecond( int ); // set second
// get functions (normally declared const)
int getHour() const; // return hour
int getMinute() const; // return minute
int getSecond() const; // return second
Class Time
int main()
{
Time wakeUp( 6, 45, 0 ); // non-constant object
const Time noon( 12, 0, 0 ); // constant object
// OBJECT MEMBER FUNCTION
wakeUp.setHour( 18 ); // non-const non-const
noon.setHour( 12 ); // const non-const
wakeUp.getHour(); // non-const const
noon.getMinute(); // const const
noon.printUniversal(); // const const
noon.printStandard(); // const non-const
return 0;
} // end main
Functions for ‘const’ Objects
#include "Date.h" // include Date class definition
class Employee
{
public:
Employee( const char * const, const char * const,
const Date &, const Date & );
void print() const;
~Employee(); // provided to confirm destruction order
private:
char firstName[ 25 ];
char lastName[ 25 ];
const Date birthDate; // composition: member object
const Date hireDate; // composition: member object
}; // end class Employee
#endif
Class Employee
Employee::Employee( const char * const first, const char * const last,
const Date &dateOfBirth, const Date &dateOfHire )
: birthDate( dateOfBirth ), // initialize birthDate
hireDate( dateOfHire ) // initialize hireDate
{
// copy first into firstName and be sure that it fits
int length = strlen( first );
length = ( length < 25 ? length : 24 );
strncpy( firstName, first, length );
firstName[ length ] = '0';
// copy last into lastName and be sure that it fits
length = strlen( last );
length = ( length < 25 ? length : 24 );
strncpy( lastName, last, length );
lastName[ length ] = '0';
// output Employee object to show when constructor is called
cout << "Employee object constructor: "
<< firstName << ' ' << lastName << endl;
} // end Employee constructor
‘const’ Objects in Composition
// Count class definition
class Count
{
friend void setX( Count &, int ); // friend declaration
public:
// constructor
Count()
: x( 0 ) // initialize x to 0
{
// empty body
} // end constructor Count
// output x
void print() const
{
cout << x << endl;
} // end function print
private:
int x; // data member
}; // end class Count
Class Count
void setX( Count &c, int val )
{
c.x = val; // allowed because setX is a friend of Count
} // end function setX
int main()
{
Count counter; // create Count object
cout << "counter.x after instantiation: ";
counter.print();
setX( counter, 8 ); // set x using a friend function
cout << "counter.x after call to setX friend function: ";
counter.print();
return 0;
} // end main
‘friend’ Function
Today’s Topics
 ‘this’ Pointer
 Dynamic Memory Allocation
‘this’ Pointer
class Test
{
public:
Test( int = 0 ); // default constructor
void print() const;
private:
int x;
}; // end class Test
// constructor
Test::Test( int value )
: x( value ) // initialize x to value
{
// empty body
} // end constructor Test
// print x using implicit and explicit this pointers;
// the parentheses around *this are required
‘this’ Pointer
void Test::print() const
{
// implicitly use the this pointer to access the member x
cout << " x = " << x;
// explicitly use the this pointer and the arrow operator
// to access the member x
cout << "n this->x = " << this->x;
// explicitly use the dereferenced this pointer and
// the dot operator to access the member x
cout << "n(*this).x = " << ( *this ).x << endl;
} // end function print
int main()
{
Test testObject( 12 ); // instantiate and initialize testObject
testObject.print();
return 0;
} // end main
Time.h
class Time
{
public:
Time( int = 0, int = 0, int = 0 ); // default constructor
// set functions (the Time & return types enable cascading)
Time &setTime( int, int, int ); // set hour, minute, second
Time &setHour( int ); // set hour
Time &setMinute( int ); // set minute
Time &setSecond( int ); // set second
// get functions (normally declared const)
int getHour() const; // return hour
int getMinute() const; // return minute
int getSecond() const; // return second
// print functions (normally declared const)
void printUniversal() const; // print universal time
void printStandard() const; // print standard time
private:
Cascaded Function calls
void main()
{
Time t; // create Time object
// cascaded function calls
t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
// output time in universal and standard formats
cout << "Universal time: ";
t.printUniversal();
cout << "nStandard time: ";
t.printStandard();
cout << "nnNew standard time: ";
// cascaded function calls
t.setTime( 20, 20, 20 ).printStandard();
} // end main

More Related Content

What's hot

JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
Yasuharu Nakano
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 

What's hot (20)

Day 1
Day 1Day 1
Day 1
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
AnyObject – 自分が見落としていた、基本の話
AnyObject – 自分が見落としていた、基本の話AnyObject – 自分が見落としていた、基本の話
AnyObject – 自分が見落としていた、基本の話
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Jest
JestJest
Jest
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Oop lab report
Oop lab reportOop lab report
Oop lab report
 

Similar to Class ‘increment’

Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdf
aaseletronics2013
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
Sidd Singh
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
Deepak Singh
 
#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf
annucommunication1
 

Similar to Class ‘increment’ (20)

Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdf
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
w10 (1).ppt
w10 (1).pptw10 (1).ppt
w10 (1).ppt
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Constructor
ConstructorConstructor
Constructor
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
Functional C++
Functional C++Functional C++
Functional C++
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
constructors
constructorsconstructors
constructors
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
 
COW
COWCOW
COW
 
#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf
 

More from Syed Zaid Irshad

Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Recently uploaded (20)

Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

Class ‘increment’

  • 1. class Increment { public: Increment( int c = 0, int i = 1 ); // default constructor // function addIncrement definition void addIncrement() { count += increment; } // end function addIncrement void print() const; // prints count and increment private: int count; const int increment; // const data member }; // end class Increment Class ‘Increment’
  • 2. Increment::Increment( int c, int i ) { count = c; // allowed because count is not constant increment = i; // ERROR: Cannot modify a const object } // end constructor Increment ‘const’ Data Member Initializer Increment::Increment( int c, int i ) : count( c ), // initializer for non-const member increment( i ) // required initializer for const member { // empty body } // end constructor Increment
  • 3. class Time { public: Time( int = 0, int = 0, int = 0 ); // default constructor // set functions void setTime( int, int, int ); // set time void setHour( int ); // set hour void setMinute( int ); // set minute void setSecond( int ); // set second // get functions (normally declared const) int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second // print functions (normally declared const) void printUniversal() const; // print universal time void printStandard(); // print standard time (should be const) private: int hour; // 0 - 23 (24-hour clock format) int minute; // 0 - 59 int second; // 0 - 59 }; // end class Time Class Time
  • 4. class Time { public: Time( int = 0, int = 0, int = 0 ); // default constructor // set functions void setTime( int, int, int ); // set time void setHour( int ); // set hour void setMinute( int ); // set minute void setSecond( int ); // set second // get functions (normally declared const) int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second Class Time
  • 5. int main() { Time wakeUp( 6, 45, 0 ); // non-constant object const Time noon( 12, 0, 0 ); // constant object // OBJECT MEMBER FUNCTION wakeUp.setHour( 18 ); // non-const non-const noon.setHour( 12 ); // const non-const wakeUp.getHour(); // non-const const noon.getMinute(); // const const noon.printUniversal(); // const const noon.printStandard(); // const non-const return 0; } // end main Functions for ‘const’ Objects
  • 6. #include "Date.h" // include Date class definition class Employee { public: Employee( const char * const, const char * const, const Date &, const Date & ); void print() const; ~Employee(); // provided to confirm destruction order private: char firstName[ 25 ]; char lastName[ 25 ]; const Date birthDate; // composition: member object const Date hireDate; // composition: member object }; // end class Employee #endif Class Employee
  • 7. Employee::Employee( const char * const first, const char * const last, const Date &dateOfBirth, const Date &dateOfHire ) : birthDate( dateOfBirth ), // initialize birthDate hireDate( dateOfHire ) // initialize hireDate { // copy first into firstName and be sure that it fits int length = strlen( first ); length = ( length < 25 ? length : 24 ); strncpy( firstName, first, length ); firstName[ length ] = '0'; // copy last into lastName and be sure that it fits length = strlen( last ); length = ( length < 25 ? length : 24 ); strncpy( lastName, last, length ); lastName[ length ] = '0'; // output Employee object to show when constructor is called cout << "Employee object constructor: " << firstName << ' ' << lastName << endl; } // end Employee constructor ‘const’ Objects in Composition
  • 8. // Count class definition class Count { friend void setX( Count &, int ); // friend declaration public: // constructor Count() : x( 0 ) // initialize x to 0 { // empty body } // end constructor Count // output x void print() const { cout << x << endl; } // end function print private: int x; // data member }; // end class Count Class Count
  • 9. void setX( Count &c, int val ) { c.x = val; // allowed because setX is a friend of Count } // end function setX int main() { Count counter; // create Count object cout << "counter.x after instantiation: "; counter.print(); setX( counter, 8 ); // set x using a friend function cout << "counter.x after call to setX friend function: "; counter.print(); return 0; } // end main ‘friend’ Function
  • 10. Today’s Topics  ‘this’ Pointer  Dynamic Memory Allocation
  • 11. ‘this’ Pointer class Test { public: Test( int = 0 ); // default constructor void print() const; private: int x; }; // end class Test // constructor Test::Test( int value ) : x( value ) // initialize x to value { // empty body } // end constructor Test // print x using implicit and explicit this pointers; // the parentheses around *this are required
  • 12. ‘this’ Pointer void Test::print() const { // implicitly use the this pointer to access the member x cout << " x = " << x; // explicitly use the this pointer and the arrow operator // to access the member x cout << "n this->x = " << this->x; // explicitly use the dereferenced this pointer and // the dot operator to access the member x cout << "n(*this).x = " << ( *this ).x << endl; } // end function print int main() { Test testObject( 12 ); // instantiate and initialize testObject testObject.print(); return 0; } // end main
  • 13. Time.h class Time { public: Time( int = 0, int = 0, int = 0 ); // default constructor // set functions (the Time & return types enable cascading) Time &setTime( int, int, int ); // set hour, minute, second Time &setHour( int ); // set hour Time &setMinute( int ); // set minute Time &setSecond( int ); // set second // get functions (normally declared const) int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second // print functions (normally declared const) void printUniversal() const; // print universal time void printStandard() const; // print standard time private:
  • 14. Cascaded Function calls void main() { Time t; // create Time object // cascaded function calls t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); // output time in universal and standard formats cout << "Universal time: "; t.printUniversal(); cout << "nStandard time: "; t.printStandard(); cout << "nnNew standard time: "; // cascaded function calls t.setTime( 20, 20, 20 ).printStandard(); } // end main