Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

Thursday, 13 July 2017

Reference to a Pointer

Notes for reading C++ Primer 4/e.
void ptrswap(int *&v1, int *&v2) {
    int *tmp = v2;
    v1 = v2;
    v2 = tmp;
}

int main() {
    int i = 10;
    int j = 20;
    int *pi = &i;
    int *pj = &j;

    cout << *pi << "  " << *pj << endl;
    ptrswap(pi, pj);
    cout << *pi << " " << *pj << endl;

    return 0;
}
Result:
10 20
20 10

Reference

Notes for reading C++ Primer 4/e.

Reference

nonconst reference can only reference to the same nonconst object.
int incr(int val) {
  return ++val;
}

int incrRef(int &val) {
  return ++val;
}

int incrRefConst(const int &val) {
  cout << val << endl;

  return val;
}

int main() {
  short v1 = 0;
  const int v2 = 42;
  double v4 = 3.4;

  int v3 = incr(v1);
  v3 = incrRef(v1);  // X: no matching function for call to 'incrRef'
  v3 = incrRefConst(v1);  // 0

  int v5 = incr(v4);
  v5 = incrRef(v4);  // X: no matching function for call to 'incrRef'
  v5 = incrRefConst(v4);  // 3
  cout << v4 << " " << v5 << endl;  // 3.4 3

  return 0;
}


[note]:

  • nonconst refernce parameter 的彈性較低,不能以 const object 初始化,也不能以字面常數 (ex. 42, 'a', "Hello", 3.14...) 或 rvalue 做為 argument.

Wednesday, 28 June 2017

Array

Notes for reading C++ Primer 4/e.

Dynamic Array

value-initialize


In dynamic array, it could only initial w/ default value, not like static array, could initial as different values.
int *pia = new int[10]();  // 10 ints w/ default value 0

const

Notes for reading C++ Primer 4/e.

const Reference

Reference to a constant object.
const int ival = 1024;
const int &refVal = ival;
const int &r = 42;
const int &r2 = r + 3;


const_iterator

for (vector<string>::const_iterator iter = text.begin();
iter != text.end(); ++iter) {
    *iter = " ";  // error: *iter is const
}
vector<int> nums(10);
const vector<int>::iterator cit = nums.begin();
*cit = 1;  // OK
++cit;  // error: cit is const


Pointers & const

Pointers to const

const double pi = 3.14;
double *ptr = &pi;  // error: nonconst pointer
const double *cptr = &pi;  // OK

double dval = 2.99;
cptr = &dval;  // OK

const Pointer

int errNumber = 0;
int *const curErr = &errNumber;
curErr = curErr;  // error: curErr is const

if (*curErr) {
    errorHandler();
    *curErr = 0;  // OK
}

const Pointer Point To A const Object

const double pi = 3.14159;
const double *const pi_ptr = &pi;
pi_ptr is a constant pointer, point to a const double object.


Pointers & Typedefs

typedef string *pstring;
const pstring cstr;
Q: What is cstr?
A: Constant point, point to string.

Wednesday, 18 January 2017

[Class Diagram] Association, Aggregation and Composition


Association: ... has a ...
ex. Professor has books and books belong to one professor.

Aggregation: ... owns a ...
ex. Department has many professors in it, and professors belong to many departments or belong to many schools.

Composition: ... is a part of ...
ex. University has many departments, and departments belong to one university. While University closed, departments won't be existed.

Sunday, 15 January 2017

[C++] return by address/reference


 int *createArrayAddr(int n) {  
   int *a = new int(5);  
     
   cout << (void*) a << endl;  
     
   return a;  
 }  
   
 int &createArrayRef(int &n) {  
     
   cout << &n << endl;  
     
   return n;  
 }  
   
 int main(int argc, const char * argv[]) {  
   int *a = createArrayAddr(5);  
   cout << (void*) a << endl;  
     
   int n = 55;  
   cout << &n << endl;  
   int &n2 = createArrayRef(n);  
   cout << &n2 << endl;  
   
   return 0;  
 }  

RESULT:

 0x1001054d0  
 0x1001054d0  
 0x7fff5fbff7f4  
 0x7fff5fbff7f4  
 0x7fff5fbff7f4  

Thursday, 15 January 2015

[C++] Abstract Class

只要類別含有任何一個 pure virtual function 就稱為 abstract class.

ex.
class Shape {  // abstract class
    virtual void rotate(int) = 0;  // pure virtual function
    virtual void draw() = 0;  // pure virtual function
    virtual bool is_closed = 0; // pure virtual function
    ...
};

abstract class 無法建立任何 object,只能做為其他 object 的 interface & base object

base:
ex.
class Point { /* */ };
class Circle : public Shape {
    public:
        void rotate(int) {}  // 覆蓋 Shape::rotate
        void draw();  // 覆蓋 Shape::draw
        bool is_closed() { return true; }  // 覆蓋Shape::is_closed

