User Tools

Site Tools


opus:fall2011:rrichar8:part3

Part 3

Entries

November 12, 2011

  • Working on Keywords today. Most of the words are dealing with C++
  • This is giving me exposure to C++ programming and syntax.
  • This is my first experience with demonstrating C++, it's taking quite a bit of research
  • I have been combing the internet and the textbook looking for definitions and some examples.
  • Still deciding which projects to undertake this month, will be incorporating Classes into the projects.

November 17, 2011

Continuing to work on Keywords today, including: Operator Overloading, Function Overloading, Classes and Objects, Const-Volatility Specifiers. Gathering information about different projects to complete.

  • Finding that there are numerous sources of information, but it's a bit difficult sorting on the info.
  • This is significant because it gives me a good chance to understand what they mean and how they are used.
  • Noticing that in C++ there are many new syntax words to deal with and many more operations.
  • Finding good examples that have fairly short code is a bit difficult.
  • Using the internet and checking the textbook to find good definitions.
  • Gathering information to start on my project today. Still undecided which projects I will undertake.

November 29, 2011

Finishing work on Keywords today. Gathering additional examples and information about the keywords. Working on project today, gathering data necessary to complete the project.

  • Since working on the keywords I've learned to use these words in the C and C++ programming.
  • Working on my project. Finding that it's a bit difficult to compile without errors. Working on eliminating them.
  • Having a bit of trouble understanding how to properly implement classes into my project.
  • Gaining a pretty good knowledge of syntax and better understanding of C and C++ programming

November 30, 2001

  • Finishing up the Keyword section today and continuing to work on my project.
  • Continuing to work on class and objects. Finding good programming examples is a bit difficult.
  • Still having some problems with syntax and the different uses between C and C++ programming.
  • Learning to incorporate what is in the textbook into actual programming has been a task at times.

cprog Topics

STL (Standard Template Library) [C++]

The STL is a collection C++ libraries that allow you to use several well known kinds of data structures with out having to program them.
The Standard Template Library is a collection of classes that provide templated containers, algorithms, and iterators.
They are designed so that the code runs efficiently. The compiler does most of the work of generating the efficient implementations.
The STL includes the classes vector, list, deque, set, multiset, map, multimap, hash_set, hash_multiset, hash_map, and hash_multimap. Each of these classes is a template, and can be instantiated to contain any type of object.

   Container class templates
   Sequence containers:
   vector	Vector (class template )
  deque	Double ended queue (class template )
  list	List (class template )
  Container adaptors:
  stack	         LIFO stack (class template )
  queue	         FIFO queue (class template )
  priority_queue	Priority queue (class template)
  Associative containers:
  set 	   Set (class template )
  multiset	   Multiple-key set (class template)
  map	           Map (class template )
  multimap	   Multiple-key map (class template )
  bitset	           Bitset (class template)

Templates [C++]

C++ provides two kinds of templates: class templates and function templates.
Templates allow functions and classes to operate with generic types.
This allows a function or class to work on many different data types without being rewritten for each one.
Declaration should start with the keyword template. A parameter should be included inside angular brackets.
The parameter inside the angular brackets, can be either the keyword class or typename. This is followed by the class body declaration with the member data and member functions.
One C++ Class Template can handle different types of parameters.
Templates reduce the effort on coding for different data types to a single set of code.
Testing and debugging efforts are reduced.
Compiler generates classes for only the used types.
If the template is instantiated for int type, compiler generates only an int version for the c++ template class.

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b); 

Abstract Base Class [C++]

An abstract class is a class that is designed to be specifically used as a base class.
An abstract class contains at least one pure virtual function.
Declare a pure virtual function by using a pure specifier in the declaration of a virtual member function in the class declaration.
You can declare pointers and references to an abstract class.
You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class.
Not all methods in an Abstract Base Class must be pure virtual, some may have an implementation. This is especially true when creating a base class encapsulating a process common to a lot of objects.

 An abstract class contains at least one pure virtual function.    

You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.

The following is an example of an abstract class:

class AB {
public:
  virtual void f() = 0;
};

Exception Handing (throw, try, catch) [C++]

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in program by transferring control to special functions called handlers.
To catch exceptions you must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block.
Exception handlers are declared with the keyword catch, which must be placed immediately after the try block.
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has default and copy constructors, operators and destructors, plus an additional virtual member function.
C++ provides three keywords to handle an exception.
Trying the normal flow:
To deal with the expected behavior of a program, use the try keyword as in the following syntax:
try {Behavior}
Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is:
catch(Argument) {WhatToDo}
Throwing an error: There are two main ways an abnormal program behavior is transferred from the try block to the catch clause. This transfer is actually carried by the throw keyword. Unlike the try and catch blocks, the throw keyword is independent of a formal syntax but still follows some rules.

