Tuesday, December 9, 2014

cs nov 6

shape s cannot be declared as the contructor for shape is protected...
Triangle T ( inherited for shape) is ok  since derived classes can use protected member functions such as the constructor..



Triangle

     -add(POint);  vector<Point> points


Polygon also inherits everything from shape. it also has a vector of points and and has the add method for it.

struct Triangle : Shape
{
  Triangle(p1,p2, p3, c)
  :
  {
    p.add(point1);
  };
}

struct Polygon : Closed_polyline {
  {
      void add(Point p);  // add is different from shape so it is being overridden from Shape, there is an invariant no parallels and intersection..
    void draw_lines() const;
 };


open_polyline <- Closed_polyline<- Polygon

Polygon <- Triangle  (so not needing a separate storage for points.

public :

Point point(int i) const {returns points[i]; }  // read only access to points vector in the shape class.


Triangle - > Point (Association relationship, Point does not know about Triangle but Triangle can see point)

violet -- metauml diagram

Inheritance is a relationship between classes.

Association/Aggregation/Composition -- relationship between class and the objects in it or between objects. specific/concrete.

3 Relationships
is-a
has-a
uses

After refactoring ::

class Triangle : Polygon
{
    Triangle ( )
  {
       this.add();
   // the number of points cannot be more than 3;
}

cs Nov 4

Study Graphlib
ch12-16

-ch 17
ch18-21 parts  (template), memory management

differences between procedural and Object oriented programming..


ADT -- hides details set of values and operations on those values.. (abstract interface), design stage, language neutral

API -- Application Porgrammers Interface eg. Graphlib  (concrete interface)

       - details of how to use the methods (functions, operations) of the classes

      - the interface, declarations, parameters.

diff between api, adt .. api shows all the interface details , adt hides the details, complexity.., implementation stage, specific to the implementation

UDT - User defined type
         - built in types..

Line class is not overriding the add method, as invoking the shape add method..

for Lines class derived from shape, are the two methods add, draw_lines

virtual -- specify polymorphism..  ie. the compiler won't wait to make the decision to which defined method to use , it would pick the method to use at compile time..

2 requirements to implement polymorphism.
-- delay the binding of calling to run time..

1. invoke the function using a  pointer or reference to the object. sh->draw() or f(Shape& s)
2. invoke a virtual function

Polymorphism

-- compile time (function operator overloading - static binding)
-- run time (dynamic binding)

Difference between overloading and overriding..
overloading -- diff parameter list
overriding -- same parameter list..

Lines -- add(Point p1, Point p2) ; overloading..
add is not polymorphic as it is not declared using the virtual keyword.
draw_lines() is polymorphic as it is declared using the virtual keyword in the base class - shape

move, draw_lines is virtual.
number_of_points is using points vector to return the number of points in shape class
return type is unsigned integer so converting it to int..

Lab :

UML diagram take a look to make it work.
ask why you got 9 and not 10 :)
use the setmask to mask and show only one picture at a time.
refactor the code using inheritance for Polygon instead of composition

Shape<- Polygon<- Triangle
later member functions in their own file.
Design Stage language independent

Thursday, December 4, 2014

cs quiz 5

write code to increment..

Date d = wed;

 d =Day(int(d) + 1); // for class enum have to do this way.

for plain enumeration the compiler will promote(widening conversion) the value to int if needed.

or plain enum (ie. not class) compiler will promote (cast0 convert widening. d = Day(d+1);

Date dates[10]; // won't work without default constructor;

Date (int y = 2000 , int m=1, int d = 1); /// all 3 are optional..

Date d1;

default constructor for Date has no parameters...

Date::Date(){}

cs Oct 30



CppDoc

Create an API from your code

JavaDoc for Java

Shape -- Circle
          -- openPolyline
              -- closedPolyline
                  -- Polygon
                   -- Triangle

Later rewrite Triangle to inherit directly from Polygon rather than inheriting from Shape.

Polygon P;

P.add(Point(100.200));

function overloading means same name different parameter list.. could take a different number or different type or both.
function overriding  -- same name, same parameter list. This can only occur in an inheritance hierarchy. (there is a hidden parameter passed which is pointer to the object type)



protected : keeps it in the family. (inheritance hierarchy). access is ok within the family ie. classes derived derived from it but not outside..

but is the same as private if the class is standalone.

struct Triangle : Polygon

For square just add 4 points instead of 3.

inherit only the protected and public but not the private data members... by the derived from the base class

editor ../.ash to check the history and copy from there.

create a shell file

https://en.wikipedia.org/wiki/Class_diagram








cs Oct 28

Oct 28

function overloading -operator overloading

f(2);
void f(int)
f()
void f()

compitle time binding -- early binding

run-time binding - late binding


Inheritance -- is-a
aggregation -- contains, has-a

ch12 - ch16

a point is a circle (could be with radius = 0)
a circle is a point (could be with radius )
a circle has a point
a point has a  circle

compile-time binding -- static
runtime-binding -- dynamic

runtime binding

Shape *sh;
Triangle T;
Square S;

T.draw();
S.draw();
Sh = &T;
Sh->draw();

or a function

f(Shape & s)
{
 s.draw()
}

inheritance hierarchy using pointers
using ponter to to the base object...

in C++ this is implemented using virtual functions.

add keyword virtual  (for this to work the compiler must add code to make it happen)
virtual void draw();  // possibly runtime polymorphism

invoke the function using a pointer.

1. invoke the function using a  pointer or reference to the object. sh->draw() or f(Shape& s)
2. virtual keyword.

Graphlib, javadoc

compile chapter.12.3.cpp

1. install  fltk-1.1.10-dev.tcz to access fltk dependent tools/libraries especially fltk-config

- Build the author's library
-compile chapter.12.3.cpp
-tangram lab(1) development

4th parameter is default..

sudo  find -name "simple_window.h"
sudo find / -name Fl.h



g++ -I ../GUI   chapter.12.3.cpp -lbookgui -L../GUI -fno-rtti `fltk-config --ldflgs --use-images`

Libraries lib___.a

compile -l libraryname(ending with .a)

atoi : ascii to integer..

1 < atoi("1")  <cstdlib>

/GUI directory ran make



editor GUI.cpp
added <cstdlib>
qualified atoi by std::atoi

fltk-config

fltk-config --compile program.cxx
fltk-config --libs

/usr/local/lib/libfltk.a

   --ldflags

-lfltk

RTTI (Runtime type Instantiation)

cd

adding -fno-rtti in makefile of /GUI for CXXflags

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=fitting%20the%207%20tangram%20shapes%20into%20a%20square%20algorithm

Building the tangram square with the seven pieces.


cs Oct 23



Class Enumeration v/s Plain Enumeration

Month::jan

Month m = jan;

enum class Month, have to always use Month::jan , scope to use

enum Month

FINAL : given enum for Month do an operloading for the ++ operator.

lab5.cpp.pdf has a dependency on CreditCards.tex

after every operation , do a check_invariant..

credit_cards.cpp

#include "credit_cards.h"
#include <stdexcept>

bool CreditCards::invariant_violation()
{
   bool r = (coomonlimit != 1000 and  ..;
  for (CreditCard* x: cards) if (x->limit !=  commonlimit) r = true; // r should be true ?
  return r;
}

CreditCards::CreditCards(unsigned int limit)
:commonlimit(limit)
{
  if (invariant_violation()) throw std::runtime_error("invariant violation");
}

void CreditCards::add(CreditCard* c)
{
    if(cards.find(c) ! = cards.end()) throw std::runtime_error("pre-condition violation");
  cards.insert(c);
  if (invariant_violation()) throw std::runtime_error("invariant violation");

}

void CreditCards::card_delete(CreditCard* c)
{
   if (invariant_violation()) throw std::runtime_error("invariant violation");
}

void CreditCards::withdraw(CreditCard* c, unsigned int)
{
   if (invariant_violation()) throw std::runtime_error("invariant violation");
}
void CreditCards::deposit(CreditCard* c, unsigned int)
{
   if (invariant_violation()) throw std::runtime_error("invariant violation");
}

void CreditCards::withdrawAvail(CreditCard* c)
{
   if (invariant_violation()) throw std::runtime_error("invariant violation");
}

CreditCars cc(3000); fail_("should be failed to create cc with invalid limit");
catch(runtime_error) {succeed_(); }
try(CreditCards cc(5000); succeed_(); }
catch(runtime_error) { fail_("should not have failed to create cc with valid limit");}
 CreditCard c1(1000);
 CreditCards cc(2000);
 try(cc.add(&c1); fail_("illegal to have different limit");} catch(){succeed_();}
 CreditCard c2(2000);
 try(cc.add(&c2); succeed_();}fail_("illegal to have different limit");} catch(){succeed_();}

cs Oct 21



struct is not adequate
-doesn't allow you to protect the integrity of the objects data

 has correct values

class -- class invariant
           in C++ describes the valid values
   integrity of the data , data hiding , data encapsulation

 allows us to use encapsulation and data hiding to protect the data.

Why would you defined the constructor (pg 14) definition outside the class versus defining it inside the class definition.

typically in a different file (.cpp))

-- you link to update definition without recompiling your code.

-- helps to clarify the interface when reading the code.

may be mre efficient to define -- inline function rather than in class definition.

con if not inline it : making function calls

int main()
{
   f();
   f()
  f()
  f()

{
eg.. if f has 10 lines then the total lines of code are 14 but if f is inline then there are 40 lines of code as the calls are replaces by the actual code.
when to inline it and when not.. if the number of lines in the function are very less then it would be better to inline it as the cost of calling a function maybe mch more..

recursive function would be impossible to inline it..

Pg 16

 class Date{

public:
   class Invalid {};

}
Date::Date

{

    if !(check) throw Invalid();

}

In exception handling

 catch (Date::Invalid)

constructor would be Date::Invalid::Invalid
summaries of types/exceptions/classes. (Pg 17)

an enumerations creates a  new type whic is the subset of integer
two versions of enumeration.

1.enum class Month (ne in C++)  -- enumerators are class scope

2. enum Month -- enumerators are global scope.

Pg 18 internal representation of enum should not matter. almost constants...

cout << dec <<x ; { output in decimal}

cout << hex<<x;  // output in hex format.


const

const int x = 0; // constant value
  int f(const int  &x) // constant reference
{
}

const Date& f(int x)  // return a reference to the Date which cannot be changed.. : what is returned cannot be changed
{
}

int f() const ; // cant modify the data members of the class. -- object.

http://www.cplusplus.com/forum/general/12087/

global scope



 Month m = feb;

Month h = Month::feb ; // class scope

Scoped enum

1. clash with the scope definitions.
2. the int can be used to make invalid comparison...  which will compile correctly

Operator Overloading

overload some operator

 x + y ; Date x, int y

x + y

Date operator+(Date d, int a)
{

    d.add_day(a);
    return d;
}

enum class Month{
  Jan=1, Feb. ..
};

Month Operator++(Month& m)
{
    m =(m == Dec) ? Jan : Month(int(m)+1);
    return m;
}

insertion operator or output operator..

vector<string> month_tbl;

ostream& operator<<(ostream& os, Month m)
{
   return os << month_tbl[int(m)];
}

  ostream& os, const Date &d) ; // as there are three members in a date
{
    return os << d.y <<" "<<d.m<< " "<<d.d;
}

Lab ::

1. Build the doc.
2. Build the executable
3. Write Unit tests for all the seven member functions. (pass, fail) so min 14

cp/mnt/sdc1/CreditCards.tex

copy , shift insert to paste to terminal

All credit cards have the same limit..

P in Object specification indicates Powerset Or all the subsets in the set..
class invariant :  all cards have the same limit.

tce-load -wio ImageMagick

cs Oct 16, 2014



two_cards.cpp

#include "two_cards.h"
#include <stdexcept>
TwoCards::TwoCards(CreditCard * cd1, CreditCard * cd2)
:c1(cd1),c2(cd2),totalbal(c1->getBalance()+c2->getBalance())
{
   if (not check_invariant())
 throw std::runtime_error("invariant violation");
}

 void TwoCards::withdraw1(unsigned int amt){
  c1->withdraw(amt);
 totalbal = c1->getBalance() + c2->getBalance();
}
 void TwoCards::transfer(unsigned int)
 void TwoCards::withdrawEither(unsigned int)
 void TwoCards::replaceCard1(CreditCard *)
{
  // check the three preconditions
}
 bool TwoCards::check_invariant()
{
   return c1 != c2  and totalbal == c1->getBalance() + c2->getBalance();
}

two_cards.h


lab4.cpp
#include <iostream>
#include <stdexcept>
using namespace std;
#include "test.h"
#include "credit_card.h"

{
  public :
  void run()
   {
/*{\subsection{testcases for TwoCards constructor - pass }}*/
      CreditCard *c1 = new CreditCard(1000);
       CreditCard *c2 = new CreditCard(2000);
      try {TwoCards tc(c1,c2); succeed_();
    test_(tc.totalBal == 0); // initially zero balance
} catch(std::runtime_error& e)
   { std::cerr << e.what() << std:: endl;
      fail_("no exception expected");
    }
  /*{\subsection{testcases for TwoCards constructor - fail }}*/

      try {TwoCards tc(c1,c1); fail_("should not allow 2 of same card");
} catch(std::runtime_error& e)
   { std::cerr << e.what() << std:: endl;
      succeed_();
    }
  TwoCards tc(c1,c2);
  tc.withdraw1(500);
test_(tc.totalbal == -500);
test_(c1->getBalance() == -500);
test(c2->getBalance() == 0);
  CreditCard *c3 = new CreditCard(1000);
 CreditCard *c4 = new CreditCard(5000);

   try {tc.replaceCard1(c1); fail_("should not allow  same card");
} catch(std::runtime_error& e)
   { std::cerr << "expected failure message"<<e.what() << std:: endl;
      succeed_();
    }

   try {tc.replaceCard1(c3); succeed_();
 test_(tc.totalbal == -500); // still owe the bank 500
} catch(std::runtime_error& e)
   { std::cerr << e.what() << std:: endl;
      fail_("no exception expected");
    }

 try {tc.replaceCard1(c4); fail_("should not allow  different limit");
} catch(std::runtime_error& e)
   { std::cerr << "expected failure message"<<e.what() << std:: endl;
      succeed_();
    }
 }
};

initialization ocurs in the order as declared in the .h file. not initializer list so sometimes there is a segmentation fault or the tests don't pass through because of that.

cs Oct 14, 2014




   return code : may be invalid or valid depending on the function so that can always not be used for exception handling..

if (area() < 0) error (" "); // just throwing an error not handling it..

sometimes there is no return code that indicates error.

g++ -c causes it to not call the linker.

class Bad_area{
    Bad_area(){};  //default constructor, {} imply definition
}

class Plant
{
 public:
   Plant(); // default ctor.
 private:
    int stems;
    const double pi;
};

Plant::Plant()
:pi(3.14154),stems(i)  // member initialization list
{

}

Date d1;
Date d2(2014);
Date d3(2014,10);
Date d4(2014,10,14);

#define vector Vector

vector<int> v;

v[0]; would throw an exception because of the define statement above.

OOP is extending the language by building new types in the new domain..

2 types of C++ UDT's classes enumerations

classes are new types that composites of other types..
enum are new types that are subsets of int.

Lab 4

Unit test each member of two cards

Download all the files from blackboard
in tinycore get lab4.sh to run (set mode to 755)
src2latex and pdlatex 5 times
cleantex.sh remove comments from tex files. (chmod 755)
make scripts executable
create any missing files.

 -create twocards.cpp minimum is 1 comment

Interaction of objects
Credit_card c1;
Credit_card c2;
Twocards tc(c1,c2);

cs Oct 9, 2014 lab



/*{\clearpage
  This tests
}*/

  c4.withdraw(1000); test_(c4.getbalance() == -1000);
  c4.withdraw(4000);test_(c4.getbalance() == -5000);
  try {c4.withdraw(10); fail_("should not have withdrawn 10");}
   catch (const char*) {succeed_();}
  test_(c4.getBalance() == -5000);

// withdraw avail and deposit
int amt = c4.withdrawAvail();
 cerr << " amt :" << amt << "limit:" << limit << "balance: "<<c4.getBalance() << std::endl;
test_(amt == c4.limit + c4.getBalance());
test_(c4.getBalance() == -c4.limit);
c4.deposit(2000);   //expect balance = -3000
test_(c4.getBalance() == 3000);
amt = c4.withdrawAvail(); // amt should be  be -2000


credit_card.cpp

void CreditCard::withdraw(unsigned int a)
{
   balance -= a;

  if (check_invariant == false )
     balance += a;
}
void CreditCard::deposit(unsigned int){
  balance += amt;
}
int CreditCard::withdrawAvail(){
 { temp =balance;
  balance = -limit;
return (int) limit + temp;
}



getbalance
  return balance;
}


\includepdf[pages=-]{credit_card.cpp.pdf}

tce-load -wio ImageMagick

cs oct 9

Oct 9, 2014

Detailed study of ch 9

skim chp 10 and 11
12-16 GUI -- application of the techniques of ch 9

ch 17 very important

18-21 as we need  generic programming..

nouns --> objects
verbs -> members

one of most important applications is  simulations

data members -- values are the state of the object (private :).

difference between class and an object :  class is a type , user-defined type, an object is instance of the class in memory.

member functions : - to manipulate /manage the state. (public : to ensure object has correct values, maintain invariant)

class data protect the integrity of the object

cs Oct 7



Goal : finish exception handling (ch5)

if time start chapter 9 , read all of ch 9 by next week, next quiz (after 5) is 9
int num = 1;
int denom = 0;

if (denom !=0)
    cout << num/denom;  (handling the error

exception handling : added to C++ baecause" separate detection of errors from handling of errors why ? --> the code that detects the error may not know the best way to handle it. eg.. display device being available. also to reuse code.

may be in a library of classes or functions written long before the application is written.

range_error is not thrown by default for out of range errors on subscript operators unless std_lib_facilities.h is used.



if you want the exception thrown use at function. v.at[2] as opposed to v[2] (which doesn't throw)

try {

}
catch (out_of_range&) {} // out_of_range errors
catch(...) {}  // all other errors

throw 0; // what is the type of the value 0 (int, so would be caught by ...

vector<int> v(3);

reference to v[10]  would not throw an out of range error but v.at[10] would throw an out of range error.

why does he use a struct sometimes and a class sometimes. He uses class instead of struct if there is a meaningful class invariant.  if there is no invariant then uses a struct instead of a class i.e. members can take any values or no constraints.

eg. a class for date (months could be only from Jan to Dec)

out_of_range : built in to standard library.

data members in range_error class  : index..
function in range_error class : constructor function.

class Bad_area{};  // do data member and member functions.. creates a default constructor.

 throw Bad_area() ; //creating a type.

catch(Bad_area)

postcondition would return the area. which should be positive so that may be checked...

cs Oct 6, 2014 lab




unit test

every member function of the class.

write the test first.
check whether all the files are transferred to linux
then start understanding the tests.


src2latex credit_card.h

pdflatex credit_card.h.tex

src2latex credit_card.cpp
pdflatex credit_card.tex

edit lab3.cpp
\includegraphics{credit_card.h.pdf}

src2latex lab3.cpp

pdflatex lab3.cpp.tex

package grfiles solves the problem of two .'s in the filename..

oz.sty not found.

Going to using pdfpages instead of include graphics as the current include files will have multiple pages rather than just 1, as includegraphics just puts its as a picture
minipage -- put it in two columns.

cs Oct 2, 2014



Pointer is taking up 4 bytes ( 4 gigabyte) 2^32 addresses.
char 1 byte
int 4 bytes
double 8 bytes
pass by reference : change and return than more than 1 value.

Lab Portion in the other lab :

credit_Card.h

/*{section{Interface of Credit class}
)*/
class CreditCard
{
   private:
  int balance;
public :
 const unsigned int limit;
  CreditCard(unsigned int);
  void withdraw(unsigned int){};
  void deposit(unsigned int){};
 int withdrawAvail(){};
 int getBalance(){};
private:
 bool check_invariant(){};

};

credit_Card.cpp

/*{section{Interface of Credit class}
)*/
#include "credit_card.h"
CreditCard::CreditCard(unsigned int n)
:limit(n);{
   if (check_invariant() == false) throw "invariant error";
}
  void withdraw(unsigned int){}
  void deposit(unsigned int){}
 int withdrawAvail(){}
 int getBalance(){}
 bool check_invariant(){
    return(limt == 1000 or limit == 2000 or limit == 5000);

}

in lab3.cpp

class CreditCardTest : public TestSuite::Test
{
public:
void run
 {
   // test_(true);  // just to check if the test cases work ok
    //test_(false);
   try{ CreditCard c1(500); } catch (const char *) { succeed_(); } ;
   test_(c1.limit == 1000 or c1.limit == 2000 or c1.limit == 5000);

}

int main()
{
  CreditCardTest t;
  t.run();
 t.report();
}

g++  -o lab3  lab3.cpp test.cpp credit_card.cpp

cs Sept 30,2014



control structures - sequence, selection (decision), iteration (llop, repetition)
Datastructures  - stack, queue, list, hashtable
modularization -- creating classes

encapsulation - data and function together.
information hiding - public and private selectively.
Information Hiding
inheritance - reusing existing code. , modularizing..
polymorphism  (feature of inheritance ) One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class.
class is a programmer defined type.
5 exception handling
17 Linked structures
18 iterators as abstraction mechanisms
interface  (declarations, .h)
Implementation (definitions) .cpp

In . h file.
class CreditCard {

 private :
     int balance ; // part of implementation
 public :
    int getbalance(); // part of interface
};

1 .cpp implementation of class
2. .cpp implementation of the application

could be many declarations but only one definition.

next quiz on chapter 8.

exception handling
separate the detection of errors from the handling of errors.
also must cleanup resources (memory)

error types :compiler error/linker/logical/run-time
kinds of errors : slide 7.
syntax - int x
type - f("hello") if  void f(int); declaration

runtime error :
1. computer - eg. stack overflow, infiinite recursion. divide by zero
2. library -- library has exception handling
3. main program user code - exception handling


int area(int l, int w)
{
   return length*width;
}

int x1 = area(7); // type error
int x2  area("seven",2); // type error
int x3 = area (7,10);
int x4 = area(7.5, 10) ; // type error
int x = area(10, -7); // logic error

exception handling code : try, catch, throw.

cs Sep 29, 2014


loop invariant : by describing something that does not change (vary)
class invariant : something in the object that never changes. / features of the object that never change.

Object Z
try replacing by the following in cs116a.bat
qemu -m 512M -hda tinycore.img  -hdb texlive.img -drive file=fat:rw:../lab -rdir tcp:2222::22

cp lab2/packages.tex to lab3

put in packages.tex the following :
hyperref


to Do OZ
cd /mnt/sdb1/texlive

sudo tlmgr install oz
tce-load -wi wget

cd
unzip obectz.zip
cd objectz/
ls
latex oz.ins
ls
cd oz.sty ../lab3
cd lab3

cs Sept 26, 2014



review of quiz 2

1. array of 5 vectors (int) with empty elements.
     vector of 5 int elements each initialized to value zero.
2. requirement for aray/vector . memory allocated must be contiugous.. no space between elements.

 a + b == c + d  // all are r-values as nothing is modified..
1.assignment and cin >> x (input value
2.assignment statement
3.for (auto x: a)
the above 3 are l-values.
5. const in n;  can only initially constants can't give assign them later on.

constexpr int m = x; // not allowed. clear value must be known at compile time..
const int m = x ; // allowed

how to sort two vectors in parallel

vector<string> n1 = n;
vector<double = a

  sort(n.begin(), n.end())
   search for n[0] in n1
     use that index to find a1[i] in a2


1. mptopdf name_pairs.mp

2. src2latex lab2.cpp

3. pdflatex lab2.cpp.tex

cs Sept 23, 2014



Ch 8 : C++ overview
Ch 5 : exce topms
By now you should have read ch3 to ch 8
except 6 and 7

scope : limit to be as local as possible so identifiers can be reused and maintained more asily, debug more easily.

#include <iostream>
class A
{
 public :
     int c; // class scope
};

int x ; // global scope file
int main ()
{
   int y; // local scope
  A a1;

   for (int i =0; i <N ; i++)
      cout << i;  // statement scope

   std::cout << a1.c;  (first is namespace scope and teh second is clas scope
}
int f(int a) // local scope (function) (block)
{
   int b;
}
default x, 0 as it is a global variable but not y as it is a local variable.
What is the default initialization of objects of type A. use default constructor
Pg 266
Pg 260

while (double d; cin >> d)

Interface : declaration
.h
-- main application will use these by including thing include . h files
Implementation : definition
.cpp will also include the .h files to implement the interface.


vector<string> v; //initialized to empty

cannot do initialization in the class, definiing a type when we do the following

class A
{
   public :
         int c; / can't initialize
}

only in the default constructor.

cs Sept 22, 2014


/*{\section{Specification}
}*/
/*{\section{Design}
}*/
/*{\section{Implementation}
}*/


class Name_pairs
{
};
#include <vector>
int main(){
  name_pairs np;
  np.read_names();
  np.read_ages();

}
/*{\section{Test}
}*/

\begin{verbatim}
\end{verbatim}
/

cs Sep 17, 2014



Separate interface concerns with implementation.

interface : how to use libraries of functions (created by the systems programmers for use by application programmers)


Implementation : details of how it is implemented
data hiding (detail)

encapsulation : put the data and the functions that manipulate that data into objects.

instances of classes into objects.

---> download texlive.img , the new zip .check whether the .mp file would be deleted ... and the .cpp.
Chp 4 : 

Review :
20. organization of code, simplify, reuse/modify (source code, component .net), flexibility, efficiency, modularization
21. what you can do to an int that you cannot do to a string (switch,  -- case values need to be constant exprs)

case constexpr

int  -- concrete (finite values )

Integer --> Absract  (infinite values)

++ 

22. What you can do to a string that you cannot do to an int. s1.substr(pos,numofchar)
24. for (int i = 0; i <name.size(); i++)
              cout << name[i] ;

  name.operator[](i) ;

  array is a function : mapping an input value to an output value.

for (auto x: name)
  cout << x;

25. vector<char> alphabet(26)
initialized ot "" for string and 0 for int.

pushback appends at the end of the vector

vector<int> v1[6]; // array of 6 vectors each of which is empty with no elements..

while(true)  // infinite loop that does nothing
 ;
for (;;)
  ;

for(initialize/assignment/definition;condition;update)
  ;

Scope : what does scope mean:
26. adds a value to the end of the vector..
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

creates a whole new vector which has a size of +1 than the older one.

cs Sep 17, 2014 Lab








tce-load -wi perl5     for installing perl.

name_pairs.mp

mpost creates an incomplete version of a postscript file.
mptopdf requires perl

1. Do this in lab2 dir cp ../lab1/packages.tex .   (pdflatex)
2. ctrl-Alt-2 do this  hostfwd_add  tcp::2222-:22  (winscp)
3. create the .mp file 
4. //mpost name_pairs.mp
5.  mptopdf name_pairs.mp

class -- behaviours are methods

name_pairs
attributes -- data members
behaviour -- operations

In UML

names : vector<string>

C++
vector<string> names;

cs Sept 16, 2014



const : some values may not be known at run time cant change the value after being given initial values.
void use (int n)
{
  const int c2 = n + 7; // cant change after being set but can be set during run time
}

constexpr" all the vales are known at compile time and cant change during runtime.
constexpr double pi = 3.14;

Both static memory allocation.

Chapter 4:

Review
5.  compare and contrast expression and statement..
A statement is an expression followed by a semicolon..
4. An expression evaluates something or computation..
2. inputs to an computation cout << x . in this case cout and x.
ouputs of computation: cout<<x is cout object...

Final exam : What is the declaration of this function : cout <<x; or operator<<(cout, x);

ostream  &  operator<<(ostream &, int);

might ask the definition of this function as well.

^. lvalue

a + b

a = b //  a must be a lvalue..

lvalue (variable) are modifed. rvalue are the not modified values..

How many ways an lvalue can be modified ?

1.assignment and cin >> x (input value)
2.assignment statement
3.for (auto x: a)

x changes to each element ..

a is a collection vector array.

How do you avoid unnamed constant.. use symbolic constant.. constexpr double pi = 3.14;
18. cout << ch;
print numeric value of a character..
cout <<(int) ch;

cout<<static_cest<int> (ch);

19. char foo(int x); //declaration of function takes an integer and returns a char..

20. 1. modular, readable.repeatable

cs Sept 15, 2014



system stats file

in the home directory look at .profile using ls -a . Download the .profile from blackboard and replace this one..
rm *.zip
rm texlive*.gz

src2latex comments

/*{\section{Specification}
}*/
/*{\section{Design}
}*/
/*{\section{Implementation}
}*/


class Name_pairs
{
};

int main(){

}
/*{\section{Test}
}*/

interface in .h file and implementation in .cpp file

.h
class Name_pairs
{
   vector<string> names;
   vector<double> ages;
};

ADT -- Abstract data type  -- data members, member functions.


cp ../lab1/packages.tex .

create lab2 directory

editor name_pairs.mp

_matauml_defaults_mp := 1;
string metauml_defaultFont;
metauml_defaultFont :="cmr10";
input metaum1;
beginfig(0);
Class.N("Name Pairs")()();
drawObjects();
endfig;
end

mpost name_pairs.mp


src2latex working for lab2..

pdflatex -- packages.tex not found

cs Sep 11



operator overloading

ostream operator <<(ostream, int)

polymorphism

bitwise left shift

pass by value and pass by reference

pass by value : pass a copy of the argument to the function (in definition and declaration of the function)
pass by reference : pass location, memory address of the argument to the function.

operator <<(cout,x)

pass by reference : specify &

1. pass by value

int f(int x)

x=2

int f (int *p)  // pass by pointer , passing an address which is getting changed , pass by value but has the effect of pass by reference;;

as if we do p++; but the value that it is pointing to is not changed..

*p = 2



int f(int &x) // pass by reference

x = 2

argument is the "actual parameter" passed to the function
placeholder inside the function is the "formal parameter"

cout : variable or name of an object.

Abstraction : hide "details" : to make it easier to understand and use. hide details behind an interface.

interface : how do you use it
implementation : put the details how something is done.

cs Sept 10, 2014



Mount second hard drive
install drop bear
start drop bear services
set PATH for tools in .profile /mnt/sdb1/texlive/bin/i386-linux


install gsview textools



In qemu unix only put passwd under etc as backup remove everything else

edit .profile

add
export PATH=$HOME  and add the above mntcd

mount /mnt/sdb1
sudo /etc/init.d/dropbear
cd /mnt/sdb1/textools
./textools.sh
cd

go to tc exit options and reboot.

qemu -m 512M -hda tinycore.img -hdb texlive.img -redir tcp:2222::22

winscp  (allows to transfer files) scp client to scp server

ctrl alt 2 to get to qemu monitor..


editor lab1.cpp

cs Sep 9, 2014



ij = f(x)

ij has a memory address pointing to
f  -> dynamically allocate memory while the program is running , "run-time"


int f(); // declaration not definition;

int f()  // definition and declaration
{

  cin >> n ;
  new int ; // definition not declaration

}

static memory allocation versus dynamic memory allocation



cin << n;
new int[n] // legal...

class myclass; // declaration not definition

const int x = 0; identifier not variable.. chapter 3

operator >>(cin, n) evaluates to an object cin

operator +(n,2) evaluates to an integer object.

Review Chapter 3

3. int number ;  cin >> number;
4. newline  How many bytes of memory our  control character takes -- 1 bytes as \ is escape sequence in '\n'

assignment operator is right associative i.e. evaluated right to left y =(x=2),

(y+x)+2 left associative
5. Null terminator
6.

int a[5];
Or
vector <int> v;

for (int x: v)  // last line of assignment (19 in chapter 4).
cout <<x;

ideas of OOP

encapsulation

struct Data
{
   string name;
   double score;
}

then we could define vector<Data> v2;

cs Sep 8, 2014




src2latex

gsview

every submission must have : sections, diagrams, images of program beng tested, explantaion of code, source code.

Downloade compiler.tcz to download the gcc compiler.

Next add everything to path .

Create a lab 1 directory.

lab1.mp and lab.tex
mpost lab1.mp creates the diagram file

src2latex lab1.cpp
pdf2latex *.tex

gsview *.pdf

to create the file packages.tex touh packages.tex

cs Sep 4, 2014



identifier which does not have memory : void f()

int main()
{
   f() ; f is called, () is the functional operator
}

main is a definition while f is a declaration..

define f now :: list out what it does..

declaration " associate a type with an identifier"
definition " this also allocates memory", (creates an object)

string s; //definition

declaration which is not a definition for a variable ?

class Myclass; //declaration  only.
class Mathclass{ }; //declaration only

variable declaration  which is not a definition..

initialization -- gives the object a value.

[]  square brackets;

<> angle brackets
{} curly braces

type -unsafe allows implicit conversions
type-safe -- does not allow implicit conversions

g++ option for c++11
flag -std=c++11

REN project

create a new type : class Mathclass {  };
data definition not a declaration

void f(int x);  (not definition, only declaration of x here)
{
}
how to add code to the above so we allocate memory to it.
f(2); allocates memory.

struct s {int x ; }; creating a new type , declaring x to be an integer within it., still not an object and no memory allocated.

can't do struct s{int x=2;}; as this does not have a memory.

Example of string literal : "hello" object with no name
eg. of numeric literal : 2
character literal : 'a'

Not every unnamed object is a literal but all literals

unnamed object which is not an identifier.

new int; basically unnamed object but not an identifier. allocates memory.

new int(2); allocating memory and initialize this.. initializing an unnamed object.

cout << new int(2) ;; would display the memory address where the object was allocated.
cout << * new int(2) ;   dereferencing operator..

int *p = new int(2);

cout<<*p;

compiletc from the list of apps install.

cs Sept 3, 2014



qemu -hda tinycore.img -hdb texlive.img

(two creaed sda1 and sdb1)


two hard drives. one that has tools on it and one that we are doing the work on


documentation -> latex >> pdflatex (pdf), src2latex

metapost for diagrams.


tinycore loaded onto a virtual machine.

qemu -hda tinycore.img -hdb texlive.img

winscp  (allows to transfer files) scp client to scp server

src

Downloaded the qemu.img and ran the qemu command to create hard disks..

to start the dropbear server (after installing this app)
to start the server : /etc/init.d/dropbear start

ctrl alt 2 to get to qemu monitor..

(qemu)  hostfwd_add  tcp::2222-:22

password ( to change password for tc in the shell
download winscp login and run it inside it modify the following parameters and login
 winscp for login  (tc - login, server localhost, scp , 2222 port)

download src2latex and then upload it into the unix server using winscp. 

unzip and run the make command.

PATH=$PATH:/mnt/sdb1/texlive/bin/i386-linux

create a .cpp file
src2latex .cpp will create a .tex file of it.

pdflatex lap1.tex

pdfreader : evince  ghostscript

postscript

tce-load -wi ghostscript

write c++ code
screen capture of it running
diagram of it

cs pre sep3

Everything in Chap 3

' ' 1 byte

1st lab is chap 4


" " two bytes as this is a string and the last char is a null.

"hello" 6 bytes

program defined type  --- > string


C++ keywords
. 1st quiz ?

2nd edition of the book.. talks about C++ 11.

understand the meaning of the list given here for the quiz : http://en.cppreference.com/w/cpp/keyword

Chap 4: Vector..

safe conversions : int 4 bytes, double 8 bytes

the bottleneck in architecture discussion ??



tc@box: Cd Chapter03

editor chapter.3.9.2.cpp
istream

cin >> d >> e chaining..

non-zero is true but zero is false

while(cin>>d)

if returns anything other than zero than true.


char b2{48} narrowing notation. to make sure narrowing erros don't happen. prevents narrowing conversions.

universal and uniform initialization

cs Aug 25

http://www.ideone.com/
http://codepad.org/zXdNZRn7

http://sourceforge.net/projects/dev-cpp/ OLD

http://quincy-2005.software.informer.com/1.3/   2005


// This program calculates the user's pay
#include <iostream>

using namespace std;
int main()
{
  double hours, rate, pay;

  // Get the number of hours worked
  cout << " How many hours did you work?";
  cin >> hours;

  // Get the hourly pay rate.
  cout << " How much do you get paid per hour?";
   cin >> rate;

  // Calculate the pay.
  pay = hours * rate;

  // Display the pay
  cout << " You have earned $" << pay << endl;
  return 0;
}

Homework 1 : ?
Homework 2:  ? Checkpoint
Algorithm workbench
Predict the result
read chapter 2..