0% found this document useful (0 votes)
25 views63 pages

OOP Week 1-2

Uploaded by

Muhammad Faizan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views63 pages

OOP Week 1-2

Uploaded by

Muhammad Faizan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

Chapter 7: Introduction to Classes and Objects

Starting Out with C++


Early Objects
Seventh Edition

by Tony Gaddis, Judy Walters,


and Godfrey Muganda

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics
7.1 Abstract Data Types
7.2 Object-Oriented Programming
7.3 Introduction to Classes
7.4 Introduction to Objects
7.5 Defining Member Functions
7.6 Constructors
7.7 Destructors
7.8 Private Member Functions

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-2


Topics (Continued)
7.9 Passing Objects to Functions
7.10 Object Composition
7.11 Separating Class Specification,
Implementation, and Client Code
7.12 Input Validation Objects
7.13 Structures
7.15 Introduction to Object-Oriented Analysis and
Design
7.16 Screen Control

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-3


7.1 Abstract Data Types
• Programmer-created data types that
specify
– legal values that can be stored
– operations that can be done on the values
• The user of an abstract data type (ADT)
does not need to know any implementation
details (e.g., how the data is stored or how the
operations on it are carried out)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-4


Abstraction and Data Types
• Abstraction: a definition that captures
general characteristics without details
– An abstract triangle is a 3-sided polygon. A
specific triangle may be scalene, isosceles, or
equilateral

• Data Type: defines the kind of values that


can be stored and the operations that can
be performed on it

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-5


7.2 Object-Oriented Programming
• Procedural programming uses variables to
store data, focuses on the processes/
functions that occur in a program. Data and
functions are separate and distinct.
• Object-oriented programming is based on
objects that encapsulate the data and the
functions that operate on it.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-6


Object-Oriented Programming
Terminology

• object: software entity that combines data and


functions that act on the data in a single unit
• attributes: the data items of an object, stored in
member variables.
• These attributes describe the characteristics of an
object.
• member functions (methods): procedures/
functions that act on the attributes of the class

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-7


More Object-Oriented Programming
Terminology

• data hiding: restricting access to certain


members of an object. The intent is to
allow only member functions to directly
access and modify the object’s data
• encapsulation: the bundling of an object’s
data and procedures into a single entity

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-8


Object Example
Square

Member variables (attributes)


int side;
Member functions
void setSide(int s)
{ side = s; }

int getSide()
{ return side; }

Square object’s data item: side

Square object’s functions: setSide - set the size of the side of the square,

getSide - return the size of the side of the square


Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-9
7.3 Introduction to Classes

• Class: A class is a user-defined data


type that we can use in our program as
a "blueprint" for creating objects.
• It is a pattern for creating objects
• Class declaration format:
class className
{
declaration;
declaration; Notice the
}; required ;

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-10


Access Specifiers

• Used to control access to members of the class.


• Each member is declared to be either
public: can be accessed by functions
outside of the class
or
private: can only be called by or accessed
by functions that are members of
the class

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-11


How to create a class
class MyClass {       // The class
 
 public:             // Access specifier
     int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string
variable)
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-12


Class Example
// Create a Car class with some attributes

class Car {
  public:
Access     string brand;   
specifiers     string model;
    int year;
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-13


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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-14


7.4 Introduction to Objects
• An object is an instance of a class
• Defined just like other variables
Square sq1, sq2;
• Can access members using dot operator
sq1.setSide(5);
cout << sq1.getSide();

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-15


Example
• class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values


  myObj.myNum = 15; 
  myObj.myString = "Some text";

