-- JuanCastillo - 25 Mar 2008

About headers

There are some headers that are compiler-dependent. If you obtain a warning about, the program still will work, up to now. Some interesting liks about:

Handling files

Check also Tips and tricks on I/O formatting

Writting in a txt file

   #include <iostream> 
   #include <fstream> 
   using namespace std; 
   int main() { 
     ofstream out("test"); 
     if(!out) { 
       cout << "Cannot open file.\n"; 
       return 1; 
     } 
     out << 10 << " " << 123.23 << endl; 
     out << "This is a short text file."; 
   out.close(); 
   return 0; 
   }    

If you want to write in the file with "format" (newline, space, scientific notation, etc), you need to use the so called escape secuences. A list of them and some examples you can find CPPreference. For example cout << "message\t" << value <<endl; will include a tab after message, before value wink

Reading from a txt file

#include <iostream> 
#include <fstream> 
using namespace std; 
int main() { 
  ofstream out("test"); //filling "test" file
  if(!out) { 
    cout << "Cannot open file.\n"; 
    return 1; 
  } 
  out << 10 << " " << 123.23 << endl; 
  out << "This is a short text file."; 
  out.close(); 

  char ch; 
  int i; 
  float f; 
  char str[80]; 
  ifstream in("test");  //reading "test" file 
  if(!in) { 
    cout << "Cannot open file.\n"; 
    return 1; 
  } 
  in >> i; 
  in >> f; 
  in >> ch; 
  in >> str; 
 //printing that we read
  cout << i << " " << f << " " << ch << endl; 
  cout << str; 
  in.close(); 
  return 0; 
}

Adding shell information

Source: Calling a shell script in your C++ program

By using cout << system("date") for example, you will output the date... so just do the same directing what you want to the file.

Classical mistakes

IF statement

If condition is fufitted (condition == 1), sentence is executed.
If false (condition == 0), sentence2 is executed.

    if (<condición>) <sentence1>
    if (<condición>) <sentence1> else <sentence2>

There's a fastest way to write an if using the ternary operator . Example. The next code:

    if(runOK==1) { Read_Once(); }
    else         { Quit();}

Is equivalent to the next line:

    (runOK==1)? Read_Once(): Quit();

SWITCH statement

I'm always forgetting it: it's faster that an IF. Format:

   schitch(option){
      case 1: //code
         break; //if not, the next cases are executed also
      case 2: // code
         break;
      ...   //more cases
      default:  //optional
   }   

Passing values

By Reference

We will work with the value, not with a COPY of the value. The value IS modified inside the function.

    void ToTheSquare (int &); //function prototype
    ...
    int x = 2; 
    ...
    ToTheSquare(x);
    cout << "x modified = " << x << endl;
    ...

By Constant Reference

We will work with the value, but we FORBID to change it. If you ty to compile a function that is modifying a constant reference value, you will obtain a compilation error. Suppose that we compile something similar to:

    void ToTheSquare (const int &); //function prototype
    ...
    ToTheSquare(x);
    cout << "x modified = " << x << endl;
    ...
Then the compiler will give us the next error:
    refConstEx.cpp: In function ‘void ToTheSquare(const int&)’:
    refConstEx.cpp:19: error: assignment of read-only reference ‘x’

Objects, pointers, and memory consumption

Pointer object remarks
double *array double array[size] 1)2)

1) "size" cannot be defined in compilation time.
2) To obtain the size of your array (number of elements), try sizeof(array)/sizeof(array[0])
3) An array is working like a pointer, and it's equally fast. Example:
   double xv[3];     //array of 3 elements
   double *px = xv;  //pointer pointing to the array
   *px = 1.5;        //equivalent to xv[0]= 1.5
   px++;             //increase the pointer
   *px = 2.3;        //equivalent to xv[1]= 2.3
   ...

The pointers need memory. The process of assigning memory is called memory allocation. In C++ you can allocate and free memory using more than one function, but the following rules must be followed:

  • If allocated with malloc, calloc, realloc, valloc or memalign, you must deallocate with free.
  • If allocated with new[], you must deallocate with delete[].
  • If allocated with new, you must deallocate with delete.

The statement delete is working if the pointer exists or if it is NULL. (See paragraph 5.3.5(2) ISO/IEC 14882 (2003-10-15) ) So to check the existence of the pointer is not necessary.
Use Valgrind to trace memory leaks on your project.
Run it writting in your prompt:
    valgrind --leak-check=yes myprog arg1 arg2

A sample output if you have a leak:

...
4 bytes in 1 blocks are still reachable in loss record 1 of 3
    at 0xFFBC584: operator new(unsigned) (vg_replace_malloc.c:163) 
...

It is due to this construct. Somewhere you have a new with the corresponding delete.
(error interpretation from here )

Tips about memory obtained from Valgrind-A closer view

Reserved words and Scope of the variables (or constants)

For classes, mainly concerning access:

  • public: Access: from everywhere where the object is accesible. Simply write object.member = value for objets, pointer->member = value for pointers.
  • private: Access: only by class members. Not by external functions or functions in derivated classes. So if you have a private member, you should use Get and Set functions for accessing from outside to them.Example:.
    ...
    private: 
           ...
           int m_x;
    public: 
           ...
           int  GetX()        const  {return X;}   //'const' see below
           void SetX(int external_x) {m_x= external_x;}

  • protected: Access: public for derivated classes, private for external functions.
  • friend: To avoid protection mechanisms. Rules :

A and B B and C A and C
A friend B B friend C No transferible
A friend B C derivate from B No inheritable
A friend B B no friend of A No symmetric

  • const: When an Object is const declared, avoid accidental modification of its contain.
  • mutable: Objects which are, neither const objects, nor non-const objects. Data members which are defined using the keyword mutable, can be modified by const member functions. It can be used when a const object needs to register the number of times it was used.
  • static: It will exist ONLY one copy ot the object that will be shared by "all". It means that if we modify a static, we modidy it for "all". Ex: for a class with a static member function.
    public:
            static void *TakeData(void* par1);     (in *.h)
    void CGDataAcq::TakeData(void* par1){...}      (in *.cpp)
  • extern: 2 uses: storage type specifier, link type specifier. it makes these variables globals for different compilation units.

Dictionary of C++ "non-common" terms

  • ABC: Abstract Base Class.
  • Callback: Technique based on passing executable code as an argument for another code. See example below.
  • Functor: function object. Class that can be called as a function. See what is wikipedia explaning about here
  • Iterator: Type. Used to refer objects stored in a STL container. Additional info about from wiki also: STL
  • RAII: Technique. Resource Acquisition Is Initialization.
  • RTTI: Technique. Runtime Type Identification. Based on using typeid, dynamic casts, etc.
  • Singleton: Pattern/class. Class that must only EVER be instantiated only once. If you ask for a singleton, the SAME object/pattern is always returned.
  • Zombie: Process that despite of being finished still depends on a "parent" which is still alive. AKA as "defunct" processes. The purpose of the "zombies" is really just for the system to remember the process ID, so that it can inform the parent process about it on request. If the parent "forgets" to collect on its children, then the zombie will stay undead forever.
Topic revision: r5 - 2009-05-26, JuanCastillo
 
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding GSI Wiki? Send feedback
Imprint (in German)
Privacy Policy (in German)