Table of Contents

Part 3

Entries

November 12, 2011

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.

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.

November 30, 2001

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.

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:

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:

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:

Hypothesis

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

Experiment

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

Data

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

Analysis

Answer the following:

Conclusions

Answer the following: