Friday, September 10, 2010

Source Codes: Big 3, Inheritance, Polymorphism, Separate Compilation, Abstract Class

I wrote this a few days ago.

Pet.h
#ifndef PET
#define PET

class Pet{ // Abstract Class
public:
 Pet(std::string name);
 Pet(); // Constructor Overloadding
 void walk(int pace);
 virtual void makeSound() = 0; // Abstract method
 virtual void favoriteFood() = 0;

protected:
 int age;
 std::string name;
 std::string hairColor;
};
#endif

Pet.cpp
#include <iostream>
#include <string>
#include "Pet.h"
using namespace std;

Pet::Pet(string name):name(name){
 cout << "In Pet's Constructor\n";
}
Pet::Pet(){
 string name;
 cout << "The pet has no name, will you please give it a name?\n>>";
 cin >> name;
 this->name = name;
 cout << "Awesome, the pet seems to love the name, " << name << endl;
}
void Pet::walk(int pace){
 cout << name << " walks ";
 if(pace>1)
  cout << "paces";
 else
  cout << "pace";
 cout << ".\n";
}

Dog.h
#ifndef DOG
#define DOG

#include "Pet.h"

class Dog : public Pet{
public:
 Dog(std::string name);
 void makeSound();
 void favoriteFood();

};
#endif

Dog.cpp
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;

Dog::Dog(string name):Pet(name){}

void Dog::makeSound(){
 cout << "Woff\n";
}

void Dog::favoriteFood(){
 cout << this->name << " loves to chew bones.\n";
}

Cat.h
#ifndef CAT
#define CAT

#include "Pet.h"
#include <vector>

class Cat : public Pet{ // Inheritance
public:
 Cat(std::string name);
 Cat();
 Cat(const Cat& cloneCat); // Copy Constructor
 ~Cat(); // Destructor
 Cat& operator=(const Cat& anotherCat);
 void makeSound();
 void favoriteFood();
 void eat(std::string food);

 void ate();
private:
 void copy(const Cat& anotherCat);
 std::vector<std::string> stomache;
};

#endif

Cat.cpp
#include <iostream>
#include <string>
#include "Cat.h"
using namespace std;

Cat::Cat(string name): Pet(name){}

Cat::Cat(): Pet(){}

Cat::Cat(const Cat& cloneCat) : Pet(cloneCat.name){
 copy(cloneCat);
 cout << "In Cat's Copy Constructor\n";
}

Cat::~Cat(){
 stomache.clear();
}

Cat& Cat::operator=(const Cat& anotherCat){
 if(this != &anotherCat){ //self check
  copy(anotherCat);
 }

 return *this;
}

void Cat::makeSound(){
 cout << "Meow\n";
}

void Cat::favoriteFood(){
 cout << this->name << " loves to eat fish.\n";
}

void Cat::eat(string food){
 cout << name << " gobbles up " << food << ".\n";
 stomache.push_back(food);
}

void Cat::copy(const Cat& cloneCat){
 this->age = cloneCat.age;
 this->hairColor = cloneCat.hairColor;

 for(size_t i = 0; i < cloneCat.stomache.size(); ++i){ // deep copying
  this->stomache.push_back(cloneCat.stomache.at(i));
 }
}

void Cat::ate(){
 cout << name << " ate: \n";
 for(int i = 0; i < stomache.size(); ++i){
  cout << "\t" << i << ". " << &stomache[i] << ": " << stomache[i] << endl;
 }

}

main.cpp
#include <iostream>
#include "Cat.h"
#include "Dog.h"
using namespace std;

int main(){
 Cat neko("neko mimi");
 Dog wan("wan chan");
 Pet* aPet = new Cat("Cat King");

 cout << "The following is the polymorphism.\n";
 aPet->makeSound();
 aPet->favoriteFood();
// Cat meowchan;

 cout << "neko's address: " << &neko;
 for(int i = 0; i <= 5; ++i)
  neko.eat("fish");
 neko.ate();
 Cat kawaii = neko;
 cout << "kawaii's address: " << &kawaii;
 kawaii.ate();

 return 0;
}

Object Oriented Language: C++, Common Operators

Arithmetic Operators
Name Symbol Syntax
Addition
+ 1 + 2
Subtraction
- 3 - 1
Multiplication
* 6 * 6
Division
/ 9 / 3
Modulo
% 100 % 3
Pre-Increment
++ ++x
Post-Increment
++ x++
Pre-Decrement
-- --x
Post-Decrement
-- x--
Assignment
= x = 3

