1. The document discusses separating a class interface from its implementation by defining the class in a header file and defining member functions in a source code file.
2. It shows a Time class defined in the time1.h header file and member functions defined in the time1.cpp source file.
3. A driver program includes the header file, creates a Time object, and calls member functions to demonstrate the separation of interface and implementation.
1. The document discusses separating a class interface from its implementation by defining the class in a header file and defining member functions in a source code file.
2. It shows a Time class defined in the time1.h header file and its member functions defined in the time1.cpp source file.
3. A driver program includes the header file, creates a Time object, and calls member functions to demonstrate separating interface and implementation works as expected.
The document describes object-oriented programming concepts like classes, objects, encapsulation, and properties. It provides code examples of a Time class that encapsulates time data and provides methods to work with it. The Time class uses properties to safely access private member variables for hour, minute and second. Constructors are demonstrated that initialize Time objects with different parameters.
This document summarizes Chapter 17 of a C++ textbook, which covers advanced class concepts in C++. The chapter discusses:
1. Constant objects and constant member functions that cannot modify objects.
2. Composition, where classes can contain objects of other classes as members. Member objects are constructed before the enclosing object.
3. Friend functions and classes that have access to private and protected members of other classes.
4. Using the 'this' pointer to access members from within member functions.
5. Dynamic memory allocation using operators new and delete.
6. Static class members that are shared among all class objects.
7. Data abstraction and information hiding techniques using classes.
C++ppt. Classs and object, class and objectsecondakay
1. Classes are blueprints that define objects with attributes (data members) and behaviors (member functions). Objects are instantiated from classes.
2. The Time class implements a time abstract data type with data members for hours, minutes, seconds and member functions to set time and print time in different formats.
3. Classes allow for encapsulation of data and functions, information hiding of implementation details, and software reusability through class libraries.
This document provides an overview of classes in C++. It begins with definitions and concepts related to classes, such as encapsulation and user-defined types. It then provides examples of declaring and defining a simple Time class with attributes like hours, minutes, seconds and methods to set, get, print and change the time. The document also discusses class members, access specifiers, constructors, pointers and references to class objects, and getter and setter methods. It concludes with brief mentions of utility functions, separating interface from implementation, and organizing classes across header and source files.
The document discusses friend functions and classes, which can access private and protected members of another class. It provides examples of declaring friend functions and classes, and demonstrates how friend functions can modify private variables, while non-friend functions cannot. The document also covers static class members, which are shared by all objects of a class, and proxy classes, which hide the implementation of another class through a public interface.
Data Structure & Algorithm - Self Referentialbabuk110
The document discusses structures in C programming. It defines a structure as a collection of logically related data items of different datatypes grouped together under a single name. Some key points discussed include:
- Structures allow user-defined datatypes that can group different data types together.
- Structures are defined using the struct keyword followed by the structure name and members.
- Structure variables are declared to use the structure datatype. Arrays of structures can also be defined.
- Members of a structure can be accessed using the dot (.) operator or arrow (->) operator for pointers to structures.
The document provides examples of defining, declaring, and accessing structure variables and members.
The document discusses functions and function components in C++. It introduces key concepts such as:
- Functions allow programmers to divide programs into modular and reusable pieces.
- Functions are defined once and can be called multiple times from different parts of a program. They take in parameters and return values.
- The standard library provides many commonly used functions for tasks like math operations.
- Functions can be used to encapsulate and reuse code through prototypes and definitions.
- Enumerations allow defining a set of integer constants with unique names for use as variable types.
- Storage classes like static and auto determine where variables are stored in memory and their scope within a program.
This lecture covers overloaded functions, constant objects and member functions, friend functions, the this pointer, static data members, and composition with objects as members of classes. Specifically, it discusses:
1) Overloading constructors to initialize objects with different values.
2) Using const to declare objects, member functions, and data members as constant to prevent modification.
3) Defining member functions outside the class and using the scope resolution operator.
4) Passing objects as arguments to other functions and returning objects.
5) Using the this pointer implicitly and explicitly to access members of the current object.
6) Declaring static data members that are shared across all objects of a class.
Modify the Time classattached to be able to work with Date.pdfaaseletronics2013
Modify the Time class(attached) to be able to work with Date class. The Time object should
always remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to increase day, month and year when it is proper. Please use CISP400V10A4.cpp that
tests the tick member function in a loop that prints the time in standard format during iteration of
the loop to illustrate that the tick member function works correctly. Be aware that we are testing
the following cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
You can adjust only programs (Date.cpp, Date.h, Time.cpp and Time.h) to generate the
required result but not the code in CISP400V10A4.cpp file.
Expecting results:
// Date.cpp
// Date class member-function definitions.
#include <array>
#include <string>
#include <iostream>
#include <stdexcept>
#include "Date.h" // include Date class definition
using namespace std;
// constructor confirms proper value for month; calls
// utility function checkDay to confirm proper value for day
Date::Date(int mn, int dy, int yr, Time time)
: time01(time)
{
if (mn > 0 && mn <= monthsPerYear) // validate the month
month = mn;
else
throw invalid_argument("month must be 1-12");
year = yr; // could validate yr
day = checkDay(dy); // validate the day
// output Date object to show when its constructor is called
cout << "Date object constructor for date ";
print();
cout << endl;
} // end Date constructor
// print Date object in form month/day/year
void Date::print() const
{
cout << month << '/' << day << '/' << year;
cout << "t";
time01.printStandard();
cout << "t";
time01.printUniversal();
cout << "n";
} // end function print
// output Date object to show when its destructor is called
Date::~Date()
{
cout << "Date object destructor for date ";
print();
cout << endl;
} // end ~Date destructor
// utility function to confirm proper day value based on
// month and year; handles leap years, too
unsigned int Date::checkDay(int testDay) const
{
static const array< int, monthsPerYear + 1 > daysPerMonth =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// determine whether testDay is valid for specified month
if (testDay > 0 && testDay <= daysPerMonth[month])
{
return testDay;
} // end if
// February 29 check for leap year
if (month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year
% 100 != 0)))
{
return testDay;
} // end if
cout << "day (" << testDay << ") set to 1." << endl;
return 1;
} // end function checkDay
// adjust data if day is not proper
void Date::increaseADay()
{
day = checkDay(day + 1);
if (day == 1) // if day wasn't accurate, its value is one
{
month = month + 1; // increase month by 1
if (month > 0 && month >= monthsPerYear) // if.
The document discusses class and objects, function and operator overloading in C++. It covers topics like class declaration, class functions defined inside and outside the class, constructors, destructors, function overloading, operator overloading etc. Examples are provided for default constructor, parameterized constructor, copy constructor, function overloading using addition operator, pre-increment and pre-decrement operators. It also discusses memory allocation for objects, passing parameters by value and reference to functions.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
C++ Please I am posting the fifth time and hoping to get th.pdfjaipur2
C++
"Please I am posting the fifth time and hoping to get this resolved. I want the year to
change from 2014 to 2015 but the days of the month change to 32 rather than 1/1/2015.
Also, Please I want personal information in the heading as well Name: Last: and Course
Name:"
Modify the Time class(attached) to be able to work with Date class. The Time object should
always
remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to
increase day, month and year when it is proper. Please use CISP400V10A4.cpp that tests the tick
member function in a loop that prints the time in standard format during iteration of the loop to
illustrate that the tick member function works correctly. Be aware that we are testing the following
cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
Time class
The Time class has three private integer data members, hour (0 - 23 (24-hour clock format)),
minute (0
59), and second (0 59).
It also has Time, setTime, setHour, setMinute, setSecond, getHour(), getMinute,
getSecond,~Time,
printUniversal, and printStandard public functions.
1. The Time function is a default constructor. It takes three integers and they all have 0 as default
values. It also displays "Time object constructor is called." message and calls
printStandard
and printUniversal functions.
2. The setTime function takes three integers but does not return any value. It initializes the
private data members (hour, minute and second) data.
3. The setHour function takes one integer but doesnt return anything. It validates and stores the
integer to the hour private data member.
4. The setMinute function takes one integer but doesnt return anything. It validates and stores
the integer to the minute private data member.
5. The setSecond function takes one integer but doesnt return anything. It validates and stores
the integer to the second private data member.
Page 3 of 11 CISP400V10A4
6. The getHour constant function returns one integer but doesnt take anything. It returns the
private data member hours data.
7. The getMinute constant function returns one integer but doesnt take anything. It returns the
private data member minutes data.
8. The getSecond constant function returns one integer but doesnt take anything. It returns the
private data member seconds data.
9. The Time destructor does not take anything. It displays "Time object destructor is
called."
message and calls printStandard and printUniversal functions.
10. The printUniversal constant function does not return or accept anything. It displays time in
universal-time format.
11. The printStandard constant function does not return or accept anything. It displays time in
standard-ti.
Please I am posting the fifth time and hoping to get this r.pdfankit11134
"Please I am posting the fifth time and hoping to get this resolved. I want the year to
change from 2014 to 2015 but the days of the month change to 32 rather than 1/1/2015.
Also, Please I want personal information in the heading as well Name: Last: and Course
Name:"
Modify the Time class(attached) to be able to work with Date class. The Time object should
always
remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to
increase day, month and year when it is proper. Please use CISP400V10A4.cpp that tests the tick
member function in a loop that prints the time in standard format during iteration of the loop to
illustrate that the tick member function works correctly. Be aware that we are testing the following
cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
Time class
The Time class has three private integer data members, hour (0 - 23 (24-hour clock format)),
minute (0
59), and second (0 59).
It also has Time, setTime, setHour, setMinute, setSecond, getHour(), getMinute,
getSecond,~Time,
printUniversal, and printStandard public functions.
1. The Time function is a default constructor. It takes three integers and they all have 0 as default
values. It also displays "Time object constructor is called." message and calls
printStandard
and printUniversal functions.
2. The setTime function takes three integers but does not return any value. It initializes the
private data members (hour, minute and second) data.
3. The setHour function takes one integer but doesnt return anything. It validates and stores the
integer to the hour private data member.
4. The setMinute function takes one integer but doesnt return anything. It validates and stores
the integer to the minute private data member.
5. The setSecond function takes one integer but doesnt return anything. It validates and stores
the integer to the second private data member.
Page 3 of 11 CISP400V10A4
6. The getHour constant function returns one integer but doesnt take anything. It returns the
private data member hours data.
7. The getMinute constant function returns one integer but doesnt take anything. It returns the
private data member minutes data.
8. The getSecond constant function returns one integer but doesnt take anything. It returns the
private data member seconds data.
9. The Time destructor does not take anything. It displays "Time object destructor is
called."
message and calls printStandard and printUniversal functions.
10. The printUniversal constant function does not return or accept anything. It displays time in
universal-time format.
11. The printStandard constant function does not return or accept anything. It displays time in
standard-time f.
Object oriented programming originated with the Simula programming languages of the 1960s. It has since become an important paradigm in computer science. The key concepts of object oriented programming include classes and objects, encapsulation, inheritance and polymorphism. An object encapsulates state (attributes) and behavior (methods) and communicates with other objects via message passing. Classes define types of objects and can be arranged in a hierarchy using inheritance where subclasses inherit attributes and methods from parent classes. Polymorphism allows objects to have multiple identities based on their class, allowing them to be used in different ways. These concepts provide benefits like modularity, code reuse and ability to model real-world problems.
1. A class defines a new user-defined type by encapsulating data members and member functions. Data members store the attributes of an object, while member functions implement the behaviors.
2. An object is an instance of a class that allocates memory for the class's data members. Objects are declared by specifying the class name followed by an identifier. Member functions manipulate the data members of an object using dot or arrow operators.
3. A class's data members and member functions can be accessed privately, publicly, or protected. Constructors initialize new objects by setting initial values for data members. Destructors release resources when objects are destroyed.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping related data members and functions together, and objects are instantiated from classes. Some key aspects of OOP include:
1. Encapsulation which involves hiding implementation details within classes and exposing a public interface.
2. Inheritance which allows a derived class to extend a base class while retaining shared properties.
3. Dynamic binding which enables polymorphic behavior where derived classes can exhibit different behavior than base classes in the same context.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping the data (attributes) and functions (methods) that operate on that data. In C++, classes use access specifiers like public and private to control whether data and methods can be accessed from outside the class or only within the class. Methods are defined either inside or outside the class using the scope resolution operator. Objects are instantiated from classes and their methods and data can be accessed using dot or arrow operators.
This document discusses iOS app design and provides examples of using timers, UIViews, and NSMutableArrays. It covers:
- Using timers (NSTimer) for time-based tasks like clocks and stopwatches, and discusses timer accuracy.
- Common operations on UIView objects like tags and UISegmentedControl.
- Storing and accessing data in NSMutableArrays, as in a numbers game.
It then provides code samples for a basic timer, specifying individual timer objects, and accurately measuring elapsed time between points. Overall the document provides an overview and examples of fundamental iOS app components.
Coding - L30-L31-Array of structures.pptxhappycocoman
The document discusses different concepts related to structures in C programming:
1. It explains how to define arrays of structures to store data of multiple types for each array element. Examples of initializing and accessing elements of an array of structures are provided.
2. Pointers to structures are introduced, showing how to declare pointer variables and access members of a structure using pointer notation with the arrow operator.
3. Benefits and drawbacks of using pointers are summarized.
4. A problem on creating a menu-driven book store management program using a structure to store book details is presented.
Construction Materials (Paints) in Civil EngineeringLavish Kashyap
This file will provide you information about various types of Paints in Civil Engineering field under Construction Materials.
It will be very useful for all Civil Engineering students who wants to search about various Construction Materials used in Civil Engineering field.
Paint is a vital construction material used for protecting surfaces and enhancing the aesthetic appeal of buildings and structures. It consists of several components, including pigments (for color), binders (to hold the pigment together), solvents or thinners (to adjust viscosity), and additives (to improve properties like durability and drying time).
Paint is one of the material used in Civil Engineering field. It is especially used in final stages of construction project.
Paint plays a dual role in construction: it protects building materials and contributes to the overall appearance and ambiance of a space.
Ad
More Related Content
Similar to lecture10 introduction to Classes and Objects.ppt (20)
The document discusses friend functions and classes, which can access private and protected members of another class. It provides examples of declaring friend functions and classes, and demonstrates how friend functions can modify private variables, while non-friend functions cannot. The document also covers static class members, which are shared by all objects of a class, and proxy classes, which hide the implementation of another class through a public interface.
Data Structure & Algorithm - Self Referentialbabuk110
The document discusses structures in C programming. It defines a structure as a collection of logically related data items of different datatypes grouped together under a single name. Some key points discussed include:
- Structures allow user-defined datatypes that can group different data types together.
- Structures are defined using the struct keyword followed by the structure name and members.
- Structure variables are declared to use the structure datatype. Arrays of structures can also be defined.
- Members of a structure can be accessed using the dot (.) operator or arrow (->) operator for pointers to structures.
The document provides examples of defining, declaring, and accessing structure variables and members.
The document discusses functions and function components in C++. It introduces key concepts such as:
- Functions allow programmers to divide programs into modular and reusable pieces.
- Functions are defined once and can be called multiple times from different parts of a program. They take in parameters and return values.
- The standard library provides many commonly used functions for tasks like math operations.
- Functions can be used to encapsulate and reuse code through prototypes and definitions.
- Enumerations allow defining a set of integer constants with unique names for use as variable types.
- Storage classes like static and auto determine where variables are stored in memory and their scope within a program.
This lecture covers overloaded functions, constant objects and member functions, friend functions, the this pointer, static data members, and composition with objects as members of classes. Specifically, it discusses:
1) Overloading constructors to initialize objects with different values.
2) Using const to declare objects, member functions, and data members as constant to prevent modification.
3) Defining member functions outside the class and using the scope resolution operator.
4) Passing objects as arguments to other functions and returning objects.
5) Using the this pointer implicitly and explicitly to access members of the current object.
6) Declaring static data members that are shared across all objects of a class.
Modify the Time classattached to be able to work with Date.pdfaaseletronics2013
Modify the Time class(attached) to be able to work with Date class. The Time object should
always remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to increase day, month and year when it is proper. Please use CISP400V10A4.cpp that
tests the tick member function in a loop that prints the time in standard format during iteration of
the loop to illustrate that the tick member function works correctly. Be aware that we are testing
the following cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
You can adjust only programs (Date.cpp, Date.h, Time.cpp and Time.h) to generate the
required result but not the code in CISP400V10A4.cpp file.
Expecting results:
// Date.cpp
// Date class member-function definitions.
#include <array>
#include <string>
#include <iostream>
#include <stdexcept>
#include "Date.h" // include Date class definition
using namespace std;
// constructor confirms proper value for month; calls
// utility function checkDay to confirm proper value for day
Date::Date(int mn, int dy, int yr, Time time)
: time01(time)
{
if (mn > 0 && mn <= monthsPerYear) // validate the month
month = mn;
else
throw invalid_argument("month must be 1-12");
year = yr; // could validate yr
day = checkDay(dy); // validate the day
// output Date object to show when its constructor is called
cout << "Date object constructor for date ";
print();
cout << endl;
} // end Date constructor
// print Date object in form month/day/year
void Date::print() const
{
cout << month << '/' << day << '/' << year;
cout << "t";
time01.printStandard();
cout << "t";
time01.printUniversal();
cout << "n";
} // end function print
// output Date object to show when its destructor is called
Date::~Date()
{
cout << "Date object destructor for date ";
print();
cout << endl;
} // end ~Date destructor
// utility function to confirm proper day value based on
// month and year; handles leap years, too
unsigned int Date::checkDay(int testDay) const
{
static const array< int, monthsPerYear + 1 > daysPerMonth =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// determine whether testDay is valid for specified month
if (testDay > 0 && testDay <= daysPerMonth[month])
{
return testDay;
} // end if
// February 29 check for leap year
if (month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year
% 100 != 0)))
{
return testDay;
} // end if
cout << "day (" << testDay << ") set to 1." << endl;
return 1;
} // end function checkDay
// adjust data if day is not proper
void Date::increaseADay()
{
day = checkDay(day + 1);
if (day == 1) // if day wasn't accurate, its value is one
{
month = month + 1; // increase month by 1
if (month > 0 && month >= monthsPerYear) // if.
The document discusses class and objects, function and operator overloading in C++. It covers topics like class declaration, class functions defined inside and outside the class, constructors, destructors, function overloading, operator overloading etc. Examples are provided for default constructor, parameterized constructor, copy constructor, function overloading using addition operator, pre-increment and pre-decrement operators. It also discusses memory allocation for objects, passing parameters by value and reference to functions.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
C++ Please I am posting the fifth time and hoping to get th.pdfjaipur2
C++
"Please I am posting the fifth time and hoping to get this resolved. I want the year to
change from 2014 to 2015 but the days of the month change to 32 rather than 1/1/2015.
Also, Please I want personal information in the heading as well Name: Last: and Course
Name:"
Modify the Time class(attached) to be able to work with Date class. The Time object should
always
remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to
increase day, month and year when it is proper. Please use CISP400V10A4.cpp that tests the tick
member function in a loop that prints the time in standard format during iteration of the loop to
illustrate that the tick member function works correctly. Be aware that we are testing the following
cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
Time class
The Time class has three private integer data members, hour (0 - 23 (24-hour clock format)),
minute (0
59), and second (0 59).
It also has Time, setTime, setHour, setMinute, setSecond, getHour(), getMinute,
getSecond,~Time,
printUniversal, and printStandard public functions.
1. The Time function is a default constructor. It takes three integers and they all have 0 as default
values. It also displays "Time object constructor is called." message and calls
printStandard
and printUniversal functions.
2. The setTime function takes three integers but does not return any value. It initializes the
private data members (hour, minute and second) data.
3. The setHour function takes one integer but doesnt return anything. It validates and stores the
integer to the hour private data member.
4. The setMinute function takes one integer but doesnt return anything. It validates and stores
the integer to the minute private data member.
5. The setSecond function takes one integer but doesnt return anything. It validates and stores
the integer to the second private data member.
Page 3 of 11 CISP400V10A4
6. The getHour constant function returns one integer but doesnt take anything. It returns the
private data member hours data.
7. The getMinute constant function returns one integer but doesnt take anything. It returns the
private data member minutes data.
8. The getSecond constant function returns one integer but doesnt take anything. It returns the
private data member seconds data.
9. The Time destructor does not take anything. It displays "Time object destructor is
called."
message and calls printStandard and printUniversal functions.
10. The printUniversal constant function does not return or accept anything. It displays time in
universal-time format.
11. The printStandard constant function does not return or accept anything. It displays time in
standard-ti.
Please I am posting the fifth time and hoping to get this r.pdfankit11134
"Please I am posting the fifth time and hoping to get this resolved. I want the year to
change from 2014 to 2015 but the days of the month change to 32 rather than 1/1/2015.
Also, Please I want personal information in the heading as well Name: Last: and Course
Name:"
Modify the Time class(attached) to be able to work with Date class. The Time object should
always
remain in a consistent state.
Modify the Date class(attached) to include a Time class object as a composition, a tick member
function that increments the time stored in a Date object by one second, and increaseADay
function to
increase day, month and year when it is proper. Please use CISP400V10A4.cpp that tests the tick
member function in a loop that prints the time in standard format during iteration of the loop to
illustrate that the tick member function works correctly. Be aware that we are testing the following
cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
d) Incrementing into the next month and next year.
Time class
The Time class has three private integer data members, hour (0 - 23 (24-hour clock format)),
minute (0
59), and second (0 59).
It also has Time, setTime, setHour, setMinute, setSecond, getHour(), getMinute,
getSecond,~Time,
printUniversal, and printStandard public functions.
1. The Time function is a default constructor. It takes three integers and they all have 0 as default
values. It also displays "Time object constructor is called." message and calls
printStandard
and printUniversal functions.
2. The setTime function takes three integers but does not return any value. It initializes the
private data members (hour, minute and second) data.
3. The setHour function takes one integer but doesnt return anything. It validates and stores the
integer to the hour private data member.
4. The setMinute function takes one integer but doesnt return anything. It validates and stores
the integer to the minute private data member.
5. The setSecond function takes one integer but doesnt return anything. It validates and stores
the integer to the second private data member.
Page 3 of 11 CISP400V10A4
6. The getHour constant function returns one integer but doesnt take anything. It returns the
private data member hours data.
7. The getMinute constant function returns one integer but doesnt take anything. It returns the
private data member minutes data.
8. The getSecond constant function returns one integer but doesnt take anything. It returns the
private data member seconds data.
9. The Time destructor does not take anything. It displays "Time object destructor is
called."
message and calls printStandard and printUniversal functions.
10. The printUniversal constant function does not return or accept anything. It displays time in
universal-time format.
11. The printStandard constant function does not return or accept anything. It displays time in
standard-time f.
Object oriented programming originated with the Simula programming languages of the 1960s. It has since become an important paradigm in computer science. The key concepts of object oriented programming include classes and objects, encapsulation, inheritance and polymorphism. An object encapsulates state (attributes) and behavior (methods) and communicates with other objects via message passing. Classes define types of objects and can be arranged in a hierarchy using inheritance where subclasses inherit attributes and methods from parent classes. Polymorphism allows objects to have multiple identities based on their class, allowing them to be used in different ways. These concepts provide benefits like modularity, code reuse and ability to model real-world problems.
1. A class defines a new user-defined type by encapsulating data members and member functions. Data members store the attributes of an object, while member functions implement the behaviors.
2. An object is an instance of a class that allocates memory for the class's data members. Objects are declared by specifying the class name followed by an identifier. Member functions manipulate the data members of an object using dot or arrow operators.
3. A class's data members and member functions can be accessed privately, publicly, or protected. Constructors initialize new objects by setting initial values for data members. Destructors release resources when objects are destroyed.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping related data members and functions together, and objects are instantiated from classes. Some key aspects of OOP include:
1. Encapsulation which involves hiding implementation details within classes and exposing a public interface.
2. Inheritance which allows a derived class to extend a base class while retaining shared properties.
3. Dynamic binding which enables polymorphic behavior where derived classes can exhibit different behavior than base classes in the same context.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping the data (attributes) and functions (methods) that operate on that data. In C++, classes use access specifiers like public and private to control whether data and methods can be accessed from outside the class or only within the class. Methods are defined either inside or outside the class using the scope resolution operator. Objects are instantiated from classes and their methods and data can be accessed using dot or arrow operators.
This document discusses iOS app design and provides examples of using timers, UIViews, and NSMutableArrays. It covers:
- Using timers (NSTimer) for time-based tasks like clocks and stopwatches, and discusses timer accuracy.
- Common operations on UIView objects like tags and UISegmentedControl.
- Storing and accessing data in NSMutableArrays, as in a numbers game.
It then provides code samples for a basic timer, specifying individual timer objects, and accurately measuring elapsed time between points. Overall the document provides an overview and examples of fundamental iOS app components.
Coding - L30-L31-Array of structures.pptxhappycocoman
The document discusses different concepts related to structures in C programming:
1. It explains how to define arrays of structures to store data of multiple types for each array element. Examples of initializing and accessing elements of an array of structures are provided.
2. Pointers to structures are introduced, showing how to declare pointer variables and access members of a structure using pointer notation with the arrow operator.
3. Benefits and drawbacks of using pointers are summarized.
4. A problem on creating a menu-driven book store management program using a structure to store book details is presented.
Construction Materials (Paints) in Civil EngineeringLavish Kashyap
This file will provide you information about various types of Paints in Civil Engineering field under Construction Materials.
It will be very useful for all Civil Engineering students who wants to search about various Construction Materials used in Civil Engineering field.
Paint is a vital construction material used for protecting surfaces and enhancing the aesthetic appeal of buildings and structures. It consists of several components, including pigments (for color), binders (to hold the pigment together), solvents or thinners (to adjust viscosity), and additives (to improve properties like durability and drying time).
Paint is one of the material used in Civil Engineering field. It is especially used in final stages of construction project.
Paint plays a dual role in construction: it protects building materials and contributes to the overall appearance and ambiance of a space.
The TRB AJE35 RIIM Coordination and Collaboration Subcommittee has organized a series of webinars focused on building coordination, collaboration, and cooperation across multiple groups. All webinars have been recorded and copies of the recording, transcripts, and slides are below. These resources are open-access following creative commons licensing agreements. The files may be found, organized by webinar date, below. The committee co-chairs would welcome any suggestions for future webinars. The support of the AASHTO RAC Coordination and Collaboration Task Force, the Council of University Transportation Centers, and AUTRI’s Alabama Transportation Assistance Program is gratefully acknowledged.
This webinar overviews proven methods for collaborating with USDOT University Transportation Centers (UTCs), emphasizing state departments of transportation and other stakeholders. It will cover partnerships at all UTC stages, from the Notice of Funding Opportunity (NOFO) release through proposal development, research and implementation. Successful USDOT UTC research, education, workforce development, and technology transfer best practices will be highlighted. Dr. Larry Rilett, Director of the Auburn University Transportation Research Institute will moderate.
For more information, visit: https://aub.ie/trbwebinars
This research presents the optimization techniques for reinforced concrete waffle slab design because the EC2 code cannot provide an efficient and optimum design. Waffle slab is mostly used where there is necessity to avoid column interfering the spaces or for a slab with large span or as an aesthetic purpose. Design optimization has been carried out here with MATLAB, using genetic algorithm. The objective function include the overall cost of reinforcement, concrete and formwork while the variables comprise of the depth of the rib including the topping thickness, rib width, and ribs spacing. The optimization constraints are the minimum and maximum areas of steel, flexural moment capacity, shear capacity and the geometry. The optimized cost and slab dimensions are obtained through genetic algorithm in MATLAB. The optimum steel ratio is 2.2% with minimum slab dimensions. The outcomes indicate that the design of reinforced concrete waffle slabs can be effectively carried out using the optimization process of genetic algorithm.
Several studies have established that strength development in concrete is not only determined by the water/binder ratio, but it is also affected by the presence of other ingredients. With the increase in the number of concrete ingredients from the conventional four materials by addition of various types of admixtures (agricultural wastes, chemical, mineral and biological) to achieve a desired property, modelling its behavior has become more complex and challenging. Presented in this work is the possibility of adopting the Gene Expression Programming (GEP) algorithm to predict the compressive strength of concrete admixed with Ground Granulated Blast Furnace Slag (GGBFS) as Supplementary Cementitious Materials (SCMs). A set of data with satisfactory experimental results were obtained from literatures for the study. Result from the GEP algorithm was compared with that from stepwise regression analysis in order to appreciate the accuracy of GEP algorithm as compared to other data analysis program. With R-Square value and MSE of -0.94 and 5.15 respectively, The GEP algorithm proves to be more accurate in the modelling of concrete compressive strength.
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...AI Publications
The escalating energy crisis, heightened environmental awareness and the impacts of climate change have driven global efforts to reduce carbon emissions. A key strategy in this transition is the adoption of green energy technologies particularly for charging electric vehicles (EVs). According to the U.S. Department of Energy, EVs utilize approximately 60% of their input energy during operation, twice the efficiency of conventional fossil fuel vehicles. However, the environmental benefits of EVs are heavily dependent on the source of electricity used for charging. This study examines the potential of renewable energy (RE) as a sustainable alternative for electric vehicle (EV) charging by analyzing several critical dimensions. It explores the current RE sources used in EV infrastructure, highlighting global adoption trends, their advantages, limitations, and the leading nations in this transition. It also evaluates supporting technologies such as energy storage systems, charging technologies, power electronics, and smart grid integration that facilitate RE adoption. The study reviews RE-enabled smart charging strategies implemented across the industry to meet growing global EV energy demands. Finally, it discusses key challenges and prospects associated with grid integration, infrastructure upgrades, standardization, maintenance, cybersecurity, and the optimization of energy resources. This review aims to serve as a foundational reference for stakeholders and researchers seeking to advance the sustainable development of RE based EV charging systems.
Newly poured concrete opposing hot and windy conditions is considerably susceptible to plastic shrinkage cracking. Crack-free concrete structures are essential in ensuring high level of durability and functionality as cracks allow harmful instances or water to penetrate in the concrete resulting in structural damages, e.g. reinforcement corrosion or pressure application on the crack sides due to water freezing effect. Among other factors influencing plastic shrinkage, an important one is the concrete surface humidity evaporation rate. The evaporation rate is currently calculated in practice by using a quite complex Nomograph, a process rather tedious, time consuming and prone to inaccuracies. In response to such limitations, three analytical models for estimating the evaporation rate are developed and evaluated in this paper on the basis of the ACI 305R-10 Nomograph for “Hot Weather Concreting”. In this direction, several methods and techniques are employed including curve fitting via Genetic Algorithm optimization and Artificial Neural Networks techniques. The models are developed and tested upon datasets from two different countries and compared to the results of a previous similar study. The outcomes of this study indicate that such models can effectively re-develop the Nomograph output and estimate the concrete evaporation rate with high accuracy compared to typical curve-fitting statistical models or models from the literature. Among the proposed methods, the optimization via Genetic Algorithms, individually applied at each estimation process step, provides the best fitting result.
2. Introduction
• Object-oriented programming (OOP)
– Encapsulation: encapsulates data (attributes) and
functions (behavior) into packages called classes
– Information hiding : implementation details are
hidden within the classes themselves
• Classes
– Classes are the standard unit of programming
– A class is like a blueprint – reusable
– Objects are instantiated (created) from the class
– For example, a house is an instance of a “blueprint
class”
3. Structure Definitions
• Structures
– Aggregate data types built using elements of other types
struct Time {
int hour;
int minute;
int second;
};
– Members of the same structure must have unique names
– Two different structures may contain members of the same
name
– Each structure definition must end with a semicolon
Structure tag
Structure members
4. Structure Definitions
• Self-referential structure
– Contains a member that is a pointer to the same structure
type
– Used for linked lists, queues, stacks and trees
• struct
– Creates a new data type that is used to declare variables
– Structure variables are declared like variables of other
types
– Example:
Time timeObject, timeArray[ 10 ],
*timePtr, &timeRef = timeObject;
5. Accessing Members of Structures
• Member access operators:
– Dot operator (.) for structures and objects
– Arrow operator (->) for pointers
– Print member hour of timeObject:
cout << timeObject.hour;
OR
timePtr = &timeObject;
cout << timePtr->hour;
– timePtr->hour is the same as ( *timePtr ).hour
– Parentheses required: * has lower precedence than .
6. 1 // Fig. 6.1: fig06_01.cpp
2 // Create a structure, set its members, and print it.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 struct Time { // structure definition
9 int hour; // 0-23
10 int minute; // 0-59
11 int second; // 0-59
12 };
13
14 void printMilitary( const Time & ); // prototype
15 void printStandard( const Time & ); // prototype
16
17 int main()
18 {
19 Time dinnerTime; // variable of new type Time
20
21 // set members to valid values
22 dinnerTime.hour = 18;
23 dinnerTime.minute = 30;
24 dinnerTime.second = 0;
25
26 cout << "Dinner will be held at ";
27 printMilitary( dinnerTime );
28 cout << " military time,nwhich is ";
29 printStandard( dinnerTime );
30 cout << " standard time.n";
31
Dinner will be held at 18:30 military time,
which is 6:30:00 PM standard time.
7. 32 // set members to invalid values
33 dinnerTime.hour = 29;
34 dinnerTime.minute = 73;
35
36 cout << "nTime with invalid values: ";
37 printMilitary( dinnerTime );
38 cout << endl;
39 return 0;
40 }
41
42 // Print the time in military format
43 void printMilitary( const Time &t )
44 {
45 cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
46 << ( t.minute < 10 ? "0" : "" ) << t.minute;
47 }
48
49 // Print the time in standard format
50 void printStandard( const Time &t )
51 {
52 cout << ( ( t.hour == 0 || t.hour == 12 ) ?
53 12 : t.hour % 12 )
54 << ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
55 << ":" << ( t.second < 10 ? "0" : "" ) << t.second
56 << ( t.hour < 12 ? " AM" : " PM" );
57 }
Time with invalid values: 29:73
8. Program Output
Dinner will be held at 18:30 military time,
which is 6:30:00 PM standard time.
Time with invalid values: 29:73
9. Implementing a Time Abstract Data
Type with a Class
• Classes
– Model objects that have attributes (data
members) and behaviors (member functions)
– Defined using keyword class
– Have a body delineated with braces ({ and })
– Class definitions terminate with a semicolon
– Example:
10. 1 class Time {
2 public:
3 Time();
4 void setTime( int, int, int );
5 void printMilitary();
6 void printStandard();
7 private:
8 int hour; // 0 - 23
9 int minute; // 0 - 59
10 int second; // 0 - 59
11 };
Public: and Private: are
member-access specifiers.
setTime, printMilitary, and
printStandard are member
functions.
Time is the constructor.
hour, minute, and
second are data members.
11. Implementing a Time Abstract Data
Type with a Class
• Member access specifiers
– Classes can limit the access to their member functions and data
– The three types of access a class can grant are:
• Public — Accessible wherever the program has access to an object of
the class
• private — Accessible only to member functions of the class
• Protected — Similar to private and discussed later
• Constructor
– Special member function that initializes the data members of a
class object
– Cannot return values
– Have the same name as the class
12. Objects
• Class definition and declaration
– Once a class has been defined, it can be used as
a type in object, array and pointer declarations
– Example:
Time sunset, // object of type Time
arrayOfTimes[ 5 ], // array of Time objects
*pointerToTime, // pointer to a Time object
&dinnerTime = sunset; // reference to a Time object
Note: The class name
becomes the new type
specifier.
13. 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
21 // Time constructor initializes each data member to zero.
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;
32 }
Note the :: preceding
the function names.
14. 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
50 // Driver to test simple class Time
51 int main()
52 {
53 Time t; // instantiate object t of class Time
54
55 cout << "The initial military time is ";
56 t.printMilitary();
57 cout << "nThe initial standard time is ";
58 t.printStandard();
59
15. 60 t.setTime( 13, 27, 6 );
61 cout << "nnMilitary time after setTime is ";
62 t.printMilitary();
63 cout << "nStandard time after setTime is ";
64 t.printStandard();
65
66 t.setTime( 99, 99, 99 ); // attempt invalid settings
67 cout << "nnAfter attempting invalid settings:"
68 << "nMilitary time: ";
69 t.printMilitary();
70 cout << "nStandard time: ";
71 t.printStandard();
72 cout << endl;
73 return 0;
74 }
The initial military time is 00:00
The initial standard time is 12:00:00 AM
Military time after setTime is 13:27
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Military time: 00:00
Standard time: 12:00:00 AM
16. Implementing a Time ADT with a Class
• Destructors
– Functions with the same name as the class but preceded
with a tilde character (~)
– Cannot take arguments and cannot be overloaded
– Performs “termination housekeeping”
• Binary scope resolution operator (::)
– Combines the class name with the member function
name
– Different classes can have member functions with the
same name
• Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){
…
}
17. • If a member function is defined inside the class
– Scope resolution operator and class name are not
needed
– Defining a function outside a class does not change
it being public or private
• Classes encourage software reuse
– Inheritance allows new classes to be derived from
old ones
Implementing a Time ADT with a Class
18. Class Scope and Accessing Class
Members
• Class scope
– Data members and member functions
• File scope
– Nonmember functions
• Inside a scope
– Members accessible by all member functions
• Referenced by name
• Outside a scope
– Members are referenced through handles
• An object name, a reference to an object or a pointer to an object
19. Class Scope and Accessing Class
Members
• Function scope
– Variables only known to function they are defined in
– Variables are destroyed after function completion
• Accessing class members
– Same as structs
– Dot (.) for objects and arrow (->) for pointers
– Example:
• t.hour is the hour element of t
• TimePtr->hour is the hour element
20. 1 // Fig. 6.4: fig06_04.cpp
2 // Demonstrating the class member access operators . and ->
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream>
6
7 using std::cout;
8 using std::endl;
9
10 // Simple class Count
11 class Count {
12 public:
13 int x;
14 void print() { cout << x << endl; }
15 };
16
17 int main()
18 {
19 Count counter, // create counter object
20 *counterPtr = &counter, // pointer to counter
21 &counterRef = counter; // reference to counter
22
23 cout << "Assign 7 to x and print using the object's name: ";
24 counter.x = 7; // assign 7 to data member x
25 counter.print(); // call member function print
26
27 cout << "Assign 8 to x and print using a reference: ";
28 counterRef.x = 8; // assign 8 to data member x
29 counterRef.print(); // call member function print
30
21. 31 cout << "Assign 10 to x and print using a pointer: ";
32 counterPtr->x = 10; // assign 10 to data member x
33 counterPtr->print(); // call member function print
34 return 0;
35 }
Assign 7 to x and print using the object's name: 7
Assign 8 to x and print using a reference: 8
Assign 10 to x and print using a pointer: 10
22. Separating Interface from
Implementation
• Separating interface from implementation
– Makes it easier to modify programs
– Header files
• Contains class definitions and function prototypes
– Source-code files
• Contains member function definitions
23. 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
6 #ifndef TIME1_H
7 #define TIME1_H
8
9 // Time abstract data type definition
10 class Time {
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
24. 23 // Fig. 6.5: time1.cpp
24 // Member function definitions for Time class.
25 #include <iostream>
26
27 using std::cout;
28
29 #include "time1.h"
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;
42 }
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 }
Source file uses #include
to load the header file
Source file contains
function definitions
25. Controlling Access to Members
• public
– Presents clients with a view of the services the class
provides (interface)
– Data and member functions are accessible
• 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
26. 1 // Fig. 6.6: fig06_06.cpp
2 // Demonstrate errors resulting from attempts
3 // to access private class members.
4 #include <iostream>
5
6 using std::cout;
7
8 #include "time1.h"
9
10 int main()
11 {
12 Time t;
13
14 // Error: 'Time::hour' is not accessible
15 t.hour = 7;
16
17 // Error: 'Time::minute' is not accessible
18 cout << "minute = " << t.minute;
19
20 return 0;
21 }
Compiling...
Fig06_06.cpp
D:Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private
member declared in class 'Time'
D:Fig6_06time1.h(18) : see declaration of 'hour'
D:Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private
member declared in class 'Time'
D:time1.h(19) : see declaration of 'minute'
Error executing cl.exe.
test.exe - 2 error(s), 0 warning(s)
Attempt to access private member
variable minute.
Attempt to modify private member
variable hour.
27. Access Functions and Utility Functions
• Utility functions
– private functions that support the operation of
public functions
– Not intended to be used directly by clients
• Access functions
– public functions that read/display data or check
conditions
– Allow public functions to check private data
• Following example
– Program to take in monthly sales and output the total
– Implementation not shown, only access functions
28. 87 // Fig. 6.7: fig06_07.cpp
88 // Demonstrating a utility function
89 // Compile with salesp.cpp
90 #include "salesp.h"
91
92 int main()
93 {
94 SalesPerson s; // create SalesPerson object s
95
96 s.getSalesFromUser(); // note simple sequential code
97 s.printAnnualSales(); // no control structures in main
98 return 0;
99 }
OUTPUT
Enter sales amount for month 1: 5314.76
Enter sales amount for month 2: 4292.38
Enter sales amount for month 3: 4589.83
Enter sales amount for month 4: 5534.03
Enter sales amount for month 5: 4376.34
Enter sales amount for month 6: 5698.45
Enter sales amount for month 7: 4439.22
Enter sales amount for month 8: 5893.57
Enter sales amount for month 9: 4909.67
Enter sales amount for month 10: 5123.45
Enter sales amount for month 11: 4024.97
Enter sales amount for month 12: 5923.92
The total annual sales are: $60120.59
Create object s, an instance
of class SalesPerson
30. Initializing Class Objects: Constructors
• Constructors
– Initialize class members
– Same name as the class
– No return type
– Member variables can be initialized by the constructor or
set afterwards
• Passing arguments to a constructor
– When an object of a class is declared, initializers can be
provided
– Format of declaration with initializers:
Class-type ObjectName( value1,value2,…);
– Default arguments may also be specified in the
constructor prototype
31. 1 // Fig. 6.8: time2.h
2 // Declaration of the Time class.
3 // Member functions are defined in time2.cpp
4
5 // preprocessor directives that
6 // prevent multiple inclusions of header file
7 #ifndef TIME2_H
8 #define TIME2_H
9
10 // Time abstract data type definition
11 class Time {
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
32. 61 // Fig. 6.8: fig06_08.cpp
62 // Demonstrating a default constructor
63 // function for class Time.
64 #include <iostream>
65
66 using std::cout;
67 using std::endl;
68
69 #include "time2.h"
70
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();
33. OUTPUT
Constructed with:
all arguments defaulted:
00:00
12:00:00 AM
hour specified; minute and second defaulted:
02:00
2:00:00 AM
hour and minute specified; second defaulted:
21:34
9:34:00 PM
hour, minute, and second specified:
12:25
12:25:42 PM
all invalid values specified:
00:00
12:00:00 AM
When only hour
is specified,
minute and
second are set
to their default
values of 0.
94 cout << "n ";
95 t3.printStandard();
96
97 cout << "nhour, minute, and second specified:"
98 << "n ";
99 t4.printMilitary();
100 cout << "n ";
101 t4.printStandard();
102
103 cout << "nall invalid values specified:"
104 << "n ";
105 t5.printMilitary();
106 cout << "n ";
107 t5.printStandard();
108 cout << endl;
109
110 return 0;
111}
34. Using Destructors
• Destructors
– Are member function of class
– Perform termination housekeeping before the system
reclaims the object’s memory
– Complement of the constructor
– Name is tilde (~) followed by the class name (i.e.,
~Time)
• Recall that the constructor’s name is the class name
– Receives no parameters, returns no value
– One destructor per class
• No overloading allowed
35. When Constructors and Destructors Are
Called
• Constructors and destructors called automatically
– Order depends on scope of objects
• 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
• Automatic local objects
– Constructors called when objects are defined
– Destructors called when objects leave scope
• i.e., when the block in which they are defined is exited
– Destructors not called if the program ends with exit or abort
36. • Static local objects
– Constructors called when execution reaches the
point where the objects are defined
– Destructors called when main terminates or
the exit function is called
– Destructors not called if the program ends with
abort
When Constructors and Destructors Are
Called
37. 1 // Fig. 6.9: create.h
2 // Definition of class CreateAndDestroy.
3 // Member functions defined in create.cpp.
4 #ifndef CREATE_H
5 #define CREATE_H
6
7 class CreateAndDestroy {
8 public:
9 CreateAndDestroy( int ); // constructor
10 ~CreateAndDestroy(); // destructor
11 private:
12 int data;
13 };
14
15 #endif
38. 16 // Fig. 6.9: create.cpp
17 // Member function definitions for class CreateAndDestroy
18 #include <iostream>
19
20 using std::cout;
21 using std::endl;
22
23 #include "create.h"
24
25 CreateAndDestroy::CreateAndDestroy( int value )
26 {
27 data = value;
28 cout << "Object " << data << " constructor";
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32 { cout << "Object " << data << " destructor " << endl; }
Constructor and Destructor changed to
print when they are called.
39. 33 // Fig. 6.9: fig06_09.cpp
34 // Demonstrating the order in which constructors and
35 // destructors are called.
36 #include <iostream>
37
38 using std::cout;
39 using std::endl;
40
41 #include "create.h"
42
43 void create( void ); // prototype
44
45 CreateAndDestroy first( 1 ); // global object
46
47 int main()
48 {
49 cout << " (global created before main)" << endl;
50
51 CreateAndDestroy second( 2 ); // local object
52 cout << " (local automatic in main)" << endl;
53
54 static CreateAndDestroy third( 3 ); // local object
55 cout << " (local static in main)" << endl;
56
57 create(); // call function to create objects
58
59 CreateAndDestroy fourth( 4 ); // local object
60 cout << " (local automatic in main)" << endl;
61 return 0;
62 }
40. 63
64 // Function to create objects
65 void create( void )
66 {
67 CreateAndDestroy fifth( 5 );
68 cout << " (local automatic in create)" << endl;
69
70 static CreateAndDestroy sixth( 6 );
71 cout << " (local static in create)" << endl;
72
73 CreateAndDestroy seventh( 7 );
74 cout << " (local automatic in create)" << endl;
75 }
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local automatic in main)
Object 3 constructor (local static in main)
Object 5 constructor (local automatic in create)
Object 6 constructor (local static in create)
Object 7 constructor (local automatic in create)
Object 7 destructor
Object 5 destructor
Object 4 constructor (local automatic in main)
Object 4 destructor
Object 2 destructor
Object 6 destructor
Object 3 destructor
Object 1 destructor
Notice how the order of the
constructor and destructor call
depends on the types of variables
(automatic, global and static)
they are associated with.
41. Using Data Members and Member
Functions
• Member functions
– Allow clients of the class to set (i.e., write) or get (i.e., read)
the values of private data members
– Example:
Adjusting a customer’s bank balance
• private data member balance of a class BankAccount
could be modified through the use of member function
computeInterest
• A member function that sets data member interestRate could
be called setInterestRate, and a member function that returns
the interestRate could be called getInterestRate
– Providing set and get functions does not make private
variables public
– A set function should ensure that the new value is valid
42. A Subtle Trap: Returning a Reference to
a Private Data Member
• Reference to an object
– Alias for the name of the object
– May be used on the left side of an assignment statement
– Reference can receive a value, which changes the
original object as well
• Returning references
– public member functions can return non-const
references to private data members
• Should be avoided, breaks encapsulation
43. 1 // Fig. 6.11: time4.h
2 // Declaration of the Time class.
3 // Member functions defined in time4.cpp
4
5 // preprocessor directives that
6 // prevent multiple inclusions of header file
7 #ifndef TIME4_H
8 #define TIME4_H
9
10 class Time {
11 public:
12 Time( int = 0, int = 0, int = 0 );
13 void setTime( int, int, int );
14 int getHour();
15 int &badSetHour( int ); // DANGEROUS reference return
16 private:
17 int hour;
18 int minute;
19 int second;
20 };
21
22 #endif
Notice how member function
badSetHour returns a reference
(int & is the return type).
44. 1. Load header
1.1 Function definitions
23 // Fig. 6.11: time4.cpp
24 // Member function definitions for Time class.
25 #include "time4.h"
26
27 // Constructor function to initialize private data.
28 // Calls member function setTime to set variables.
29 // Default values are 0 (see class definition).
30 Time::Time( int hr, int min, int sec )
31 { setTime( hr, min, sec ); }
32
33 // Set the values of hour, minute, and second.
34 void Time::setTime( int h, int m, int s )
35 {
36 hour = ( h >= 0 && h < 24 ) ? h : 0;
37 minute = ( m >= 0 && m < 60 ) ? m : 0;
38 second = ( s >= 0 && s < 60 ) ? s : 0;
39 }
40
41 // Get the hour value
42 int Time::getHour() { return hour; }
43
44 // POOR PROGRAMMING PRACTICE:
45 // Returning a reference to a private data member.
46 int &Time::badSetHour( int hh )
47 {
48 hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
49
50 return hour; // DANGEROUS reference return
51 }
badSetHour returns a
reference to the private
member variable hour.
Changing this reference
will alter hour as well.
45. 52 // Fig. 6.11: fig06_11.cpp
53 // Demonstrating a public member function that
54 // returns a reference to a private data member.
55 // Time class has been trimmed for this example.
56 #include <iostream>
57
58 using std::cout;
59 using std::endl;
60
61 #include "time4.h"
62
63 int main()
64 {
65 Time t;
66 int &hourRef = t.badSetHour( 20 );
67
68 cout << "Hour before modification: " << hourRef;
69 hourRef = 30; // modification with invalid value
70 cout << "nHour after modification: " << t.getHour();
71
72 // Dangerous: Function call that returns
73 // a reference can be used as an lvalue!
74 t.badSetHour(12) = 74;
75 cout << "nn*********************************n"
76 << "POOR PROGRAMMING PRACTICE!!!!!!!!n"
77 << "badSetHour as an lvalue, Hour: "
78 << t.getHour()
79 << "n*********************************" << endl;
80
81 return 0;
82 }
Hour after modification: 30
*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
46. Program Output
Hour before modification: 20
Hour after modification: 30
*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
47. Assignment by Default Memberwise
Copy
• Assigning objects
– An object can be assigned to another object of
the same type using the assignment operator (=)
– Member by member copy
• Objects may be
– Passed as function arguments
– Returned from functions (call-by-value default)
48. 1 // Fig. 6.12: fig06_12.cpp
2 // Demonstrating that class objects can be assigned
3 // to each other using default memberwise copy
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // Simple Date class
10 class Date {
11 public:
12 Date( int = 1, int = 1, int = 1990 ); // default constructor
13 void print();
14 private:
15 int month;
16 int day;
17 int year;
18 };
19
20 // Simple Date constructor with no range checking
21 Date::Date( int m, int d, int y )
22 {
23 month = m;
24 day = d;
25 year = y;
26 }
27
28 // Print the Date in the form mm-dd-yyyy
29 void Date::print()
30 { cout << month << '-' << day << '-' << year; }
50. Software Reusability
• Software resusability
– Implementation of useful classes
– Class libraries exist to promote reusability
• Allows for construction of programs from existing, well-
defined, carefully tested, well-documented, portable, widely
available components
– Speeds development of powerful, high-quality
software