Today’s Objectives
Structures
• Keeping track of data
• C-style structure
Classes: a Deeper Look, Part 1
• Class
• The public interface
• Encapsulation
• Information hiding
• Constructor
• Destructor
• Separating interface and implementation
• Inline functions
• Default memberwise assignment
1
Structs
Chapter 22.2
2
Structs
Keeping Track of Data
Variables are used to keep track of data in the
computer’s memory.
Regular variable – keeps track of the value of
one data element
Pointer variable – keeps track of the memory
address of a data element
Array – keeps track of a collection of related
data elements of the same data type
3
Structs (Deitel, 1058–1061)
Struct
Struct – keeps track of a collection of related
data elements that may have different data
types
• Each element is called a “member” or “field”
• Each field has a name and data type
Defining a struct
Name
struct Person{
int ID;
string firstName; Fields – always “public”
string lastName;
};
Remember the ‘;’ ! 4
Structs (Deitel, 1058–1061)
Using Structs
The struct’s definition creates a new data type
We can use it to declare a structure variable
Person alan;
To initialize the struct variable, each field can be
accessed by the “.” operator
alan.ID = 1001;
alan.firstName = "Alan";
alan.lastName = "Turing";
cout << alan.firstName << endl;
5
Structs
Dynamically Allocated Structs
We can dynamically create a struct with “new”
Use “new” to allocate memory and return a pointer
Person *pDonald = new Person;
When a pointer is used to get values stored in a struct,
each field must be accessed by the “->” operator
pDonald->ID = 1005;
pDonald->firstName = "Donald";
pDonald->lastName = "Knuth";
cout << pDonald->firstName << endl;
delete pDonald;//Always delete after new
Optional syntax: cout << (*pDonald).firstName;
6
Classes: a Deeper Look, Part 1
Chapter 9
7
Classes, Part 1 (Deitel, 77–110)
Class
Another collection of related data elements that
may have different data types
Like a struct, but better – a class also includes
all the operations that can be performed with its
data
Definition
• Class = a collection of related elements that may
have different data types and the operations that can
be performed on them
8
Classes, Part 1 (Deitel, 77–110)
Declaring a Class
Name
class Person{
public:
Person();
int getID();
void setID( int id );
string getFirstName(); Member functions
void setFirstName( string nm ); (also called methods
string getLastName();
void setLastName( string nm ); or operations)
string toString();
private:
int ID;
string firstName; Data Members
string lastName;
};
Remember the ‘;’ ! 9
Classes, Part 1 (Deitel, 77–110)
Using a Class
Instantiate an object
After a class is declared, it creates a new data
type
We can use it to “declare a variable,” but we use
a different terminology. We say that a class is
used to create an “object” that is an instance of
the class.
Instantiating an object
int main(){
Person donald;
} Object
10
Classes, Part 1 (Deitel, 77–110)
Using an Object
Call the member functions
All of the operations that an object can perform
are defined by its public member functions,
called its “public interface”
int main(){
Person donald;
donald.setFirstName("Donald");
donald.setLastName("Knuth");
cout << donald.toString();
} Argument
Object Parentheses are
“Dot” operator Member required
function
11
Classes, Part 1 (Deitel, 77–110)
The Public Interface
All of the public member functions are collectively called
the “public interface” of the class
The public interface is defined first in the design stage
After the class implementation is finished, the user of the
objects of the class has an outside view, and has access
only to the public interface
• The user knows what the objects of the class can do because
the names of the member functions, the return data type, and
the argument data types are all public
12
Classes, Part 1 (Deitel, 77–110)
Information Hiding
The implementation of the class is not always accessible
• The user does not know how the member functions work and
does not need to know
Data members are always made private
• The user of an object in your program cannot change the data by
accessing it directly
• So that we can control how the data can be changed
– We can validate a requested change
– Example: The ID member cannot be a negative number, it has to be an
integer, and it should not be a number that is already in use
• Also, so we can control how we store the data inside the class
– Example: We may decide to store the ID as a string instead of an int
The user of an object can still get the data and change it, but only by
using a public member function
13
Classes, Part 1 (Deitel, 77–110)
Encapsulation
One of the three principle features of object-oriented
programming
Means that we keep both the data and the
operations that can be done with that data inside a
single entity, the class
In addition, the user of the objects of the class has an
outside view, and has access only to the operations.
14
Classes, Part 1 (Deitel, 77–110)
Advantages
Advantages to encapsulation in a single entity that has a
public interface:
• Teamwork during development is supported – Each member
of the development team can develop a class independently.
When a developer’s class needs to interact with a class
developed by another team member, the first developer only
needs to know its public interface
• Easy to improve your program – The programmer has the
freedom to implement the operations and change them in any
way, as long as the public interface works correctly
• Reuse and program maintenance are easier
– Easier for future programmers to understand the way it works
– Easier to make improvements, e.g. speeding up a searching
function by storing the data in a sorted array instead of an unsorted
array 15
Classes, Part 1 (Deitel, 491)
Private Member Functions
Not all member functions have to be
public
If a member function is only used by
other functions in the class, it can be
private
Called utility functions
16
Classes, Part 1 (Budd)
Message Passing
Using an object’s member functions is called “message
passing”
The user of the object sends a message to the object,
asking it to perform an action
Write the name of the receiver of the message, the dot
operator, the message, and any arguments that are
required
Person james;//instantiating an object
james.setID( 1006 );//sending a message to james
james.setFirstName( "James" );
james.setLastName( "Gosling" );
cout << james.toString() << endl;
17
Classes, Part 1 (Deitel, 77–110, 493–502)
Constructor
Public member function with the same name as the class and with
no return value
Called automatically to initialize the data members whenever an
object is instantiated
Implement it in one of two ways
1. Either assign values in the constructor body
Person( int id = 0, string fn = "", string ln = "" ){
setID(id);
setFirstName(fn); Appropriate if the set function does
setLastName(ln); more than simple assignment
}
2. Or use an initializer list
Person( int id = 0, string fn = "", string ln = "" )
: ID(id), firstName(fn), lastName(ln) { }
Initializer list 18
Classes, Part 1 (Deitel, 77–110, 493–502)
Instantiating an object with
default values
When an object is instantiated, the constructor
automatically initializes the data members
The constructor will initialize the data members to default
values if the object is instantiated with this syntax:
Person james; //Invokes the default constructor
If there is a version of the constructor with parameters,
then the initial values can be passed as arguments
Person james( 1006, "James", "Gosling" );
19
Classes, Part 1 (Deitel, 489)
Inline Functions
Placing the function definition inside the class
declaration instead of defining it externally
Appropriate only for small functions
Program execution is speeded up when member
functions are defined as inline functions
The compiler will have the option of placing the code
for the function inside the main program code instead
of making a function call
20
Classes, Part 1 (Deitel, 486, 489)
Separate Implementation
Outside of and below the declaration of the member function in the
class
Class name Binary scope operator
Return type
Member function name
string Person::toString(){
return firstName + " " + lastName; Implementation
}
21
Classes, Part 1 (Deitel, 486, 489)
Separate Files for
Interface and Implementation
In C++, this is the normal approach
• Declaration goes in the header file (Person.h) – this part is
considered the “interface”
• Definition goes in the source file (Person.cpp) – this part is
considered the “implementation”
main.cpp Person.h Person.cpp
#include "Person.h" #include <string> #include "Person.h"
using std::string; string Person::getName()
int main(){ class Person{ {
Person james; public: return name;
void setName(string);
james.setName("James"); }
string getName();
} private: void Person::setName(string nm)
string name; {
}; name = nm;
}
Advantages
• Smaller header files – header files are included with the source
file
• Developer can hide the implementation details 22