        Circle(Point p, int r);
    private:
        Point center;
        int radius;
};

interface:
ex. driver
class Character_device {
    public:
        virtual int open(int opt) = 0;
        virtual int close(int opt) = 0;
        virtual int read(char* p, int n) = 0;
        virtual int write(const char* p, int n) = 0;
        virtual int ioctl(int ...) = 0;
        virtual ~Character_device() {}
};
可從 Character_device 衍生出各式各樣的 driver object

有 abstract class 便能以 object 拼出完整模組化的系統。

Thursday, 21 August 2014

[C++] Container


size add delete access
vector size() push_back() pop_back() [], back()
list size() push_back() pop_back() back()
queue size() push() pop() back()
dequeue size() push_back(),
push_front()
pop_front(),
pop_front()
[], back()
priority_queue size() push() pop() top()
set size() iterators iterators iterators
multiset size() iterators iterators iterators
map size() iterators iterators [], iterators
multimap size() iterators iterators iterators

Tuesday, 29 July 2014

[C++] Why we need new/delete in C++? Can't malloc/free do the same thing?

The difference between malloc/free and new/delete is malloc/free are standard library, and new/delete are operator.
#include <iostream>
#include <cstdlib>

using namespace std;

class Obj
{
public :
    Obj(void){ cout << "Constructor" << endl; }
    ~Obj(void){ cout << "Destructor" << endl; }
    void Initialize(void){ cout << "Initialization" << endl; }
    void Destroy(void){ cout << "Destroy" << endl; }
};

void UseMallocFree(void)
{
    Obj  *a = (Obj *)malloc(sizeof(Obj));
    a->Initialize();

    //…

    a->Destroy();
    free(a);

}

void UseNewDelete(void)
{
    Obj  *a = new Obj;

    //…

    delete a;
}

int main()
{
    cout << "UseMallocFree" << endl;
    UseMallocFree();
    cout << endl << "UseNewDelete" << endl;
    UseNewDelete();

    return 0;
}
UseMallocFree
Initialization
Destroy

UseNewDelete
Constructor
Destructor

Ref.: http://fanqiang.chinaunix.net/a4/b2/20020722/060200273_b.html

Monday, 28 July 2014

[C++] Constructor/Copy Constructor/Assignment Operator/Destructor

1) Both Copy Constructor and Assignment Operator are call by address, not call by value
#include <iostream>

using namespace std;

class Array {
    public:
        int *_array;
        int size;

        Array(int input):size(input)
        {
            _array = new int[size];
        }

        void Set(int i, int v)
        {
            _array[i] = v;
        }

        int Get(int i)
        {
            return _array[i];
        }

        ~Array()
        {
            delete [] _array;
        }
};

int main()
{
    Array a(5);
    Array b = a;

    a.Set(0, 10);
    a.Set(1, 20);
    a.Set(2, 30);
    a.Set(3, 40);
    a.Set(4, 50);

    cout << a.Get(0) << " " << a.Get(1) << " " << a.Get(2) << " " << a.Get(3) << " " << a.Get(4) << endl;
    cout << b.Get(0) << " " << b.Get(1) << " " << b.Get(2) << " " << b.Get(3) << " " << b.Get(4) << endl;
    cout << &a << " " << a._array << endl;
    cout << &b << " " << b._array << endl;

    return 0;
}
10 20 30 40 50
10 20 30 40 50
0x7fff61f44a90 0x1180010
0x7fff61f44aa0 0x1180010
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000001180010 ***

the problem caused in this program:
- memory leak in b
- it was copied by "b._array = a._array;", either modified in b or a will change the result
- double free

2) Initialization list
#include <iostream>

using namespace std;

class A {
    public:
        A()
        {
            cout << "A constructor" << endl;
        }

        A(const A& a)
        {
            cout << "A copy constructor" << endl;
        }

        A& operator=(const A& a)
        {
            cout << "A assignment Operator" << endl;
        }
};

class B {
    public:
        B(A &input)
        {
            cout << "B consturctor" << endl;
            m_a = input;
        }

    private:
        A m_a;
};

class C {
    public:
        C(A& input):m_a(input)
        {
            cout << "C constructor" << endl;
        }

    private:
        A m_a;
};

int main()
{
    cout << "===A===" << endl;
    A a;
    cout << "===B===" << endl;
    B b(a);
    cout << "===C===" << endl;
    C c(a);

    return 0;
}
===A===
A constructor
===B===
A constructor
B consturctor
A assignment Operator
===C===
A copy constructor
C constructor

3) Const variable can only be initialed in initialization list
#include <iostream>

using namespace std;

