0% found this document useful (0 votes)
17 views

Lec5. C++ Classes, Constructors, Vectors

Structures and classes are both data types that can contain data members and member functions in C++. Structures by default have public members while classes have private members by default. Classes emphasize encapsulation more than structures.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lec5. C++ Classes, Constructors, Vectors

Structures and classes are both data types that can contain data members and member functions in C++. Structures by default have public members while classes have private members by default. Classes emphasize encapsulation more than structures.

Uploaded by

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

Chapters 6 & 7

Structures, Classes,
Constructors,
Objects, Vectors, etc.

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Structures
• 2nd aggregate (meaning "grouping“) data type: struct
– Recall array: collection of values of same type
– Structure: collection of values of different types
struct CDAccountV1 // Name of new struct "type"
{
double balance; // member names
double interestRate;
int term;
};

• Treated as a single item but must first "define" struct prior to


declaring any variables
• Define struct globally : no memory is allocated but just a
"placeholder" for what our struct will "look like“
• Declare structure variable: CDAccountV1 account;
– Just like simple types: variable account now of type CDAccountV1
– It contains "member values“ that is each of the struct "parts"
• Accessing structure members: account.balance, account.term
6-2
Structure Example: (1 of 2)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 6-3


Structure Example (2 of 2)

Enter account balance: $100.00


Enter account interest rate: 10.0
Enter the number of months until maturity: 6
When your CD matures in 6 months,
it will have a balance of $105.00

6-4
Structure Pitfall
• Structure Pitfall: Semicolon after structure definition
– ; MUST exist:
Required since you "can“ struct CropYield
declare structure variables {
int quantity;
in this location double size;
}; // REQUIRED semicolon!

• Structure assignments
– Given structure named CropYield, declare two structure
variables:
CropYield apples, oranges;
• Both are variables of "struct type CropYield"
• Simple assignments are legal: apples = oranges;
– Simply copies each member variable from apples into member variables from
oranges 6-5
Structures as Function Arguments
• Passed like any simple data type
– Pass-by-value
– Pass-by-reference
– Or combination
• Can also be returned by function
– Return-type is structure type
– Return statement in function definition sends structure variable back to caller
• Initializing Structures struct Date
{
int month;
int day;
int year;
};
– Can initialize at declaration
Date dueDate = {12, 31, 2003};
– Declaration provides initial data to all three member variables

6-6
class DayOfYear //name of new class type
Classes {
public:
• Similar to structures void output(); //member function!
int month;
– Adds member FUNCTIONS int day;
};
– Not just member data
• Integral to object-oriented programming
– Focus on objects: Object contains data and operations
• In C++, variables of class type are objects

• Members: data (month, day) and operations/methods (output())


• Notice only member function’s prototype
– Function’s code is elsewhere
– Can be after main() definition
• Declared same as all variables:
DayOfYear today, birthday;
– Declares two objects of class type DayOfYear 6-7
class DayOfYear //name of new class type
Classes {
public:
void output(); //member function!
DayOfYear today; int month;
int day;
};

• Members accessed same as structures


– Dot operator: Specifies member of particular object
today.month; today.day; today.output();

• Must define or "implement" class member functions


– Like other function definitions but must specify class:
void DayOfYear::output() {…}
• :: is scope resolution operator that specifies to compiler what class the function
definition comes from
– Item before :: called type qualifier

• Function used for all objects of the class and refers to "that object’s"
data when invoked
– Example: today.output(); //Displays "today" object’s data 6-8
Complete Class
Example(1 of 2)

6-9
Complete Class
Example(1 of 2)

Enter today's date:


Enter month as a number: 10
Enter the day of the month: 15
Enter your birthday:
Enter month as a number: 2
Enter the day of the month: 21
Today's date is October 15
Your birthday is February 21
Happy Unbirthday!

6-10
Encapsulation
• Any data type includes data (range of data) and operations (that can
be performed on data)
– Example int data type has:
– Data: -2147483648 to 2147483647 (for 32 bit int)
– Operations: +,-,*,/,%,logical,etc.
• Same with classes but WE specify data, and the operations to be
allowed on our data!
• Encapsulation: Means "bringing together as one"
• Declare a class  get an object
• Object is "encapsulation" of
– Data values
– Operations on the data (member functions)

6-11
Abstract Data Types (ADT)
• "Abstract“ : Programmers don’t know details
• Collection of data values together with set of basic operations
defined for the values
• ADT’s often "language-independent"
– We implement ADT’s in C++ with classes
• C++ class "defines" the ADT
– Other languages implement ADT’s as well

6-12
Principles of OOP
• Information Hiding: Details of how operations work not known to
"user" of class
• Data Abstraction: Details of how data is manipulated within
ADT/class not known to user
• Encapsulation: Bring together data and operations, but keep
"details" hidden
• Separate Interface and Implementation
– User of class need not see details of how class is implemented
• Principle of OOP  encapsulation
– User only needs "rules"
• Called "interface" for the class
– In C++  public member functions and associated comments
– Implementation of class hidden
• Member function definitions elsewhere
• User need not see them
6-13
Public and Private Members
• Data in class almost always designated private in definition!
– Upholds principles of OOP
– Hide data from user
– Allow manipulation only via operations
• Which are member functions

• Public items (usually member functions) are "user-accessible"

• Can mix & match public & private


• More typically place public first
– Allows easy viewing of portions that can be USED by programmers using the
class
– Private data is "hidden", so irrelevant to users
• Outside of class definition, cannot change (or even access) private
data
6-14
class DayOfYear Public and Private
{
public: Example
void input();
void output();
private:
int month;
int day;
};

• Data now private and objects have no direct access to them

• Declare object: DayOfYear today;


• Object today can ONLY access public members
cin >> today.month; // NOT ALLOWED!
cout << today.day; // NOT ALLOWED!
– Must instead call public operations:
today.input();
6-15
today.output();
Accessor and Mutator Functions
• Object needs to "do something" with its data
• Call accessor member functions
– Allow object to read data
– Also called "get member functions"
– Simple retrieval of member data
• Mutator member functions
– Allow object to change data
– Manipulated based on application
– Ex: set member functions

6-16
Improved version of
previous example

6-17
6-18
6-19
Enter today's date:
Enter the month as a number: 3
Enter the day of the month: 21
Today's date is March 21
J. S. Bach's birthday is March 21
Same as previous example
Happy Birthday Johann Sebastian!
6-20
Structures versus Classes
• Structures
– Typically all members public
– No member functions
• Classes
– Typically all data members private
– Interface member functions public
• Technically, same
– Perceptionally, very different mechanisms

6-21
Constructors
• Used to initialize objects
• A special kind of member function that is automatically called when
object declared
• Constructors defined like any member function, except:
1. Must have same name as class
2. Cannot return a value; not even void!
class DayOfYear {
public:
DayOfYear(int monthValue, int dayValue);
DayOfYear(int monthValue);
void input();
void output();

private:
int month;
int day;
}
• Can overload constructors just like other functions
• Provide constructors for all possible argument-lists
– Particularly "how many" 7-22
Constructors code
DayOfYear::DayOfYear(int monthValue, int dayValue)
{
month = monthValue;
day = dayValue;
}
– Can be written as
DayOfYear::DayOfYear(int monthValue,int dayValue)
: month(monthValue), day(dayValue) {}
//default argument
DayOfYear::DayOfYear(int monthValue,int dayValue)
: month(monthValue), day(1) {}
• Constructor in public section
– If private, could never declare objects!
• Constructors are executed when we declare objects:
DayOfYear date1(7, 4), date2(5);
– Objects are created here
• Constructor is called
• Values passed as arguments to constructor
• Member variables month, day initialized:
date1.month  7 date2.month  5
date1.dat  4 date2.day  1 7-23
Class with
Constructors
Example

7-24
Class with
Constructors
Example

6-25
Constructor with No Arguments
– object declarations with no "initializers":
• DayOfYear date1; // This way!
Default Constructor: defined as constructor with no arguments
– One should always be defined
– Auto-Generated?
• If no constructors AT ALL are defined  Yes
• If any constructors are defined  No
Explicit Constructor Calls
– Can also call constructor AGAIN, after object declaration :
– Such call returns "anonymous object“ which can then be assigned
• In Action: DayOfYear holiday(7, 4);
– Constructor called at object’s declaration
– Now to "re-initialize": holiday = DayOfYear(5, 5);
» Explicit constructor call
» Returns new "anonymous object"
» Assigned back to current object 7-26
Class Type Member Variables
• Class member variables can be any type including objects of other
classes!
– Need special notation for constructors So they can call "back" to member
object’s constructor

Class DayOfYear is
the same as in
previous example 7-27
Class Type
Member
Variables

7-28
Parameter Passing Methods
• Call-by-reference desirable for "large" data, like class types
• const Parameter Modifier
– For large data types (typically classes): better to use pass-by-reference
• Even if function will not make modifications
• To protect argument, use constant parameter to makes parameter "read-only"
– Place keyword const before type
– Attempt to modify parameter results in compiler error

• If a member function does not change the value of its calling object,
– you can add the const modifier to the heading of function declaration and
definition.
– const is placed at the end of function declaration, just before final
semicolon.
class BankAccount {

public:
double getBalance( ) const ;

}
7-29
double getBalance( ) const { return (accountDollars + accountCents*0.01);}
Inline Functions
• Member function definitions
– Typically defined separately, in different file
– Can be defined IN class definition
• Makes function "in-line“
• Use keyword inline in function declaration and function heading

• For class member functions:


– Place code for function IN class definition  automatically inline
• inline definitions are typically used for very short functions only
• Compiler treats an inline function in a special way.
– inserts the code for an inline function where the function is invoked.
• This saves the overhead of a function invocation
class BankAccount {

public:
double getBalance( ) const { return (accountDollars + accountCents*0.01);}

}
7-30
class BankAccount { #include <iostream>
public: #include <cmath>
#include <cstdlib>
BankAccount( double balance, double rate);
using namespace std;
BankAccount( int dollars, int cents, double rate);
BankAccount( int dollars, double rate);
BankAccount( );
void update( );
void input( );
void output( ) const;
double getBalance( ) const { return (accountDollars + accountCents*0.01);}
int getDollars( ) const { return accountDollars; }
int getCents( ) const { return accountCents; }
double getRate( ) const { return rate; }
void setBalance( double balance);
void setBalance( int dollars, int cents);
void setRate( double newRate);
private:
int accountDollars; //of balance
int accountCents; //of balance
double rate; //as a percentage
int dollarsPart( double amount) const { return static_cast<int>(amount); }
int centsPart( double amount) const;
int round( double number) const
{ return static_cast<int>(floor(number + 0.5)); }
double fraction( double percent) const { return (percent / 100.0); }
};
6-31
Static Variables and functions
• Static member variables
– All objects of class "share" one copy
– One object changes it  all see change
• Useful for "tracking"
– How often a member function is called
– How many objects exist at given time
• Place keyword static before type
• Member functions can be static If no access to object data
needed
– but still "must" be member of the class
– Can then be called outside class
• From non-class objects:
– E.g., Server::getTurn();
• As well as via class objects
– Standard method: myObject.getTurn();

• Can only use static data, functions! 7-32


class Server{
public: Static Members Example:
Server( char letterName); Server::Server( char letterName)
static int getTurn( ) {
: name(letterName)
turn++;
{ /*Intentionally empty*/}
return turn;
}
void serveOne( ); void Server::serveOne( ){
static bool stillOpen( ){ if (nowOpen && lastServed < turn){
return nowOpen; lastServed++;
} cout << "Server " << name
private: << " now serving "
static int turn; << lastServed << endl;
static int lastServed; }
static bool nowOpen; if (lastServed >= turn) //Everyone served
char name; nowOpen = false;
}; }
int Server::turn = 0;
int Server::lastServed = 0;
bool Server::nowOpen = true; How many in your group? 3
int main( ){ Your turns are: 1 2 3
Server s1('A'), s2('B');
int number, count; Server A now serving 1
do { Server B now serving 2
cout << "How many in your group? "; How many in your group? 2
cin >> number; Your turns are: 4 5
cout << "Your turns are: ";
for (count = 0; count < number; count++)
Server A now serving 3
cout << Server::getTurn( ) << ' '; Server B now serving 4
cout << endl; How many in your group? 0
s1.serveOne( ); Your turns are:
s2.serveOne( );
Server A now serving 5
} while (Server::stillOpen( )); 7-33
cout << "Now closing service.\n"; Now closing service.
Introduction to Vectors
• Recall: arrays are fixed size
• Vectors: "arrays that grow and shrink“ during program execution
• Formed from STL using template class
• Similar to array, a vector has base type and stores collection of base
type values
• Declared differently: vector <Base_Type> v;
• Indicates template class
• Any type can be "plugged in" to Base_Type
• Produces "new" class for vectors with that type
– Example declaration: vector<int> v;
• "v is vector of type int"
• Calls class default constructor, so empty vector object created
• Indexed like arrays for access
• to add elements, use member function push_back()
• To get the current number of elements, use member function size()
7-34
#include <iostream>
#include <vector> Vector Example
using namespace std;
int main( ){
vector< int> v;
cout << "Enter a list of positive numbers.\n"
<< "Place a negative number at the end.\n";
int next;
cin >> next;
while (next > 0){
v.push_back(next);
cout << next << " added. ";
cout << "v.size( ) = " << v.size( ) << endl;
cin >> next;
}
cout << "You entered:\n";
for ( unsigned int i = 0; i < v.size( ); i++)
cout << v[i] << " ";
cout << endl; Enter a list of positive numbers.
return 0; Place a negative number at the end.
} 2 4 6 8 -1
2 added. v.size = 1
4 added. v.size = 2
6 added. v.size = 3
8 added. v.size = 4
You entered:
7-35
2468
Vector Efficiency
• Member function capacity()
– Returns memory currently allocated
– Not same as size()
– Capacity typically > size
• Automatically increased as needed

• If efficiency critical:
– Can set behaviors manually
• v.reserve(32); //sets capacity to 32
• v.reserve(v.size()+10); //sets capacity to 10 more
than size

7-36

You might also like