Compound Assignment
Name Symbol Syntax
Addition Assignment
+= x += 2
Subtraction Assignment
-= x -= 1
Multiplication Assignment
*= x *= 6
Division Assignment
/= x /= 3
Modulo Assignment
%= x %= 3
Bitwise AND Assignment
&= x &= 3
Bitwise OR Assignment
|= x |= 3
Bitwise XOR Assignment
^= x ^= 3
Bitwise left shift Assignment
<<= x <<= 3
Bitwise right shift Assignment
>>= x >>= 3

Relation and Equality Operators
Name Symbol Syntax
Equality
== x == y
Inequality
!= x != y
Greater Than
> x > y
Less Than
< x < y
Greater Than or Equal to
>= x >= y
Less Than or Equal to
<= x <= y

Logical Operators
Name Symbol Syntax
Logical Negation (not)
! !x
Logical AND
&& x && y
Logical OR
|| x || y

Of course, there are other operators, but they are out of scope of this lesson. We should all know the obvious, so basic arithmetic operators are not discussed. I'll start off with the modulo operator, %. It's easier to start with some simple examples.
int x = 100;

cout << x / 3; // will output 33
cout << x % 3; // will output 1

cout << x / 2; // will output 50
cout << x % 2; // will output 0

cout << x / 19; // will output 5
cout << x % 19; //will output 5

cout << 20 / x; // will output 0
cout << 20 % x; //will output 20
In C++, 100 / 3 = 33. This is called integer division, it is also the quotient of the division. 100 % 3 = 1. Modulo returns the remainder after computing the integer division. 100 / 3 = quotient, 33 100 % 3 = remainder, 1 If you still do not get the concept, try to write a program practicing integer division and modulo operation. Pre and post increment. x++ is a simplified version of writing x = x + 1, or x += 1. The difference of pre and post increment is the order of evaluation of the expression. Pre-increment does the increment before the expression is evaluated. Post-increment does the increment after the expression is evaluated.
int x = 5;
cout << ++x; // x is incremented, then outputs 6
// x is 6 now
cout << x++; // outputs 6, then x is incremented
cout << x; // outputs 7 since it was incremented in the last statement.

Addition assignment, +=. For instance, x += 2, can be rewritten as x = x + 2. The concept is the same with all the compound assignment operators.

Operators used for conditions:
int x = 25;
if( (x >= 10) && (x <= 99) ){
    cout << "x is greater than or equal to 10 AND less than or equal to 99" << endl;
    if( x != 50){
        cout << "x is not equal to 50";
        if ( x == 25 ){
            cout << "x is equal to 25";
        }
    } 
}
Please study short-circuit evaluation by yourself.

Thursday, September 9, 2010

Object Oriented Language: C++, Control Flow



Control flow statements controls the flow of execution in a program. The control flow statement discuss here will not contain any loops; they are, however, taught in the next lesson.

Let's say you have to write a simple program that answers true/false to the given string.
"3+3=6" is the string, for example.
How do you write such a program? Let's not worry about the actual implementation of the program, and instead, look at the design and logic of the program. The program has to read in the string and decide if 3+3=6 is true or false. This decision is based on the result of the given condition. If the condition is true, the program outputs "true", else the program outputs "false". Simple. The way we tell our program to do that is by using the if/else statement.
if ( 3+3 == 6 ){
    cout << "true";
}else{
    cout << "false";
}
Notice in line 1, I wrote 3+3 == 6, instead of what is expected to be: 3+3 = 6. Since = operator is dedicated to assignment, the C programming language creator chose, Dennis Ritchie, to use the == instead to check for equality. The code itself should be self-explanatory and easy to comprehend.

The syntax & semantics for the if/else statement is as follow:
if ( condition ){
    // execute this block if the condition is evaluated to true
}
else{
    // execute this block if the condition is evaluated to false
}


if statement




if/else statement

If you only want to check if the condition is true, then just use the if statement. If there are multiple conditions to be checked, one can use the following syntax:
if(condition1){
... statement
}else if(condition2){
...statement
}
.
.
.
else if(conditionN){
...statement
}else{
...statement
}


if/else if/else statement



If you have many conditions to check the if/else if/else may be a little burden for most people, therefore, switch is specialized to do that kind of operations.
The syntax & semantics for switch is as follow:
switch(condition | int | char){
    case value1:
        //...statements
        break;
    case value2:
        //...statements
        break;
    ...
    ...
    ...
    case valueN:
        //...statements
        break;
    default: // optional, default case if none of the above matches
        //...statements
        break;
}


switch statement


There is a few things to note about a switch statement, I'll go over them with you one by one. switch can only take in a boolean value, integer, or a character, which means the following is prohibited:
string msg = "hi";
switch(msg){
    case "hi": // This is not allowed!
        ...
    ...
}

char aChar = 'x';
switch(aChar){ // example 1
    case 'a':
    ...
    ...
    ...
    case 'x':
        cout << "x";
        break;
    ...
    ...
}


int x = 10;
switch (x){ // example 2
    case 1:
        cout << "x = 1";
        break;
    case 2:
    case 3:
    case 4:
        cout << "x > 1 && x < 5";
        break;
    case 5:
        cout << "x = 5";
        break;
    case 6:
    case 7:
    case 8:
    case 9:
        cout << "x > 5 && x < 10";
        break;
    case 10:
        cout << "x = 1";
        break;
    default:
        cout << "x is not in between 1-10";
        break;
}
Another thing to note is that each case are ended with a break statement, the control of flow will flow through to other cases if it were not to be terminated by a break statement. For the second example above, if x were to be initialized to 6, the control flow will flow to case 6, continuing to 7 ,8, and finally terminated by the break statement in the case 9.

Source Codes: Vector and Iterator

I have been practicing operator overloading, friend method, template, separate compilation, vector and iterators by writing up a sample vector class. Although this is not as great as the STL's templated container class, vector, one can look at this source code to get a feel of the inner structure of the vector class' coded. :)

A minimal commentary is available to understand the code.
Note: the indentation shown here are like 1-2 space.
Vector.h
#ifndef VECTOR_H
#define VECTOR_H

template <class Type>
class Vector{
public:
 Vector();
 void push_back(const Type& entry);
 void pop_back();
 void clear();
 void resize(int newSize);
 int size() const;

 /* read */
 Type operator[](int index) const;

 /* write */
 Type& operator[](int index);

 /* Nested Iterator class */
 class Iterator{

  /* Binary operator should be made a function */
  friend bool operator==(const Iterator& a, const Iterator& b){
   return a.current == b.current;
  }

  friend bool operator!=(const Iterator& a, const Iterator& b){
   return !(a == b); //return !operator==(a, b);
  }

 public:
  Iterator(Vector* parent = NULL);

  /* Advances the iterator by an offset */
  Iterator& operator+(int offset);
  Iterator& operator-(int offset);
  Iterator operator++();
  Iterator operator++(int);
  Iterator operator--();
  Iterator operator--(int);
  Type operator*();
  Type* operator->() const;

  /* sets the current pointer with the given pointer */
  void setCurrent(Type* given);

 private:
  Type* current;
 };

 Iterator begin();
 Iterator end();

private: 
 Type* data;
 int theSize, capacity;
 Iterator iterator;
};

#endif

Vector.cpp
#include <iostream>
#include "Vector.h"

template <class Type>
Vector<Type>::Vector():theSize(0), capacity(10){
 data = new Type[capacity];
 iterator = Iterator(this);
}

template <class Type>
void Vector<Type>::push_back(const Type& entry){
 if(theSize == capacity)
  resize(theSize*2); //doubles the size of the vector if capacity is reached
 data[++theSize] = entry; //increments the size, and adds the new entry
}

template <class Type>
void Vector<Type>::pop_back(){
 if(theSize == 0)
  return;
 data[theSize] = NULL;
 --theSize;
}

template <class Type>
void Vector<Type>::clear(){
 while(theSize > 0)
  pop_back();
}

/* Reduce the size to the newSize if current capacity is smaller greater than the newSize. 
   Otherwise grow the capacity to the demanded newSize, deep copying all the elements in existence. */
template <class Type>
void Vector<Type>::resize(int newSize){
 if(newSize > capacity){
  Type* backup = data;
  data = new Type[newSize];
  capacity = newSize;
  int j = theSize;
  theSize = 0;

  for(int i = 0; i < j; ++i){
   push_back(backup[i+1]);
  }
 }
 else{
  while(newSize < theSize)
   pop_back();
 }
}

template <class Type>
int Vector<Type>::size() const{
 return theSize;
}

template <class Type>
Type Vector<Type>::operator[](int index) const{
 return data[index+1];
}

template <class Type>
Type& Vector<Type>::operator[](int index){
 return data[index+1];
}

/* returns the Iterator that points to the first element in the data dynamic array */
template <class Type>
typename Vector<Type>::Iterator Vector<Type>::begin(){
 iterator.setCurrent(data + 1);
 return iterator;
}