Operator Overloading [C++]

You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention.
To overload the + operator for your class, you would provide a member-function named operator+ on your class.

The following set of operators is commonly overloaded for user-defined classes:

  = (assignment operator)
  + - * (binary arithmetic operators)
  += -= *= (compound assignment operators)
  == != (comparison operators)

The assignment operator has a signature like the example below and the = operator takes a const-reference to the right hand side of the assignment:
In other words, assignment is right-associative. The last assignment operation is evaluated first, and is propagated leftward through the series of assignments.

class MyClass {
public:
  ...
  MyClass & operator=(const MyClass &rhs);
  ...
}
MyClass a, b;
...
b = a;   // Same as b.operator=(a);

The number of operands to a function is fixed; that is, a binary operator takes two operands, a unary only one, and you can't change it. The same is true for the precedence of operators too; for example the multiplication operator is called before addition. There are some operators that need the first operand to be assignable, such as : operator=, operator(), operator[] and operator→, so their use is restricted just as member functions(non-static), they can't be overloaded globally.

Function Overloading [C++]

C++ allows specification of more than one function of the same name in the same scope.
You overload a function name f by declaring more than one function with the name f in the same scope.
When you call an overloaded function named f, the correct function is selected by comparing the argument list of the function call with the parameter list of each of the overloaded candidate functions with the name f.
Overloaded functions enable programmers to supply different semantics for a function, depending on the types and number of arguments.

// overloaded function
#include <iostream>
using namespace std;
 
int operate (int a, int b)
{
  return (a*b);
}
float operate (float a, float b)
{
  return (a/b);
}
int main ()
{
  int x=5,y=2;
  float n=5.0,m=2.0;
  cout << operate (x,y);
  cout << "\n";
  cout << operate (n,m);
  cout << "\n";
  return 0;
} 

There two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called.

Classes and Objects (Constructor, Destructor, Members) [C++]

A class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void.
Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution.
Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created.
The destructor fulfills the opposite functionality.
It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.
A destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value.
The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.

Classes are generally declared using the keyword class, with the following format: The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

class class_name {
  access_specifier_1:
    member1;
  access_specifier_2:
    member2;
  ...
  } object_names;

An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire: Private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

class X {
public:
  // Constructor for class X
  X();
  // Destructor for class X
  ~X();
};
 

A destructor takes no arguments and has no return type. Its address cannot be taken.

Compiler, Preprocessor, Flags, Assembler, Linker

A C++ compiler is a computer program that converts a C++ program from our form to a form the computer can read and execute. The computer works in binary which is a string of 1's and 0's thatcan be very quickly and accurately understood by the computer. The original C++ program is called the “source code”, and the resulting compiled code produced by the compiler is usually called an “object file”.

  % gcc one.c -o one

This tells the compiler to run the preprocessor on one.c, compile it and then link it to create an executable called one. The -o option states that the next word on the line is the name of the binary executable file (program).

One or more object files are combined with predefined libraries by a linker, sometimes called a binder, to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled “object code” that provides operations that are done repeatedly by many computer programs.

Preprocessor directives are lines included in the code that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements.
These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\

When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++, it simply replaces any occurrence of identifier by replacement.

#define TABLE_SIZE 100
int table1[TABLE_SIZE];
int table2[TABLE_SIZE]; 

After the preprocessor has replaced TABLE_SIZE, the code becomes equivalent to:

int table1[100];
int table2[100]; 

A flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program. For example, in a message being exchanged by two programs, a three-bit flag's field or data area might be set to different configurations:

001 (meaning “self-contained message”)
011 (meaning “one of several pieces of data in this message”)
111 (meaning “last piece of data in this message”)

An assembly language is a low-level programming language for computers, and it implements a symbolic representation of the machine codes and other constants needed to program a given CPU architecture.
A utility program called an assembler is used to translate assembly language statements into the target computer's machine code. It takes the assembly source code and produces an assembly listing with offsets. The assembler program takes each program statement in the source program and generates a corresponding bit stream or pattern (a series of 0's and 1's of a given length).
The assembler takes as its source code an assembly language program; this is a file of ASCII characters which is used to produce machine code.
Typically a modern assembler creates object code by translating assembly instruction mnemonics into opcodes, and by resolving symbolic names for memory locations and other entities.
In the earliest computers, programmers actually wrote programs in machine code, but assembler languages or instruction sets were soon developed to speed up programming. Today, assembler programming is used only where very efficient control over processor operations is needed. It requires knowledge of a particular computer's instruction set.

