69
ECE 449 – OOP and Computer Simulation Lecture 06 Associative Containers, Class Design Professor Jia Wang Department of Electrical and Computer Engineering Illinois Institute of Technology September 29, 2017 ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/69

ECE 449 OOP and Computer Simulation Lecture 06 Associative ...jwang/ece449-2017f/ece449-lec06.pdf · ECE 449 { OOP and Computer Simulation Lecture 06 Associative Containers, Class

Embed Size (px)

Citation preview

ECE 449 – OOP and Computer SimulationLecture 06 Associative Containers,

Class Design

Professor Jia WangDepartment of Electrical and Computer Engineering

Illinois Institute of Technology

September 29, 2017

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 2/69

Reading Assignment

I This lecture: 7, 9

I Next lecture: Project 3 Specification

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 3/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 4/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 5/69

Semantics

module top;

wire in, out;

wire [7:0] a, b, s, in; // wire in is defined twice

not(outp, in); // wire outp is not defined

zero(a[8], b[7:4]); // a[8] doesn’t exist

output sim_out(out[0], b); // out is not a bus

endmodule

I Every statement follows the syntax of EasyVL.I When grouped together into a module, the statements as a

whole, do not make much sense.I The semantics of the circuit are not correct.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 6/69

Semantics of Wires, Pins, and Gates

I Semantics of wiresI Each wire should be defined only once.

I Semantics of pinsI Pin name must be name of wire.I Range of bits can only be used for wires whose widths are at

least 2.I Range of bits must be consistent with wire widths.

I Semantics of gates (components)I Each gate has a desired number of pins.I Each pin has a desired number of bits.

I With correct semantics, we are able to proceed to build thenetlist.

I As a data structure that will be discussed later.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 7/69

Semantics and Search

I Verify that no wire with the same name is defined.I Cross-reference: for a given pin, search for its wire definition

to decide if the bits as specified in the pin are valid.I The width of the pin is further validated against the type of

the gate it belongs to.

I In essence, we need to search by names.I How much time does it take to search a vector or a list?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 8/69

Sequential Search

struct evl_wire

{

std::string name;

int width;

}; // struct evl_wire

typedef std::vector<evl_wire> evl_wires;

I We can find a wire with a given name by applying sequentialsearch to the container no matter it’s a list or a vector.

I Time complexity of sequential search: O(k) on average for acontainer with k elements

I On average you need to access k2 elements.

I So if there are n wires and m pins,I Need O(n2) time to perform name check for all wiresI Need O(mn) time to perform name check for all pins

I How to improve performance?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 9/69

Sorting and Binary Search

I To search for things efficiently, you always need to sort them.I We can verify no two wires have the same name after all the

statements are processed.I Sort the wires in the container according to their namesI Verify that no two consecutive wires have the same nameI Time complexity: O(n log n) (compared to O(n2))

I We can perform binary search on the sorted container for awire when verifying semantics for pins.

I The container has to be a vector.I Time complexity: O(m log n) (compared to O(mn))

I There are library algorithms for sorting and binary search,though they are conceptually complicated.

I Is there a container supporting efficient search but hiding allthe details?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 10/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 11/69

Associative Containers

I Containers automatically arrange elements into a sequencedepending on the contents of the elements themselves.

I Instead of the sequence in which we inserted them, as forsequential containers.

I The ordering is further exploited to expedite searches forparticular elements.

I Key: the value used for ordering and searchI For wires, their names are the keys.

I Key-value pair: in addition to key, each element could containadditional information (value) that is not used for ordering orsearch

I For wires, their widths are the values.

I std::map: associative containers that store key-value pairsI From the standard header map

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 12/69

The C++ Map

typedef std::map<std::string, int> evl_wires_table;

I std::map<Key,Value> is a template class that requires twotypes for instantiation.

I The type Key can be of any value type whose objects we cancompare to keep them ordered.

I E.g. built-in integral types and std::stringI Never use float or double as Key

I The type Value can be of any value type.I Provide additional information about the keys

I std::map is usually implemented as red-black trees, thoughwe don’t need to understand its theory before we can use it.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 13/69

Insert Key-Value Pairs

bool make_wires_table(const evl_wires &wires,

evl_wires_table &wires_table) {

for (auto &wire: wires) {

wires_table.insert(std::make_pair(wire.name, wire.width));

}

return true;

}

I Note that auto is deduced as const evl_wire.

I Use std::make_pair to create a key-value pair to beinserted to the container

I The value is associated with the key at the time the pair isinserted to the container.

I We ignore the wires with the same name for now.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 14/69

Access Key-Value Pairs Sequentially

void display_wires_table(std::ostream &out,

const evl_wires_table &wires_table) {

for (evl_wires_table::const_iterator it = wires_table.begin();

it != wires_table.end(); ++it) {

out << "wire " << it->first

<< " " << it->second << std::endl;

}

}

I The pattern of the for loop and the iterators is alsoapplicable for std::map.

I Note that the sequence follows the ordering of keys, e.g. thewires are shown in the alphabetical order of their names.

I The elements of std::map are key-value pairs.I The key is the member first of the pair.I The value is the member second of the pair.I They can be accessed using iterators. Also recall that

it->first stands for (*it).first.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 15/69

Access Key-Value Pairs Sequentially (Cont.)

void display_wires_table(std::ostream &out,

const evl_wires_table &wires_table) {

for (auto &kv: wires_table) {

out << "wire " << kv.first

<< " " << kv.second << std::endl;

}

}

I It is usually easier to use range-based for loops to accesselements in containers sequentially. map.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 16/69

Search for Elements

bool make_wires_table(const evl_wires &wires,

evl_wires_table &wires_table) {

for (auto &wire: wires) {

auto same_name = wires_table.find(wire.name);

if (same_name != wires_table.end()) {

std::cerr << "Wire ’" << wire.name

<< "’is already defined" << std::endl;

return false;

}

wires_table.insert(std::make_pair(wire.name, wire.width));

}

return true;

}

I The member function std::map<Key,Value>::find is usedto search for the element with a given key.

I It returns an iterator to the element.I Or end() if no such element exists.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 17/69

Insert Key-Value Pairs Using []

bool make_wires_table(const evl_wires &wires,

evl_wires_table &wires_table) {

for (auto &wire: wires) {

auto same_name = wires_table.find(wire.name);

if (same_name != wires_table.end()) {

std::cerr << "Wire ’" << wire.name

<< "’is already defined" << std::endl;

return false;

}

wires_table[wire.name] = wire.width;

}

return true;

}

I The operator [] is overloaded for std::map, which gives anillusion that you can index into it using keys.

I It returns the reference to the value associated with the key.I If the key is not already in the map, it will insert a key-value

pair first.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 18/69

Complexity of Map Operations

I Consider a map of n elements.I Space complexity is O(n).

I Map operationsI insert and erase: O(log n) timeI find: O(log n) timeI []: O(log n) time

I Iterator operationsI ==, !=, *: O(1) timeI ++, --: O(log n) time

I All operations consume O(1) space.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 19/69

Other Associative Containers

I Use std::set<Key> from the standard header set if you areonly interested in keys instead of key-value pairs

I Hash tables instead of red-black trees.I To emphasize that the elements are not ordered in a way that

makes sense to users. They are called std::unordered_map

and std::unordered_set.I With the same interface as std::map and std::setI insert, erase, find, [] will take O(1) time on average if

there is enough memory.

I The idea to manage data as key-value pairs extends to mostmodern programming languages and is centric to many cloudcomputing and storage techniques.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 20/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 21/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 22/69

Possible Issues with Our Previous Class Type Definitions

struct evl_token {

enum token_type {NAME, NUMBER, SINGLE};

token_type type;

std::string str;

int line_no;

}; // struct evl_token

I One must learn them in great detail.I E.g. one must know there are three data members before

attempting to initialize an object correctly.I You are actually working on a lower abstraction level if you

need such detailed understandings.

I One must code them correctly.I E.g. one may forget to initialize line_no or would modify str

without updating type.

I It’s convenient for one to learn the knowledge if they aregrouped. But that’s not enforced.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 23/69

Object-Oriented Programming (OOP)

I A programming paradigm.

I Abstraction: to use a type, you don’t need to know its detailsI Encapsulation: the details of a type is hidden from you

I You can only manipulate its objects in a predefined way.I The operations is therefore guaranteed to be valid.

I Modularity: things related to a type is required to be groupedtogether

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 24/69

Class Types

I There are two kinds of types in C++.I Built-in types: int, int &, bool, etcI Class types: std::string, std::vector, evl_token

I To create class types for OOP is the most critical task inC++ and most other languages.

I What language features are available for OOP?I How to design class types?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 25/69

Class Design for Calendar Dates

I Let’s design a class type for calendar dates.I We can start with the following type date.

struct date {

int year, month, day;

}; // struct date

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 26/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 27/69

Member Functions

I We have seen and used many member functions for classtypes from the standard library.

I std::string: substr, c_str, etc.I Containers: size, begin, end, etc.

I Member functions define the valid operations available to aclass type.

I It helps to hide details: you don’t need to know how toimplement a double-linked list before you can useinsert/erase to modify a std::list.

I Member functions group operations related to a class type.I All the member functions have the scope of the class type.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 28/69

Use Member Functions

I Consider a function that will display the date.

void display_date(std::ostream &out, const date &d) {

...

}

void some_function() {

date today;

today.year = 2017; today.month = 9; today.day = 29;

display_date(std::cout, today)

}

I How about to introduce a member function called display?

void some_function() {

date today;

today.year = 2017; today.month = 9; today.day = 29;

today.display(std::cout);

}

I A member function should be declared before one can use itand be defined exactly once.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 29/69

Declare Member Functions

struct date {

int year, month, day;

void display(std::ostream &out);

}; // struct date

I To declare a member function, you should put its headerinside struct.

I Essentially, you are forced to group all related operations ofdate together when defining the type itself.

I Where is the parameter d in display_date?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 30/69

Define Member Functions

void date::display(std::ostream &out) {

out << year << "/" << month << "/" << day << std::endl;

}

I To define a member function, you need to use its qualifiedname.

I The member function has the scope of the class type.I The qualified name for display is date::display.

I Since you must call a member function with an object and .,the object becomes implicit to the member function.

I So we don’t need to specify the parameter d explicitly in amember function.

I Since the object is implicit, you don’t need to use . to refer toits members when implementing the function.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 31/69

Set Date

struct date {

int year, month, day;

void display(std::ostream &out);

bool set(int y, int m, int d);

}; // struct date

bool date::set(int y, int m, int d) {

... // return false if the date is not valid

year = y; month = m; day = d;

return true;

}

I We can introduce another member function to set a specificdate.

I We can also validate the date before modifying the object.I Better than let someone to set date arbitrarily.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 32/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 33/69

Protection

I By using member functions, one can work with date withoutknowing its details.

I However, one can still access the three data members.I Able to make changes bypassing the validation in set

I We should allow users to manipulate date objects onlythrough the member functions.

I In other words, we need to protect data members.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 34/69

Public and Private Members

struct date {

private:

int year, month, day;

public:

void display(std::ostream &out);

bool set(int y, int m, int d);

}; // struct date

I A protection label defines how the members thereafter shouldbe protected, until the next label appears.

I Public members are defined using the label public:.I Accessible to all users of the type

I Private members are defined using the label private:.I Inaccessible to users of the typeI But accessible to member functions

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 35/69

Default Protection for Structs

I By default, all members in a struct are public.I So

struct date {

private:

int year, month, day;

public:

void display(std::ostream &out);

bool set(int y, int m, int d);

}; // struct date

is the same asstruct date {

void display(std::ostream &out);

bool set(int y, int m, int d);

private:

int year, month, day;

}; // struct date

I Protection labels can occur in any order within the type, andcan occur multiple times.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 36/69

Define Class Types Using Classes

class date {

int year, month, day;

public:

void display(std::ostream &out);

bool set(int y, int m, int d);

}; // class date

I Since we need to keep data members private, the languageconstruct like struct but has all members being private bydefault is class.

I Default protection is the only difference between struct andclass.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 37/69

Accessor Functions

class date {

int year, month, day;

public:

...

int get_year();

int get_month();

int get_day();

}; // class date

int date::get_year() {

return year;

}

...

I Member functions whose names follow some conventions.

I getter functions allow to read data members.

I setter functions allow to write data members.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 38/69

Issues with Accessor Functions

I Accessor functions break encapsulation and thus should beintroduced with care.

I Setter functions can easily bypass validations so you will getan invalid object.

I So we should never introduce set_year, set_month, andset_day.

I Getter functions are less troublesome since they are supposedto keep the objects unchanged.

I However, they create tight couplings between theimplementation and the user’s code.

I It’s a design decision and one must try to balance theencapsulation and the ease of use.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 39/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 40/69

Initialization

date someday;

someday.display(std::cout); // undefined behavior

I There is one remaining problem we need to address.I One has to call set to make a date object valid.I Otherwise all data members contain undefined value and will

lead to undefined behavior.

I We need to enforce proper initializations when constructing anobject.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 41/69

Constructor

class date {

int year, month, day;

public:

date(int y, int m, int d);

void display(std::ostream &out);

bool set(int y, int m, int d);

...

}; // class date

I A constructors is a special member function.I Has the same name as the classI Won’t return a result (NEVER put void there)I Will be called automatically when constructing objects

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 42/69

Define Constructor

date::date(int y, int m, int d)

: year(y), month(m), day(d) {

}

I Constructor initializers: the new syntax between theparameter list and the function body starting by :.

I Used by compiler to initialize data members before thefunction body get executed

I The data members are initialized using the values that appearbetween ().

I Since we initialize all the data members using constructorinitializers, the body of the constructor is empty.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 43/69

Use Constructor

date today(2017, 9, 29);

today.display(std::cout);

date someday; // compiling error

I You can provide year/month/day to construct a date object.I The constructor is called implicitly and automatically.

I You have to provide them to construct any date object.I So it is guaranteed by compiler that there is no undefined

behavior because of members not initialized.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 44/69

Work with Multiple Constructors

class date {

public:

date(int y, int m, int d);

date(std::string str);

...

}; // class date

date today(2017, 9, 29);

date date_from_str("2017/9/29");

I A class can have multiple ctors.I They should have different parameters types – so the compiler

can decide which one to call given the arguments.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 45/69

Have you thought of these questions?

I Any remaining issues with date::display and the getterfunctions?

I Why we need to use constructor initializers?

I Why we have to provide year/month/day to construct dateobjects after we introduce a constructor?

I When we define a variable of type evl_token, why themember str is initialized to an empty string but type andline_no contain undefined value?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 46/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 47/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 48/69

Constness

date today(2017, 9, 29);

const date const_today = today;

display_date(std::cout, const_today);

const_today.display(std::cout); // compiling error

I We cannot change const_today.

I There is no problem to call display_date since the secondparameter is a const reference.

I Although we won’t change the object in display, thecompiler doesn’t know that and will complain if we call it.

I We need to tell the compiler so.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 49/69

Handle Constness in Member Functions

class date {

int year, month, day;

public:

...

void display(std::ostream &out) const;

int get_year() const;

int get_month() const;

int get_day() const;

}; // class date

void date::display(std::ostream &out) const {

out << year << "/" << month << "/" << day << std::endl;

}

int date::get_year() const {

return year;

}

...I You create a const member function by adding const afterits parameter list.

I The compiler will complain for any modification to the objectin const member functions.

I For const objects, you can only call const member functions.ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 50/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 51/69

Language Features vs. Design Decisions

I Defining a nice class in C++ is a very challenging task.I Need to use many language features.I Need to make design decisions.

I Language features and design decisions are actually closelyrelated.

I C++ is designed to support established design practices.

I How to design a class?I What should be the data members?I What should be the member functions?

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 52/69

State of Object

I Consider any object.I Consisting of data members and member functions specified by

its type

I The values of the members and the objects referred to bymembers are collectively called the state of the object.

I Or simply called its value

I For example,I State of date: values of year, month, dayI State of evl_token: values of str, type, line_no

I To use an object, the major concern is to keep its state valid,or well defined.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 53/69

Class Invariant

I An invariant is something that will always remain true duringsome progress.

I If we consider a date or a evl_token object during programexecution,

I We expect year/month/day to be a valid calendar date.I We expect the token str is on line line_no of the input file

and has a type of type.

I Class invariant: the condition for the state of an object to bevalid

I It is implied by the type of the object so we call it classinvariant.

I The class invariants of date and evl_token are shown above.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 54/69

Roles of Class Interface

I Class interface: declarations of constructors and publicmember functions

I Constructors should establish the class invariant for theobjects when they are constructed.

I Public member functions should maintain the class invariant.I Therefore, one can safely assume all the objects of the class

always satisfy the invariant as long as they are manipulatedthrough the class interface.

I As guaranteed by mathematical induction.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 55/69

Public Member Functions

I Class invariant should hold before and after a call to a publicmember function.

I Class invariant serves as the precondition and thepostcondition of the implicit object for any public memberfunction.

I Postcondition: a condition that should be satisfied when thefunction returns

I That’s always true for const member functions.I Non-const public member functions are expected to make

some progress: change the state of the object from a validone to another valid one.

I When we refer to implementation, we mean how that changeis computed.

I The class invariant may be violated during the computation.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 56/69

Private Member Functions

I Implementations could be very complicated.I Class designers need to organize the computations into

functions.I Those functions should be private member functions.

I It is not necessary for the private member functions to havethe class invariant as the pre- and the postcondition.

I In other words,I If a member function may violate class invariant, it need to be

private.I Otherwise, it could be public.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 57/69

Data Members

I If invariants exist among a set of variables, it is a good idea toform a class with them as data members.

I year, month, day.I str, line_no, type.I argv, argc.

I Avoid to design a class that leads to a god object – the objectthat tries to do everything.

I Variables where no invariant exist should not be bundled into aclass directly.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 58/69

Outline

Associative ContainersEasyVL Semantics and SearchAssociative Containers

Class TypesOOPMember FunctionsProtectionConstructors

Advanced ConceptsConstnessClass InvariantDefault Constructor and More

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 59/69

Default Constructor and Default Initialization

class date {

public:

date();

date(int y, int m, int d);

...

}; // class date

date::date() : year(1970), month(1), day(1) {

}

// inside some other function

date firstday;

firstday.display(std::cout); // show 1970/1/1

I Default constructor: a ctor takes no arguments.I Let’s shorten constructor to ctor in the slides.

I Default-initialization: constructing an object withoutproviding any arguments

I Default ctor is called automatically for default-initialization.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 60/69

A Usual Mistake

date firstday(); // construct firstday using the default ctor?

firstday.display(std::cout);

I date firstday(); declares a function called firstday thattakes no arguments and returns a date object.

I A rule from the C language.

I For default-initialization, you provide no arguments and ().

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 61/69

Implicitly-Declared Default Constructor

I The compiler will generate a public default ctor for anynon-reference type if the type has no user-defined ctors.

I For built-in types, e.g. int and bool, it will do nothing.I For class types, it will default-initialize their members.

I There will be a compiling error if a member has no defaultconstructor.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 62/69

Why?

I Having a user-defined ctor is a hint of non-trivial classinvariants.

I The compiler expects the class designer to provide a defaultctor if one tries to default-initialize an object.

I Otherwise, the compiler attempts to maintain the weakestclass invariant – members should satisfy their individual classinvariant, by default-initializing them.

I Why don’t default ctors assign some value to built-in types toavoid undefined behaviors?

I Again, this is a rule from the C language for performancereasons.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 63/69

Default Constructor: Example I

class vec_ref {

std::vector<int> &ref;

}; // class vec_ref

vec_ref vref; // compiling error

I No user-defined ctor

I So there will be an implicitly-declared default ctor.I It will default-initialize ref.

I It’s a reference type and default-initialization makes no sense.I So there is a compiling error.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 64/69

Default Constructor: Example II

struct evl_token {

enum token_type {NAME, NUMBER, SINGLE};

token_type type;

std::string str;

int line_no;

}; // struct evl_token

I No user-defined ctor

I So there will be an implicitly-declared default ctor.

I It will default-initialize str to an empty string.I It will default-initialize type and line_no.

I They are built-in types and so will contain undefined values.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 65/69

Default Constructor: Example III

class date {

int year, month, day;

public:

date(int y, int m, int d);

void display(std::ostream &out) const;

bool set(int y, int m, int d);

}; // class date

date someday; // compiling error

I There is a user-defined ctor.

I So there is no implicitly-declared default ctor.

I There is a compiling error since the compiler fails to find thedefault ctor for default-initialization.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 66/69

How to call constructors?

date::date() {

date(1970, 1, 1);

}

I Many times, you are tired of writing repeated codes in ctorsto initialize the object.

I How about reusing some ctor by calling it?

I The above C++ code is valid, though not what you want.I date(1970, 1, 1); creates a date object without a name,

which is then destroyed at the end of the statement.

I You CANNOT call ctors from within the object, e.g. a ctor.I It is logically incorrect: starting from the body of the ctor, the

members are already constructed – calling a ctor implies theywill be constructed again.

I Anyway, you can define a private member function to sharecode.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 67/69

How to initialize reference members?

class vec_ref {

std::vector<int> &ref;

public:

vec_ref(std::vector<int> &param);

}; // class vec_ref

vec_ref::vec_ref(std::vector<int> &param)

: ref(param) {

}

// some other function

std::vector<int> int_vec

vec_ref vref(int_vec);

I You have to initialize reference members using the constructorinitializers.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 68/69

Summary and Advice

I Use associative containers if you need to search frequently.I Elements of std::map are key-value pairs and are ordered

according to the keys.I Most operations, including search, of std::map consume

O(log n) time.

I Each class type should have a class invariant.I Constructors establish the class invariant.I Public member functions maintain the class invariant.

I Implicitly-declared default ctorI Generated automatically for types w/o user-defined ctorsI It will default-initialize the members recursively.I Do nothing for a member of a built-in type.

I Member functions can be const or non-const, depending ontheir semantics.

ECE 449 – Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 69/69