/* returns the Iterator that points to the last element in the data dynamic array */
template <class Type>
typename Vector<Type>::Iterator Vector<Type>::end(){
 iterator.setCurrent(data + theSize + 1);
 return iterator;
}

/*********************** Iterator /***********************/

//template <class Type>
//bool operator==(const typename Vector<Type>::Iterator& a, const typename Vector<Type>::Iterator& b){
// return a.current == b.current;
//}
//
//template <class Type>
//bool operator!=(const typename Vector<Type>::Iterator& a, const typename Vector<Type>::Iterator& b){
// return !(a == b);
//}

template <class Type>
Vector<Type>::Iterator::Iterator(Vector* parent = NULL){
 current = (parent) ? (parent->data + 1) : NULL; // sets current to NULL if the parent pointer given is NULL.
}

template <class Type>
typename Vector<Type>::Iterator& Vector<Type>::Iterator::operator+(int offset){
 current += offset; // Pointer Arithmetic
 return *this;
}

template <class Type>
typename Vector<Type>::Iterator& Vector<Type>::Iterator::operator-(int offset){
 current -= offset; // Pointer Arithmetic
 return *this;
}

template <class Type>
typename Vector<Type>::Iterator Vector<Type>::Iterator::operator++(){ //pre-increment
 ++current;
 return *this;
}

template <class Type>
typename Vector<Type>::Iterator Vector<Type>::Iterator::operator++(int){ //post-increment
 Iterator backup = *this;
 ++current;
 return backup;
} 

template <class Type>
typename Vector<Type>::Iterator Vector<Type>::Iterator::operator--(){ //pre-decrement
 --current;
 return *this;
}

template <class Type>
typename Vector<Type>::Iterator Vector<Type>::Iterator::operator--(int){ //post-decrement
 Iterator backup = *this;
 --current;
 return backup;
} 

template <class Type>
Type Vector<Type>::Iterator::operator*(){
 return *current;
}

template <class Type>
Type* Vector<Type>::Iterator::operator->() const{
 return current;
}

template <class Type>
void Vector<Type>::Iterator::setCurrent(Type* given){
 current = given;
}

main.cpp
/* This source code is written by Wensheng Chen, anyone can freely redistribute the code under GPL. */
#include <iostream>
#include "Vector.h"
#include "Vector.cpp"
/* Note: Template and separate compilation do not work well together, 
one has to include both the header and the implementation file to 
achieve the goal of separation compilation. */

using namespace std;

class Cat{
 friend ostream& operator<<(ostream& os, const Cat& cat){
  os << cat.age;
  return os;
 }

public:
 Cat(){}
 Cat(int age):age(age){}
 string meow(){
  return "meow\n";
 }

private:
 int age;
};

int main(){
 Vector<Cat> number;
 for(int i = 0; i < 100; ++i){
  number.push_back(i);
 }

 for(int i = 0; i < number.size(); ++i){
  cout << number[i] << endl;
 }

 cout << "iterator begins now!!\n\n";
 int i = 0;
 for(Vector<Cat>::Iterator iter = number.begin() + 5; iter != number.end() - 9; ++iter, ++i){
  cout << i << ". " << *iter << " " << (iter->meow()).c_str() /* C++ cannot take both a cstring and a string at the same time.*/ << endl;
 }
 

}

Saturday, September 4, 2010

Object Oriented Language: C++, Variables and Data types

I have introduced the use of variables in the previous lesson. We are going into more details today.

// Variable declaration
int x;

// Variable initialization, the following two statements does the same thing, initialized the left-hand variable to 0
int y = 0;
int z(0); 

// Assignment statement
x = 22; 

// Play around with the variables
y = x = z; // guess what this does?



We'll talk about types of data types.

Source: http://www.desy.de/gna/html/cc/Tutorial/img20.gif

There is another predefined data type called bool, it has values true/false.
string is an add-on library to provide the language with the ability to store and manipulate a stream of characters.
int x = 100, y = 20, z = 10;
double pi(3.14);
float quarter = 0.25;

quarter = x; // this is fine
x = pi; // this would cause information to be truncated because integer cannot store decimal values. 

string aStr("Proving strongly/strictly typed");

// this would not compile because c++ is a strictly typed language.
x = aStr; // Compiler error, an integer variable cannot hold a string.

Object Oriented Language: C++, Basic I/O operations

I am writing this article to prepare myself for the upcoming interview with FactSet. As a warm up, I'll need to review all the basics, object oriented concepts, data structure and algorithms.

It's best to review by writing up a few easy and simple source codes.