If a source file references library functions or functions defined in other source files the link editor combines these functions (with main()) to create an executable file.
Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker may find undefined functions (commonly, main itself). During compilation, if the compiler can not find the definition for a particular function, it would just assume that the function was defined in another file.
The job of the linker is to link together a bunch of object files (.o files) into a binary executable. This includes both the object files that the compiler created from your source code files as well as object files that have been pre-compiled for you and collected into library files.
Like the preprocessor, the linker is a separate program. Also like the preprocessor, the linker is invoked automatically for you when you use the compiler. The normal way of using the linker is as follows:

  % gcc one.o two.o three.o -o myprogram

This line tells the compiler to link together three object files (one.o, two.o, and three.o) into a binary executable file named myprogram.

Access Control (Public, Protected, Private, Friend) [C++]]

With C++, you can specify the level of access to member data and functions. There are three levels of access: public, protected, and private. The default access to class members (members of a class type declared using the class keyword) is private; the default access to struct and union members is public. For either case, the current access level can be changed using the public, private, or protected keyword.

The private keyword specifies that those members are accessible only from member functions and friends of the class. This applies to all members declared up to the next access specifier or the end of the class.
When preceding the name of a base class, the private keyword specifies that the public and protected members of the base class are private members of the derived class.
Default access of members in a class is private. Default access of members in a structure or union is public.
Default access of a base class is private for classes and public for structures. Unions cannot have base classes.

  private:
     [member-list]
  private base-class

The protected keyword specifies access to class members in the member-list up to the next access specifier (public or private) or the end of the class definition. Class members declared as protected can be used only by the following:

Member functions of the class that originally declared these members.
Friends of the class that originally declared these members.
Classes derived with public or protected access from the class that originally declared these members.
Direct privately derived classes that also have private access to protected members.

When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of its derived classes.
Protected members are not as private as private members, which are accessible only to members of the class in which they are declared, but they are not as public as public members, which are accessible in any function.
Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

   protected:
     [member-list]
   protected base-class

When preceding a list of class members, the public keyword specifies that those members are accessible from any function. This applies to all members declared up to the next access specifier or the end of the class.
When preceding the name of a base class, the public keyword specifies that the public and protected members of the base class are public and protected members, respectively, of the derived class.
Default access of members in a class is private. Default access of members in a structure or union is public.
Default access of a base class is private for classes and public for structures. Unions cannot have base classes.

  public:
     [member-list]
  public base-class

Friends are functions or classes declared with the friend keyword.
A class grants access privileges to its friends. Normally a developer has technical control over both the friend and member functions of a class (else you may need to get permission from the owner of the other pieces when you want to update your own class).
You can declare friend functions or friend classes to access not only public members but also protected and private class members.

   friend class aClass;

Friend declarations can go in either the public, private, or protected section of a class–it doesn't matter where they appear. In particular, specifying a friend in the section marked protected doesn't prevent the friend from also accessing private fields

  class Converter 
  {
  private: 
  int data;
  int bass;
  // ...
  friend class Binary; // class Binary can now access data directly
  };

Scope (Block, Local, Global, File)

Scope refers to identifiers, that is types, functions, classes and variables and is that part of the source code where the particular identifier is visible.

Variables have a finite life-time a program executes. The scope of an object or variable is simply that part of a program in which the variable name exists or is visible to the compiler.
A variable’s scope determines who can see the variable, and how long it lives for. Variables declared inside a block are called local variables, and local variables have block scope (also called local scope). Variables with block scope can be accessed only within the block that they are declared in, and are destroyed as soon as the block ends.
Because each function has it’s own block, variables in one function can not be seen from another function.
Blocks allow multiple statements to be used wherever a single statement can normally be used.

