kenics.net

Technical notes on perl, python, php, sql, cgi, c/c++, q/kdb+, unix/shell, revision control tools, data structures & algorithms, and their applications into web services and other various forms of software engineering.

C++ intro

 
################# 
###    C++    ### 
################# 
 
C++ is essentially C plus OOP (namely classes). mostly backward compatible depending on the compiler, and certain exceptions. 
 
its advantage over other major general purpose OOP languages is speed. relatively speaking, we can code in low level, including assembly, which sometimes becomes important for performance optimization. 
 
(of course, one can still code in C++ without OOP/classes.) 
(python is similar, but java is a pure OOP lang. one must define a class.) 
 

#  method VS function 

 
a function defined within a class is called a method. (or "member function" in C++) 
in practice, unlike a function, a method can access member variables without them being explicitly specified as input parameters. 
 
 
############################################# 
###   OOP - object oriented programming   ### 
############################################# 
 
Three key concepts (1) inheritance (2) encapsulation (3) polymorphysm. 
 
benefits of inheritance is (a) code reusability, (b) structure (c) abstraction 
benefits of encapsulation is access/privacy control of attributes, safer code/manipulation of properties. 
benefits of polymorphism is (a) structure, (b)abstraction 
 
(Concrete examples to follow in the cpp_class article) 
 
NOTE#  encapsulation is sometimes described as "binding of data and functions". 
 
 
####################### 
###   hello world   ### 
####################### 
 
 
------- helloworld.cpp ------- 
 
#include <iostream> 
#include <string> 
using namespace std; 
 
int main() 

  string user_name; 
  cout << "name pls:";     //  std::cout << "hello world" << std::endl;  w/out namespace declaration 
  cin >> user_name; 
  cout << "hello ";        // same as    fprintf(stdout, "hello ");    in C. 
  cout << user_name;       // cout is easier to use than printf which requires you to specify data type 
  cout << "\n"; 
  return 0;               // you can omit this in most compilers. 

---------------------- 
 
 
the shortest c++ code will be 
---------------- 
int main(){} 
---------------- 
 
 
#################### 
####   basics   #### 
#################### 
 
declaration VS definition  // definition is once, but declaration can be done many times. 
 
 
header file(.h) VS program file(.cpp)   // header file only contains the func name. actual def is in .cpp 
 
#include <cstdlib>       // looks thru the std places    - brackets 
#include "kenCustom.H"   // loooks thru the current dir  - double quotes 
 
 
prototype    // function declaration info to compiler 
e.g. 
int fibon_elem(int pos); 
int fibon_elem(int)    ;   // this is also ok at the declaration stage. 
 
 
 
!!!!   unlike java, you can do "==" for string too. cos its == operator overloaded in string class 
 
 
 
################################## 
####   std::<manipulators>    #### 
################################## 
 
lots of useful stuff 
http://www.cplusplus.com/reference/library/manipulators/ 
 
----------------- 
int foo, bar; 
cin >> foo >> bar;     // this will put the input into both foo & bar 
----------------- 
 
 
std::cout << "hello world"  << std::endl;          //  endl will output "\n" plus flushes all the IO buffer stream 
std::cout << "hello world"  << "\n" << std::flush; //  same as this 
 
===> the difference is lets say your output stream is some file descriptor, so your output buffer may not be writing onto the actual target file until you flush. but you dont really care usually. so you can pretty much use "\n" and std::endl inter-changeably. 
 
 
int num = 100; 
int foo = 123; 
std::cout << std::oct << num << std::endl;   //   this will print num in octed (8-bit). 
std::cout << foo;                            //   foo will still be octed. beware. 
                                             //   std::dec = decimal, std::hex = hex 
 
 
std::cout << std::setw(3) << "Hello World" << std::endl;   //  setw(n) specifies n-bytes in input/output stream 
                                                           //  will be "Hel" 
 