I'll start off assuming the reader does not have any prior or little programming experiences.

The first thing everyone might notice in a programming book is how to write "Hello World!" message to the output device, the screen. I'll start off by providing a simple output statement with C++:
cout << "Hello World!";
This is the statement required for printing the message onto your screen. cout serves as the key word to output messages.

For a complete program, you would have to type the following:
#include 
using namespace std;

int main(){
    cout << "Hello World!";

    return 0; // It's a good practice to always return a 0 indicating the program executed without any interruption or problems.
}
Now that you have created your first program, save it as "HelloWorld.cpp". Compile it with your favorite compiler to see the results.

After you have seen the results, you might be curious what that rest of the code does. I will give you a brief overview of each statement.
#include 
This is a include statement, we included the iostream library. IOstream library is required for source files that are required to do basic input/output related operation. If you forget to include the required library, the compiler would not recognize the keyword "cout" as in this example.
using namespace std;
That is namespace. Just remember to type this statement for each source file you are going to write for now. We'll go into more details later on.
int main(){
This is the main function. It served as the entry point, the starting point for all programs. This function is mandatory by all programs. We will discuss function soon in the future.
return 0;
This is the return statement. For now, just remember to type this statement before you close the main function.
}
Finally, the closing curly braces. This closes the previous opening curly braces, which is the '{' after the main function. Everything inside the two braces are called a block of code.

There is one more thing in the source code that we haven't mention.
// It's a good practice to always return a 0 indicating the program executed without any interruption or problems.
The two forward slashes forms what we called, Single Line Comment. Everything that is in the same line and after the "//" will be ignored by the compiler and serve as notes to the developer. More ways of writing comments will be introduced in the near future.




We are done with the first program, but we are not done with the lesson yet.
We are going to learn how to take in messages from our user now. The trick is simple:
int daysInMonth;
cout << "How many days are there in a month?\n";
cin >> daysInMonth;
cout << "You entered " << daysInMonth << "." << endl;
There are a few new keywords here, I'll go over all of them briefly. First of all the int keyword.
int daysInMonth;
This is a variable declaration statement, it declare the integer variable. An int (integer) is a real number that can hold a number within ranges of: −2,147,483,648 to +2,147,483,647. We'll discuss more about variables in the next lesson. A variable can be thought of as a container that is holds a type and is subject to changes. daysInMonth in our case is an integer variable that is able to hold real number from −2,147,483,648 to +2,147,483,647.
cout << "How many days are there in a month?\n";
This should be familiar with you guys as I taught you about it a few paragraphs ago. Some of you with sharp eyes might have notice the difference with this statement. Yes, there is newline character, denoted by '\n'. This character tells the compiler to go to the next line and continue printing from there. As most of you would be better familiar with the "Enter" key in the notepad. The newline is created when you presses the key.
cin >> daysInMonth;
This is the statement that we are interested in this mini-program. The cin keyword, as some of you might have already figured out, takes in the input from the user and stores it in the daysInMonth variable.
cout << "You entered " << daysInMonth << "." << endl;
The last line of the program is an output operation with a little bit freshness. I'll walk you through the new codes. You didn't know you could do that with cout, did you? The left arrow arrow, "<<", means that we are concatenating or linking the the previous cstring, a string literal, or variable with the next. This linking is required for printing a variable and a cstring. cstring will be discuss when we talk about the string class. Finally, the endl keyword. This keyword creates a newline character just as '\n' does; same function, different approaches, use whichever you feel like to. For a complete view of the second program, "program2.cpp", it will look like the following code:
#include 
using namespace std;

int main(){
    int daysInMonth;
    cout << "How many days are there in a month?\n";
    cin >> daysInMonth;
    cout << "You entered " << daysInMonth << "." << endl;

    return 0; // Once again, please do not forget to include this line in your code.
}
I'll wrap the lesson up with the following:
cout << "outputs the message";
cin >> inputsTheMessage; // assuming the variable is declared. 
Some of you might be curious about the annoying semicolon, ';', I typed after each and every statement. As a matter of fact, this character is required and it signifies the end of statement for the compiler.

Enjoy and I'll write you some more tutorials tomorrow. :)
Give me some feedbacks if you find this helpful, or would like to give a suggestion or advice.

Hello, and welcome to My Technical Blog!

Hello, everyone.

This is first and probably last blog.

I am Wensheng Chen. Anyone bright enough would have figured out I am a Chinese from the name. :)
From now on, I am going to periodically post some technical posts into this blog. Hopefully, it will help out some novices surfing for help.