  // Print attribute values


  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-16


// Create a Car class with some attributes
class Car {
  public:
    string brand;   
    string model;
    int year;
};

int main() {
  // Create an object of Car
  Car carObj1;
  carObj1.brand = "BMW";
  carObj1.model = "X5";
  carObj1.year = 1999;

  // Create another object of Car


  Car carObj2;
  carObj2.brand = "Ford";
  carObj2.model = "Mustang";
  carObj2.year = 1969;

  // Print attribute values


  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-17


Home Task.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-18


Types of Member Functions
• Acessor, get, getter function: uses but
does not modify a member variable
ex: getSide

• Mutator, set, setter function: modifies a


member variable
ex: setSide

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-19


7.5 Defining Member Functions

• Member functions are part of a class


declaration
• Can place entire function definition inside
the class declaration

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-20


Defining Member Functions Inside the
Class Declaration
• Member functions defined inside the class
declaration are called inline functions
• Only very short functions, like the one
below, should be inline functions
int getSide()
{ return side; }

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-21


Inline Member Function Example

class Square
{
private:
int side;
public:
void setSide(int s)
inline
functions
{ side = s; }
int getSide()
{ return side; }
};
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-22
Defining Member Functions After the
Class Declaration

• Put a function prototype in the class declaration


• In the function definition, precede function
name with class name and scope resolution
operator (::)
int Square::getSide()
{
return side;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-23


Conventions and a Suggestion
Conventions:
• Member variables are usually private
• Accessor and mutator functions are usually public
• Use ‘get’ in the name of accessor functions, ‘set’ in
the name of mutator functions

Suggestion: calculate values to be returned in


accessor functions when possible, to minimize the
potential for stale data

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-24


Tradeoffs of Inline vs. Regular Member
Functions
• When a regular function is called, control
passes to the called function
– the compiler stores return address of call,
allocates memory for local variables, etc.
• Code for an inline function is copied into the
program in place of the call when the
program is compiled
– larger executable program, but
– less function call overhead, possibly faster
execution
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-25
7.6 Constructors

• A constructor is a member function that is


used to initialize data members of a class
• Is called automatically when an object of the
class is created
• Must be a public member function
• Must be named the same as the class
• Must have no return type
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-26
Constructor – 2 Examples
Inline: Declaration outside the
class Square class:
{ Square(int); //prototype
. . . //in class
public:
Square(int s) Square::Square(int s)
{ side = s; } {
. . . side = s;
}; }

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-27


Overloading Constructors
• A class can have more than 1 constructor
• Overloaded constructors in a class must
have different parameter lists
Square();
Square(int);

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-28


The Default Constructor
• Constructors can have any number of
parameters, including none
• A default constructor is one that takes
no arguments either due to
– No parameters or
– All parameters have default values
• If a class has any programmer-defined
constructors, it must have a programmer-
defined default constructor
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-29
Default Constructor Example

class Square
{
private: Has no
int side; parameters

public:
Square() // default
{ side = 1; } // constructor
// Other member
// functions go here
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-30


Another Default Constructor Example

class Square
{ Has parameter
private: but it has a
int side; default value

public:
Square(int s = 1) // default
{ side = s; } // constructor
// Other member
// functions go here
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-31


Invoking a Constructor

• To create an object using the default


constructor, use no argument list and no ()
Square square1;
• To create an object using a constructor that
has parameters, include an argument list
Square square1(8);

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-32


7.7 Destructors
• Public member function automatically
called when an object is destroyed
• Destructor name is ~className, e.g.,
~Square
• Has no return type
• Takes no arguments
• Only 1 destructor is allowed per class
(i.e., it cannot be overloaded)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-33


• Will be continue in the next lecturer…..

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-34


7. 8 Private Member Functions

• A private member function can only


be called by another member function of
the same class
• It is used for internal processing by the
class, not for use outside of the class

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-35


7.9 Passing Objects to Functions
• A class object can be passed as an
argument to a function
• When passed by value, function makes a
local copy of object. Original object in
calling environment is unaffected by actions
in function
• When passed by reference, function can
use ‘set’ functions to modify the object.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-36


Notes on Passing Objects
• Using a value parameter for an object can
slow down a program and waste space
• Using a reference parameter speeds up
program, but allows the function to modify
data in the structure
• To save space and time, while protecting
structure data that should not be changed,
use a const reference parameter
void showData(const Square &s)
// header
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-37
Returning an Object from a Function

• A function can return an object


Square initSquare(); // prototype
s1 = initSquare(); // call
• Function must define a object
– for internal use
– to use with return statement

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-38


Returning an Object Example
Square initSquare()
{
Square s; // local variable
int inputSize;
cout << "Enter the length of side: ";
cin >> inputSize;
s.setSide(inputSize);
return s;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-39


7.10 Object Composition
• Occurs when an object is a member
variable of another object.
• Often used to design complex objects
whose members are simpler objects
• ex. (from book): Define a rectangle class.
Then, define a carpet class and use a
rectangle object as a member of a carpet
object.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-40


Object Composition, cont.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-41


7.11 Separating Class Specification,
Implementation, and Client Code

Separating class declaration, member


function definitions, and the program that
uses the class into separate files is
considered good design

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-42


Using Separate Files

• 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 a class
implementation file. Name the file classname.cpp
(for example, Square.cpp)This file should
#include the class specification file.
• A client program (client code) that uses the class must
#include the class specification file and be compiled
and linked with the class implementation file.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-43


Include Guards
• Used to prevent a header file from being included twice
• Format:
#ifndef symbol_name
#define symbol_name
. . . (normal contents of header file)
#endif
• symbol_name is usually the name of the header file, in all
capital letters:
#ifndef SQUARE_H
#define SQUARE_H
. . .
#endif

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-44


What Should Be Done Inside vs. Outside
the Class

• Class should be designed to provide


functions to store and retrieve data
• In general, I/O should be done by functions
that use class objects, rather than by class
member functions

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-45


7.12 Input Validation Objects
Classes can be designed to validate user
input
– to ensure acceptable menu choice
– to ensure a value is in range of valid values
– etc.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-46


7.13 Structures

• Structure: C++ construct that allows multiple


variables to be grouped together
• Structure Declaration Format:
struct structure name
{
type1 field1;
type2 field2;

typen fieldn;
};
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-47
Example struct Declaration

struct Student
structure tag
{
int studentID;
string name; structure members
short year;
double gpa;
}; Notice the
required
;
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-48
struct Declaration Notes

• struct names commonly begin with an


uppercase letter
• The structure name is also called the tag
• Multiple fields of same type can be in a
comma-separated list
string name,
address;

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-49


Defining Structure Variables
• struct declaration does not allocate
memory or create variables
• To define variables, use structure tag as
type name
Student s1; s1
studentID
name
year

gpa

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-50


Accessing Structure Members
• Use the dot (.) operator to refer to
members of struct variables
getline(cin, s1.name);
cin >> s1.studentID;
s1.gpa = 3.75;
• Member variables can be used in any
manner appropriate for their data type

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-51


Displaying struct Members

To display the contents of a struct


variable, you must display each field
separately, using the dot operator
Wrong:
cout << s1; // won’t work!
Correct:
cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.year << endl;
cout << s1.gpa;

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-52


Comparing struct Members

• Similar to displaying a struct, you


cannot compare two struct variables
directly:

if (s1 >= s2) // won’t work!

• Instead, compare member variables:


if (s1.gpa >= s2.gpa) // better

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-53


Initializing a Structure
Cannot initialize members in the structure
declaration, because no memory has been
allocated yet

struct Student // Illegal


{ // initialization
int studentID = 1145;
string name = "Alex";
short year = 1;
float gpa = 2.95;
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-54


Initializing a Structure (continued)

• Structure members are initialized at the time


a structure variable is created
• Can initialize a structure variable’s members
with either
– an initialization list
– a constructor

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-55


Using an Initialization List
An initialization list is an ordered set of
values, separated by commas and
contained in { }, that provides initial values
for a set of data members

{12, 6, 3} // initialization list


// with 3 values

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-56


More on Initialization Lists

• Order of list elements matters: First value


initializes first data member, second value
initializes second data member, etc.
• Elements of an initialization list can be constants,
variables, or expressions
{12, W, L/W + 1} // initialization list
// with 3 items

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-57


Initialization List Example
Structure Declaration Structure Variable
box
struct Dimensions
{ int length, length 12
width, width 6
height;
height 3
};
Dimensions box = {12,6,3};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-58


Partial Initialization

Can initialize just some members, but


cannot skip over members
Dimensions box1 = {12,6}; //OK
Dimensions box2 = {12,,3}; //illegal

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-59


Problems with Initialization List

• Can’t omit a value for a member without


omitting values for all following members
• Does not work on most modern compilers if
the structure contains any string objects
– Will, however, work with C-string members

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-60


Using a Constructor to Initialize
Structure Members

• Similar to a constructor for a class:


– name is the same as the name of the struct
– no return type
– used to initialize data members
• It is normally written inside the struct
declaration

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-61


A Structure with a Constructor

struct Dimensions
{
int length,
width,
height;
// Constructor
Dimensions(int L, int W, int H)
{length = L; width = W; height = H;}
};

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-62


Passing Arguments to a Constructor

• Create a structure variable and follow its


name with an argument list
• Example:
Dimensions box3(12, 6, 3);

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7-63

You might also like