Upload
mabel-carroll
View
221
Download
1
Tags:
Embed Size (px)
Citation preview
IT PUTS THE ++ IN C++
Object Oriented Programming
Why O-O?
It makes data the main focusObjects translate from real-world objectsAllows for abstraction (Too many details!)Allows for encapsulation for security and reusePromotes modularity
Design, develop and test classes independentlyPromotes reuse (did I mention reuse?)Project managementMemory management
Stack vs. heap control over allocation and deallocation of memory
Dynamic vs. static
The Header of the Class
The class structure is the blueprint for future objects
Class components are allowed to be private Mostly for protecting data Data can only be shared through a public function
that YOU (the programmer) will controlClass components are allowed to be public
Mostly for sharing functions. Member function prototypes listed here Can be accessed (called) directly from a client’s
function main() Other non-member function
The Header of the Class
Class structure is an interface Provides a list of member functions without revealing
details Provides parameters of each function and correct
usage Info for client about what is available
The class file is called the header file Filename ends in .h
Class Structure
Interface
Header file class.h
Contains public and private components:data members and member functions
Class Interface
Reveals what client can use in class and howReveals to implementer what it needs to workLists data and operations
Data members (fields) Member functions (methods) Use public/private sections to control access to clients
Preconditions and Postconditions
Communicates what a function accomplishes without indicating how it accomplishes it
Contract between two programmers Client programmer Implementation programmer
Precondition statement indicates what must be true before a function is called Required state or range of data being passed to the
functionPostcondition statement indicates what will be
true when the function finishes its work What to expect from the function
Access to Data Members
Members declared on stack, but can also be declared in heap
Client can access public features only—error returned for calls to private members
Member functions can access private data members and return to client Accessor method: method that returns or displays private data
Control over data formatting Control over which data is accessible and in which state
Mutator method Controls how data is modified Controls where data is saved Can constrain changes to a specified range Can enforce business rules for data
Implementation
Contains complete member function codeKept in separate .cpp file in IDE project folder Must include #include “class.h”
System header file in default location #include <assert> Client header file in current (IDE project) directory Preprocessor replaces #include line with entire contents
of the file Function name gets class name identifier for
class level scope Class::functionName Otherwise function is non-member function (global scope)
Class Structure
Interface Implementation
Header file class.h
Implementation file class.cpp
Contains public and private components:data members and member functions
Code for member functions
Keyword before member function name class::
#include “class.h”
Interface and Implementation Separate
Separate physical files for interface and implementation Must keep them in sync; change to any part of
prototype must be changed in both files
Accessing Private Data in Public Functions
All data members are accessible directly within a member function No object needed Dot notation not necessary
Can call other member functions (both public and private) from within a member function
Class Constructor
Constructor Member function that initializes all data member functions
to a valid state You must write it--not automatically set to default Unique Prototype
No return type Exactly same name as class Can have parameters, but if provided the client must use them Can be overloaded to provide client more than one option for
parameters Otherwise, just like other member functions
Must be included in class definition and implementation file Must have class:: keyword in implementation
Destructor
Function to clean up after an object is destroyed Called automatically on delete call or when leaving object
scopeUnlike the constructor, you don’t always need a
destructor Can use it to remove very large objects from memory if
memory is an issueUnique prototype
Exactly same name as class, but prefixed with ~ (you’ll find this symbol above the tab on most keyboards)
No parameters No return type
Client Program
Client uses class as an abstraction Invokes public operations only Internal implementation not visible
Client can’t and shouldn’t change internals Class data should be private
Interface is used by the client programmer to use the class Get information to use objects of that class, without
having to manage functionality associated with it.
Data Storage
Client program will declare object on stack Each data member defined in the class is associated
with that object declarationClient program can declare many objects on
stack of same class Each object has its own copy of each data member
defined in that classIf a client program accesses data for an
object, it is accessing the data for that copy of the member data for that class only.
Driver
Client program could be a lot like a driver. Create objects of classes to be used Call functions of those objects Call non-member client functions
To handle specific tasks of client Otherwise, may have no original code
master controller program
Client Structure
Uses #include <libraries>Uses #include “class.h”Can have using namespace std; Client file has .cpp extension
Class Structure
Client Interface Implementation
Client fileprogram.cpp
Header file class.h
Implementation file class.cpp
Code uses objects of class
Contains public and private components:data members and member functions
Code for member functions
Prototype for required function: int main( )
Keyword before member function name class::
#include “class.h”#include <library>using namespace std;
#include “class.h”
How to Use Objects
Private Member Variables – How To Access Them…
Public Member Functions
From Member function implementation?
From Client or non-member function?
Variable name (no object)
Not accessible – is there another way?
From Member function implementation?
From Client or non-member function?
function_name(*)*Provide data if required
object.function_name(*) *Provide data if required
Non-Member Functions
Non-member functions: Not part of a class Not part of a client Can be implemented in either
Class implementation file Client file
Global scope Does not have access to private class data Has access to public class functions (must use an
object)
Helper Function
Private member function of a classCannot be called by a client or non-member
function (with or without an object)—it’s private!
Can be called by another member function of the same class only
Needed to help one or more public member function of the same class Can be used to provide private data manipulation
needed as a precondition of a member function
Friend Function
Non-member function with access to private class dataPrototype in class header—public or privateIncludes friend keyword in prototype in header file
only Implemented in implementation .cpp file without the class:: keyword
Because it is a non-member function, the client calls this function without an object: function ( ) not object.function( )
Friend function can access private data, but not directly—must use an object of the class and dot operator: object.variable
How To Use Functions
Interface Prototype
Implementation Declaration
Member Function
Non-Member Friend
.h file in class { }
Not in class { } .h file in class { } with friend keyword
void print(); friend Ratio sum(Ratio, Ratio);
Member Non-Member Friend
.cpp fileclass:: keyword
Can be .cpp file if prototype in .h No keyword
.h file after class { }No keywords
void Ratio::print() {…}
Ratio sum(Ratio x, Ratio y) { …}
Private data accessible without object
Private member data not available
Private data accessible with objectx._num = 10;
How To Use Functions
Client
Member Function Non-Member Friend
Client .cpp file Attached to object
Client .cpp fileNot attached to object
Client .cpp fileNot attached to object
t.print(); Sum(r,s);
Operator Overloading
Syntax convenienceWay of allowing more than one way to use the
class as an object Client can create object and provide data to set the
intial state of member variables OR Client can create object without providing data
(contructor will set intial state)Way of using common operators for objects
Example: + vs function called add
Overloaded Operator Precedence
To overload for an operator, implement function named operatorX (Where X represents the operator you are interested in) For a class member function, the left hand side of the
equation is the receiver object and other operands are passed as arguments f1 + f2 sum = f1.operator+(f2)
For a non-member function, two operands are on equal footing f1 + f2 sum=operator+(f1, f2)