class A {
    public:
        A(int input) { a = input; }
        void show() { cout << a << endl; }

    private:
        const int a;
};

int main()
{
    A aa(5);
    aa.show();

    return 0;
}
test2.cpp: In constructor ‘A::A(int)’:
test2.cpp:7:9: error: uninitialized member ‘A::a’ with ‘const’ type ‘const int’ [-fpermissive]
test2.cpp:7:28: error: assignment of read-only member ‘A::a’
#include <iostream>

using namespace std;

class A {
    public:
        A(int input):a(input) { }
        void show() { cout << a << endl; }

    private:
        const int a;
};

int main()
{
    A aa(5);
    aa.show();

    return 0;
}
5

4) The serial of constructor and destructor
#include <iostream>

using namespace std;

class A {
    public:
        A()
        {
            cout << "A constructor" << endl;
        }

        ~A()
        {
            cout << "A destructor" << endl;
        }
};

class B {
    public:
        B()
        {
            cout << "B constructor" << endl;
        }

        ~B()
        {
            cout << "B destructor" << endl;
        }
};

class C {
    public:
        C()
        {
            cout << "C constructor" << endl;
        }

        ~C()
        {
            cout << "C destructor" << endl;
        }
};

class Aa : public A {
    public:
        Aa(int in1):y(in1)
        {
            cout << "Aa constructor" << endl;
        }

        ~Aa()
        {
            cout << "Aa destructor" << endl;
        }

    private:
        B b;
        int y;
        C c;
};

int main()
{
    Aa hi(5);

    return 0;
}
A constructor
B constructor
C constructor
Aa constructor
Aa destructor
C destructor
B destructor
A destructor

Saturday, 26 July 2014

[C++] The difference between class and struct

class X {
    int a; // X::a is private by default
};

struct S {
    int a; // S::a is public by default
};

[note]: the variable in union is also public by default.



Ref. Working Draft, Standard for Programming Language C++

Thursday, 29 May 2014

[MIT] Note 2 of Introduction to C and C++

18.01 Single Variable Calculus

Lecture 4 : Data Structures, Debugging



note: Structure Memory
ex.
#include <stdio.h>

int main()
{
    struct X
    {
        short s; 
        int i; 
        char c;
    };

    struct Y
    {
        int i;
        char c;
        short s;
    };

    struct Z
    {
        int   i;
        short s;
        char  c;
    };

    printf("%ld\n", sizeof(struct X));
    printf("%ld\n", sizeof(struct Y));
    printf("%ld\n", sizeof(struct Z));

    return 0;
}

12
8
8

Ref. http://ocw.mit.edu/courses/mathematics/18-01sc-single-variable-calculus-fall-2010/

[MIT] Note 1 of Introduction to C and C++

MIT 6.S096 Introduction to C and C++

Lecture 1: Compilation Pipeline


Ref. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-s096-introduction-to-c-and-c-january-iap-2013/

Thursday, 8 May 2014

[C++] Generic Programmin

1) Function templates
2) Class templates
- inherit:
a)


b)

c)

d)

Ref.: Practice on Programming course from Peking University

Tuesday, 22 April 2014

[C++] Pointers

Noted down the important concepts:
1. Reference Operator (&)
ex.
myvar = 25;  
foo = &myvar;
bar = myvar; 

2. Dereference Operator (*)
ex.
baz = *foo;

3. Pointers & Arrays
It collects so many ways to get address from an array and set value to an array.
#include <iostream>
using namespace std;

int main ()
{
  int numbers[5];
  int * p;

  p = numbers;
  *p = 10;

  p++;
  *p = 20;

  p = &numbers[2];
  *p = 30;

  p = numbers + 3;
  *p = 40;

  p = numbers;
  *(p+4) = 50;

  for (int n=0; n<5; n++)
    cout << numbers[n] << ", ";
  return 0;
Output:
10, 20, 30, 40, 50,

4. Pointers and Const
int x;
      int *       p1 = &x;  // non-const pointer to non-const int
const int *       p2 = &x;  // non-const pointer to const int
int const *       p3 = &x;  // also non-const pointer to const int
      int * const p4 = &x;  // const pointer to non-const int
const int * const p5 = &x;  // const pointer to const int 

5. Pointers to Pointers
char a;
char * b;
char ** c;

a = 'z';
b = &a;
c = &b;

6. Pointers and Functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))
{
  int g;
  g = (*functocall)(x,y);
  return (g);
}

int main ()
{
  int m,n;
  int (*minus)(int,int) = subtraction;

  m = operation (7, 5, addition);
  n = operation (20, m, minus);
  cout << n;
  return 0;
}
Output:
8
Mostly, we use function point in sqort().

7. Arrow
Same description below:
(*p).foo;
p->foo;

Ref. http://www.cplusplus.com/doc/tutorial/pointers/