Local scope is activated when the flow of the program enters it, and deactivated when it leaves it. Objects in local scope are constructed whenever their definition is encountered, and destroyed when the scope is exited. Such objects are also called automatic (because they are automatically created and destroyed), or stack objects (because they occupy memory that is allocated on the program's stack).
Local scopes are usually, but not always, delimited by the curly braces.

The default scope is defined as global scope, this is commonly used to define and use global variables or other global constructs (classes, structure, functions, etc), this makes them valid and visible to the compiler at all times. It is considered a good practice to use a namespace scope for hiding the otherwise global elements, without removing their validity.
Global is usually outside of the curly braces.

In C++, a declaration of an object at file scope is just a declaration (and not also a definition) if and only if it has an explicit extern keyword specifier and no initializer.

Each object declared at file scope must be defined exactly once. All but one declaration must have both an explicit extern keyword specifier and no initializer.

Any name declared outside all blocks or classes has file scope. It is accessible anywhere in the translation unit after its declaration. Names with file scope that do not declare static objects are often called global names.
In C++, file scope is also known as namespace scope.

lab46:~$ cd src
lab46:~/src$ gcc -o hello hello.c
lab46:~/src$ ./hello
Hello, World!
lab46:~/src$ 

cprog Objective

Objective

I've been bpending a lot of time reading the textbook and reading online. On my first solo project I worked on a Base Conversion program that converts a decimal number into other BASES, and now I'm working on a simple C++ program that will convert miles to kilometers. I'm also working on a small program using VECTORS.

Method

I have been continuing to learn the syntax and operations needed for C++ Programming. Been working on the assigned keywords and topics which are a good way to learn new ways to write and utilize the C++ code.

Measurement

After spending many hours, weeks on the miles conversion program and ironing out all the kinks, I've gotten it to compile properly and run without errors.

Analysis

Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.

  • I did get the program to run and compile properly after numerous attempts and failures.
  • There is a lot of room for improvement and I hope that the next project goes smoother.
  • I would like to see more information on actual procedures in the textbook that is used in the course.
  • Though there is considerable resources available online, many are not self explanatory and require further research.
  • I would like to see a book that outlines the course and has better examples of code and procedures.

Experiments

Experiment 1

Question

What is the question you'd like to pose for experimentation? State it here.

Resources

Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.

Hypothesis

Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.

State your rationale.

Experiment

How are you going to test your hypothesis? What is the structure of your experiment?

Data

Perform your experiment, and collect/document the results here.

Analysis

Based on the data collected:

  • was your hypothesis correct?
  • was your hypothesis not applicable?
  • is there more going on than you originally thought? (shortcomings in hypothesis)
  • what shortcomings might there be in your experiment?
  • what shortcomings might there be in your data?

Conclusions

What can you ascertain based on the experiment performed and data collected? Document your findings here; make a statement as to any discoveries you've made.

Experiment 2

Question

What is the question you'd like to pose for experimentation? State it here.

Resources

Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.

Hypothesis

Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.

State your rationale.

Experiment

How are you going to test your hypothesis? What is the structure of your experiment?

Data

Perform your experiment, and collect/document the results here.

Analysis

Based on the data collected:

  • was your hypothesis correct?
  • was your hypothesis not applicable?
  • is there more going on than you originally thought? (shortcomings in hypothesis)
  • what shortcomings might there be in your experiment?
  • what shortcomings might there be in your data?

Conclusions

What can you ascertain based on the experiment performed and data collected? Document your findings here; make a statement as to any discoveries you've made.

Retest

If you're doing an experiment instead of a retest, delete this section.

If you've opted to test the experiment of someone else, delete the experiment section and steps above; perform the following steps:

State Experiment

Whose existing experiment are you going to retest? Prove the URL, note the author, and restate their question.

Resources

Evaluate their resources and commentary. Answer the following questions:

  • Do you feel the given resources are adequate in providing sufficient background information?
  • Are there additional resources you've found that you can add to the resources list?
  • Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment?
  • If you find a deviation in opinion, state why you think this might exist.

Hypothesis

State their experiment's hypothesis. Answer the following questions:

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?
  • What improvements could you make to their hypothesis, if any?

Experiment

Follow the steps given to recreate the original experiment. Answer the following questions:

  • Are the instructions correct in successfully achieving the results?
  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?
  • Would you make any alterations to the structure of the experiment to yield better results? What, and why?

Data

Publish the data you have gained from your performing of the experiment here.

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author?
  • Can you explain any deviations?
  • How about any sources of error?
  • Is the stated hypothesis adequate?

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment?
  • Do you feel the experiment was adequate in obtaining a further understanding of a concept?
  • Does the original author appear to have gotten some value out of performing the experiment?
  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).
opus/fall2011/rrichar8/part3.txt · Last modified: 2011/12/03 18:01 by rrichar8