string str;                                                //  need  include <string> 
std::cin >> std::setw(10) >> str;                          //  will only get the first 10 chars. safe way. 
 
 
 
 
################### 
###  priority   ### 
################### 
 
!        # NOT 
* / % 
+ - 
< > <= >= 
== != 
&& 
|| 
 
 
################### 
###   comment   ### 
################### 
 
//  all comment here 
 
/* 
all 
comment 
here 
  */ 
 
 
####################### 
####  operations   #### 
####################### 
 
### conditional statement 
 
ternary operator syntax. 
 
(condition) ? <true> : <false> 
 
e.g. 
c = (a > b) ? a : b; 
 
--> same as below. 
 
if(a > b){ 
  c = a; 
}else{ 
  c = b; 

 
e.g. 
 
cout << (val % base_val ? ' ' : '\n') ;    // if val % base_val is zero, then that is false 
 
switch (val)  // dont forget break. otherwise it keeps going down. 

   case 1: 
        cout << "case one is hit. \n"; 
        break; 
   case 2: 
   case 3: 
        cout << "case two or three is hit. \n"; 
        break; 
   default:                                  // default is not mandatory, it just exits in that case. 
        cout << "default case is hit. \n"; 
        break; 

 
 
### increment 
 
val = val + 3;   // C way 
val += 3;        // C++ way. same goes for -=, *=, /=, %= 
 
 
 
 
################### 
###   file IO   ### 
################### 
 
 
-------------------------------------- 
#include <fstream> 
using namespace std; 
 
int main(){ 
 
  ofsteam outfile ("data.txt");     // constructor acturally translate this to outfile.open("data.txt") 
  if (!outfile){                    // another way is   if(outfile.is_open()) 
    cerr << "file could not be read \n"; 
  }else{ 
    outfile << "ken" << ' ' 
            << "26"  << ' ' 
            << "87"  << endl;  // endl flashes the buffer content as C++ holds some output content in buffer 
  } 
  outfile.close() 
 
  string name; 
  int age; 
  int year; 
  ifstream infile("data.txt"); 
  if(!infile){ 
    cerr << "file could not be read \n"; 
  }else{ 
    while(infile >> name){      // you can use infile.eof() also 
      infile >> age >> year;    // will get name = "ken", age = 26, year = 1987 
    } 
  } 
  infile.close() 

--------------------------------------- 
 
 
#################################### 
####  default input parameter   #### 
#################################### 
 
this is very simple. you can define a default initialization value to the input parameter of a function, in case it's invoked without any input paramter. 
 
--------------------------------- 
#include <iostream> 
 
int f(int x=333) 

return x*2; 

 
int main() 

  std::cout << f() << std::endl;        // will print 666 
  std::cout << f(111) << std::endl;     // will print 222 
  return 0; 

---------------------------------- 
 
NOTE:  in function override using virtual, you should NOT change the default value. more details in override section. 
 
 
 
########################### 
###   online compiler   ### 
########################### 
 
https://ideone.com 
 
there are many others 
 
 
 
################################# 
###   vector init - subtlety  ### 
################################# 
 
int foo[5];   // elements are uninitialized so they may contain garbage (whatever is in the allocated mem addr). 
int foo[5] = {12, 34, 56, 78, 90}; 
int foo[5] = {12, 34, 56};           // 4th and 5th elems are initialized to 0 
int foo[5] = {0};                    // similarly, 1st elem is set to 0, and the rest is set to 0 
int foo[5] = {};                     // same 
int foo[5] = {1};                    // NOTE here 1st elem is set to 1, and the rest is set to 0 
 
 
int foo[3][2] = {10, 20, 30, 40, 50, 60}; 
i.e. 
foo[0][0] to 10 
foo[0][1] to 20 
foo[1][0] to 30 
foo[1][1] to 40 
foo[2][0] to 50 
foo[2][1] to 60 
 
foo[3][2] = {{10,20},{30,40},{50,60}}; 
 

  1. 2014-05-08 00:03:55 |
  2. Category : cpp
  3. Page View:

Google Ads