Introduction to Classes - PowerPoint PPT Presentation

1 / 53
About This Presentation

Introduction to Classes


Title: Powerpoint Slides for the Standard Version of Starting Out with C++, Fourth Edition Author: Christopher Kardaras Last modified by: itjones – PowerPoint PPT presentation

Number of Views:80
Avg rating:3.0/5.0
Slides: 54
Provided by: Christop452


Transcript and Presenter's Notes

Title: Introduction to Classes

  • Chapter 13
  • Introduction to Classes

  • 12.1 Procedural and Object-Oriented Programming
  • 12.2 Introduction to Classes
  • 12.3 Defining an Instance of a Class
  • 12.4 Why Have Private Members?
  • 12.5 Software Design Considerations
  • 12.6 Using Private Member Functions
  • 12.7 Inline Member Functions
  • 12.8 Constructors

  • 12.9 Destructors
  • 12.10 Constructors That Accept Arguments
  • 12.11 Input Validation Objects
  • 12.12 Overloading Constructors
  • 12.13 Only One Default Constructor and One
  • 12.14 Arrays of Objects
  • 12.17 An Object-Oriented System Development Primer

12.1 Procedural and Object- Oriented
  • Procedural programming
  • focuses on the processes/actions that occur in a
  • Object-Oriented programming
  • is based on the data and the functions that
    operate on it.
  • Objects are instances of ADTs that represent the
    data and its functions

Problems with Procedural Programming
  • global variables versus complex function
  • Use of global data may allow data corruption
  • Programs based on complex function hierarchies
  • difficult to understand and maintain
  • difficult to modify and extend
  • easy to break

Object-Oriented Programming Terminology
  • class
  • like a struct (allows bundling of related
    variables), but variables and functions in the
    class can have different properties than in a
  • object
  • an instance of a class, in the same way that a
    variable can be an instance of a struct

Object-Oriented Programming Terminology
  • attributes
  • member data of a class
  • behaviors
  • member functions of a class

More on Objects
  • data hiding
  • restricting access to certain data members of an
  • public interface
  • members of an object that are available outside
    of the object.
  • This allows the object to provide access to some
    data and functions without sharing its internal
    details and design, and provides some protection
    from data corruption
  • objects can be general-purpose or


Member Variables float width float
length float area
Member Functions void setData(float w, float
l) function code void calcArea(void)
function code float getWidth(void)
function code float getLength(void)
function code float getArea(void)
function code
Figure 12-2
General Purpose Objects
  • Creating data types that are improvements on
    Cs built-in data types. For example, an array
    object could be created that works like a regular
    array, but additionally provides bounds-checking.
    ( Vector )
  • Creating data types that are missing from C.
    For instance, an object could be designed to
    process currencies or dates as if they were
    built-in data types.The string class provides an
    alternative to using C-string.
  • Creating objects that perform commonly needed
    tasks, such as input validation and screen output
    in a graphical user interface.

12.2 Introduction to Classes
  • Objects are created from a class (instances of a
  • Format
  • class ltclass namegt
  • member data declarations
  • member function declarations

Class Example
  • class Square
  • private
  • int side
  • public
  • void setSide(int s)
  • side s
  • int getSide()
  • return side

Access Specifiers
  • Used to control access to members of the class
  • public
  • can be accessed by functions outside of the class
  • private
  • can only be called by or accessed by functions
    that are members of the class

More on Access Specifiers
  • Can be listed in any order in a class
  • Can appear multiple times in a class
  • If not specified, the default is private

  • // This program demonstrates a simple class.
  • include ltiostreamgt
  • using namespace std
  • // Rectangle class declaration.
  • class Rectangle // class
  • private // private member data
  • float width
  • float length
  • public // public member functions
  • void setWidth(float)
  • void setLength(float)
  • float getWidth()
  • float getLength()

private data
Function Prototypes
public functions
Example (Cont.)
Scope resolution operator
  • ltReturnTypegt ltClassNamegtltfunctionNamegt(Parameter
  • // setData copies the argument w to private
  • // width and len to private member length.
  • void RectanglesetWidth(float w)
  • width w
  • void RectanglesetLength(float len)
  • length len

Example (Cont.)
  • // getWidth returns the value in the private
    member width.
  • float RectanglegetWidth(void)
  • return width
  • // getLength returns the value in the private
    member length.
  • float RectanglegetLength( )
  • return length
  • // getArea returns the value in the private
    member area.
  • float RectanglegetArea( )
  • return length width

Example (Cont.)
  • int main( )
  • Rectangle box
  • float rectWidth, rectLength
  • cout ltlt "This program will calculate the area of
  • cout ltlt "rectangle. What is the width? "
  • cin gtgt rectWidth
  • cout ltlt "What is the length? "
  • cin gtgt rectLength
  • box.setWidth(rectWidth)
  • box.setLength(rectLength)
  • cout ltlt "Here is the rectangle's data\n"
  • cout ltlt "width " ltlt box.getWidth() ltlt endl
  • cout ltlt "length " ltlt box.getLength() ltlt endl
  • cout ltlt "area " ltlt box.getArea() ltlt endl

Program Output
  • This program will calculate the area of a
  • rectangle. What is the width? 10 Enter
  • What is the length? 5 Enter
  • Here is the rectangle's data
  • width 10
  • length 5
  • area 50

12.3 Defining an Instance of a Class
  • Class objects must to be defined after the class
    is declared
  • An object is an instance of a class
  • Defined like structure variables
  • Square sq1, sq2
  • Access public members using dot operator
  • sq1.setSide(5)
  • cout ltlt sq2.getSide()
  • A compiler error is generated if you attempt to
    access a private member using a dot operator
  • Example Prog 12-1

Pointer to an Object
  • Can define a pointer to an object
  • Square sqPtr
  • Can access public members via pointer
  • sqPtr sq1
  • sqPtr-gtsetSide(12)
  • sqPtr sq2
  • sqPtr-gtsetSide(sq1.getSide())
  • cout ltlt sqPtr-gtgetSide()

12.4 Why Have Private Members?
  • Making data members private provides data
  • Data can be accessed only through public
  • Public functions define the classs public

Set versus Get Functions
  • Set function
  • function that stores a value in a private member
  • Get function
  • function that retrieves a value from a private
    member variable
  • Common class design practice
  • make all member variables private, provide public
    set and get functions

12.5 Software Design Considerations
  • Place class declaration in a header file that
    serves as the class specification file. Name the
    file classname.h, for example, square.h
  • Place member function definitions in
    classname.cpp, for example, square.cpp
  • File should include the class specification file
  • Programs that use the class must include the
    class specification file, and be compiled and
    linked with the member function definitions

Software Design Considerations
  • Usually
  • class declarations are stored in their own
    header files. ( .h )
  • Member function definitions are stored in their
    own source files. ( .cpp )
  • The ifndef directive allows statements to be
    conditionally compiled. This prevents a header
    file from accidentally being included more than

  • Contents of Rectangle.h
  • ifndef RECTANGLE_H
  • define RECTANGLE_H
  • // Rectangle class declaration.
  • class Rectangle
  • private
  • float width
  • float length
  • float area
  • public
  • void setData(float, float)
  • void calcArea( )
  • float getWidth( )
  • float getLength( )
  • float getArea( )
  • endif

Example Cont.
  • Contents of Rectangle.cpp
  • include Rectangle.h" // Rectangle Class
  • // Rectangle Class member function definitions
  • // setData copies the argument w to private
    member width and
  • // l to private member length.
  • void RectanglesetData(float w, float l)
  • width w
  • length l
  • ...

Defining a Member Function
  • When defining a member function
  • Put the function prototype in the class
  • Define the function outside of the class
    declaration using class name and scope resolution
  • ()
  • int SquaregetSide()
  • return side
  • Example .h file, .cpp file, main file

Input/Output with Objects
  • Class should be designed to provide functions to
    store and retrieve data
  • Functions that use objects of a class should
    perform input/output operations, not class member
  • There can be exceptions to these rules
  • a class can be designed to display a menu, or
    specifically to perform I/O

12.6 Using Private Member Functions
  • A private member function can only be called by
    another member function
  • It is used for internal processing by the class,
    not for use outside of the class
  • A private member function is also referred to as
    a utility function
  • Example .h file, .cpp file, main file

12.7 Inline Member Functions
  • Member functions can be defined
  • in the class declaration ( inline )
  • after the class declaration
  • Inline member functions are appropriate for short
    function bodies
  • int getSide() return side

Tradeoffs Inline vs. Regular Member Functions
  • Regular functions
  • when called, compiler stores return address of
    call, allocates memory for local variables, etc.
  • Inline functions
  • Code for an inline function is copied into
    program in place of call larger executable
    program, but no function call overhead, hence
    faster execution

12.8 Constructors
  • Member function that is called when an object is
  • Called automatically
  • Constructor function name is class name
  • Has no return type ( not even void )

Constructor Example
  • class Square
  • private
  • int side
  • public
  • Square() //constructor prototype
  • ...
  • SquareSquare() //function header
  • side 1
  • Example Progs 12-4, 12-5

12.9 Destructors
  • Member function automatically called when an
    object is destroyed
  • Destructor name is classname, e.g., Square
  • character is called the tilde
  • Has no return type takes no arguments
  • Only 1 destructor per class, i.e., it cannot be
  • If constructor allocates dynamic memory,
    destructor should release it
  • Example Prog 12-7

12.10 Constructors That Accept Arguments
  • Default constructor
  • constructor that takes no arguments
  • To create an object using the default
    constructor, use no argument list and no ()
  • Square square1
  • To create a constructor that takes arguments
  • indicate parameters in prototype( if used ) ,
  • provide arguments when object is created
  • Square square2(12)

Constructors That Accept Arguments
  • Constructor may have default arguments
  • Square(int 1) // prototype
  • SquareSquare(int s) // heading
  • side s
  • Example
  • .h file, main file,
  • .h file, main file

12.11 Input Validation Objects
  • Objects can be designed to validate user input
  • Acceptable menu choice
  • Test score in range of valid scores
  • etc.

12.12 Overloading Constructors
  • A class can have more than 1 constructor
  • Overloaded constructors ( like any overloaded
    function ) in a class must have different
    parameter lists
  • Square()
  • Square(int)

Member Function Overloading
  • Non-constructor member functions can also be
  • void setSide()
  • void setSide(int)
  • Must have unique parameter lists as for

12.13 Only One Default Constructor and One
  • Do not provide gt 1 default constructor for a
    class one that takes no arguments and one that
    has default arguments for all parameters
  • Square()
  • Square(int 0) // will not compile
  • Since a destructor takes no arguments, there can
    only be one destructor for a class

12.14 Arrays of Objects
  • Objects can be the elements of an array
  • Square lottaSquares10
  • Default constructor for object is used when array
    is defined
  • Must use initializer list to invoke constructor
    that takes arguments
  • Square triSqu3 5,7,11
  • More complex initialization if constructor takes
    gt 1 argument

Accessing Objects in an Array
  • Objects in an array are referenced using
  • Member functions are referenced using dot
  • lottaSquares3.setSide(6)
  • cout ltlt triSqui.getSide()

12.17 An Object-Oriented System Development Primer
  • Procedural Programming
  • program is made up of procedures sets of
    programming statements that perform tasks
  • Object-Oriented Programming
  • program is made up of objects entities that
    contain data (attributes) and actions (methods)

Benefits of Object-Oriented Programming
  • Simplification of software development for
    graphical (GUI) applications
  • visual components (menus, text boxes, etc.)
    modeled as objects
  • visual components (e.g., windows) may be made up
    of multiple objects
  • some objects (e.g., buttons) may have methods
    associated with them

Benefits of Object-Oriented Programming
  • Simplification of software development for
    non-GUI applications - the problem
  • procedural programming enforces separation
    between code and data
  • changes in data format require extensive
    analysis, testing to ensure program functionality

Benefits of Object-Oriented Programming
  • Simplification of software development for
    non-GUI applications - a solution
  • OO programming addresses the problem through
  • encapsulation combination of data and actions in
    an object
  • data hiding protection of an objects data by
    its public member functions

Component Reusability
  • Component a software object that performs a
    well-defined task or that provides a service
  • Component Reusability the ability to use a
    component in multiple programs without (or with
    little) modification

Relationships Between Objects
  • A program may contain objects of different
  • Objects may be related by one of the following
  • Access (knows relationship)
  • Ownership (has a relationship)
  • Inheritance (is a relationship)

Messages and Polymorphism
  • Message request to an object to perform a task.
    Implemented as a member function call
  • Polymorphism ability to take many forms.
    Sending the same message to different objects may
    produce different behaviors

Object Oriented Analysis
  • Used to create the logical design of a system,
    what the system is to do
  • Usually includes
  • examine the problem domain model the system from
    within that perspective
  • identify the objects that exist within the
    boundaries of that system
  • identify the relationships between the objects
  • realize that there may be many right solutions

Object Oriented Design
  • Used to determine how requirements from OO
    Analysis will be implemented
  • Usually includes
  • determine hierarchical relation between objects
  • determine object ownership of attributes
  • implement and test refine as required
Write a Comment
User Comments (0)