Monday, September 14, 2015

C++ Terminology

1.   Reference  VS Pointer

  • pointer can be re-assigned any number of times, but reference can't be changed after initial binding
  • pointer can be NULL, but reference has to refer to an object
  • you can't take the address of  a reference but you can take the address of pointers
  • A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.

2.   Const  VS Static

      Const:

  • if use const to declare a variable: const means that we can't change the value, const always decorate the type in its left side, it decorate the type in its right side when nothing in its left side. e.g.: const char * ptr;  // the value that ptr points to should not be changed.  char* const ptr; // the pointer should not point to other memory
  • if use const is applied to a function in class: const means this function should not change any value of class variables. eg: void MyConstFunction() const;
     Static:

  • if we declare a static variable within  a function, that means this is a global variable, this variable lasts until the whole program stop. 
  • if we declare a static variable or static function without in any function, this means that these variables or functions can only visible within this file. 
  • if we declare a static variable within a class, that means this variable is belongs to the class, not for a specific object, all objects of that class have the same value of a static variable.
  • if we declare a static function within a class, the static function operates static variables or global variables.


3.   Virtual function(base class) VS  abstract base class VS Interface

      Virtual:

  • A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties through references
  • The member function area has been declared as virtual in the base class because it is later redefined in each of the derived classes. Non-virtual members can also be redefined in derived classes, but non-virtual members of derived classes cannot be accessed through a reference of the base class
  • A class that declares or inherits a virtual function is called polymorphic class.

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()
      { return 0; }
};

class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
};

class Triangle: public Polygon {
  public:
    int area ()
      { return (width * height / 2); }
};

  Rectangle rect;
  Triangle trgl;
  Polygon poly;
  Polygon * ppoly1 = ▭
  Polygon * ppoly2 = &trgl;
  Polygon * ppoly3 = &poly;
  cout << ppoly1->area() << '\n';
  cout << ppoly2->area() << '\n';
  cout << ppoly3->area() << '\n';
  • Virtual destructor in base class why?
  • the destructor are called automatically base on the reverse order of constructor when we declare a pointer points to the derived class and delete that pointer when we either declare the virtual destructor in base class or not;
  • but if the destructor is not virtual in base class, when we declare a base pointer points to a derived class, and try to delete the base pointer, only the base destructor is called, and only the resources in base class is deleted, what if we declare the destructor to be virtual in base class, when we delete the base pointer, both the base destructor and the derived destructor are called.
class Base {
public:
    Base(){
        cout << "this is the constructor of base class \n";
    }
    virtual ~Base() {
        cout << "this is the destructor of base class \n";
    }
};

class Derived : public Base {
public:
    Derived() {
        cout << "this is the constructor of derived class \n";
    }
    ~Derived() {
        cout << "this is the destructor of derived class \n";
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    Derived* d = new Derived(); //create a base object first, then create a derived object
    delete d; 
    Base* b = new Derived();
    delete b;
    return 0;
}
output:
with virtual
-----------------------------------------------------------\
this is the constructor of base class 
this is the constructor of derived class 
this is the destructor of derived class 
this is the destructor of base class 
this is the constructor of base class 
this is the constructor of derived class 
this is the destructor of derived class 
this is the destructor of base class 
----------------------------------------------------------\
without virtual
-----------------------------------------------------------\
this is the constructor of base class 
this is the constructor of derived class 
this is the destructor of derived class 
this is the destructor of base class 
this is the constructor of base class 
this is the constructor of derived class 
this is the destructor of base class 
-----------------------------------------------\



Abstract base class

Although the above class has virtual function, but it's still a regular class. 
Abstract base class can only be used as base classes, and thus are allowed to have virtual functions without any definition (pure virtual functions). 

// abstract class CPolygon
class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area () =0;
};

the definition of virtual function area has been replaced by = 0, which makes it a pure virtual function. 
  • Classes contain at least one pure virtual function are known as abstract base class.
  • A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract) derived class. 
  • Abstract base classes can't be used to instantiate objects, can only be used as a pointer. The same use as a pointer in regular class.
Polygon mypolygon;   // not working if Polygon is abstract base class 


Interface:
an interface has no implementation.
an interface class contains only a virtual destructor and pure virtual functions.
class shape   // An interface class
{
  public:
    virtual ~shape();
    virtual void move_x(int x) = 0;
    virtual void move_y(int y) = 0;
    virtual void draw() = 0;
//...
};

abstract base classes VS Interface
  • Interface classes can have no state or implementation, but abstract base classes may contain state(data members) and/or implementation(methods).
  • a class that implements an interface must provide an implementation of all the method of that interface, but abstract classes can  be inherited without implementing the abstract methods(such a derived class is abstract class itself).
  • Interface may be multiple-inherited, abstract classes may not. this is probably the key concrete reason for interfaces to exist separately from abtract classes
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
Related knowledge:

C++ inheritance:

syntax:
class derived_class_name : public base_class_name

how to access members in a class?

syntax:
class_name :: member
eg: Polygon :: width
      Polygon :: set_values()

What is inherited from the base class?
A publicly derived class inherits access to every member of a base class except:
  • its constructors and its destructor
  • its assignment operator members (operator=)
  • its friends
  • its private members
// constructors and derived classes
#include <iostream>
using namespace std;

class Mother {
  public:
    Mother ()
      { cout << "Mother: no parameters\n"; }
    Mother (int a)
      { cout << "Mother: int parameter\n"; }
};

class Daughter : public Mother {
  public:
    Daughter (int a)
      { cout << "Daughter: int parameter\n\n"; }
};

class Son : public Mother {
  public:
    Son (int a) : Mother (a)
      { cout << "Son: int parameter\n\n"; }
};

int main () {
  Daughter kelly(0);
  Son bud(0);
  
  return 0;
}
Mother: no parameters
Daughter: int parameter

Mother: int parameter
Son: int parameter
Daughter (int a)          // nothing specified: call default constructor
Son (int a) : Mother (a)  // constructor specified: call this specific constructor

Multiple inheritance:

A C++ class can inherit members from more than one class. 
syntax: 

class derived-class: access baseA, access baseB....

#include <iostream>
 
using namespace std;

// Base class Shape
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};

// Base class PaintCost
class PaintCost 
{
   public:
      int getCost(int area)
      {
         return area * 70;
      }
};

// Derived class
class Rectangle: public Shape, public PaintCost
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};

int main(void)
{
   Rectangle Rect;
   int area;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   area = Rect.getArea();
   
   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   // Print the total cost of painting
   cout << "Total paint cost: $" << Rect.getCost(area) << endl;

   return 0;
}

4.   Polymorphism
the pointer point to a derived class is type compatible with the pointer point to the base class. A base class type pointer may call different member function according to the derived class it points to.

A polymorphism class is class with virtual functions. Virtual and Inheritance in C++ allows polymorphism to be implemented.

      how is polymorphism achieved?
Each class maintain a Vtable, which is  a lookup table for function calls, which version of the function shall I call. The base class function will always be included as the top portion of the subclass. A base class type pointer pointing to a derived class, the virtual pointer points to the vtable of derived class. Thus, achieving polymorphism.

5.  Dynamic binding VS Static binding
Both of these terms are associated with Inheritance, not polymorphism, polymorphism is just a specific example of dynamic binding. Binding used to determine whether to execute the parent's version of the function or the children's version of the function.
Binding: Dynamic binding VS static binding
Static binding: happens when the virtual key word is not used, Decision is made in compiler time based on the type of the variable. 


Employee * e = new Employee(); 
Person * p = e;
e
>whoAmI(); //Employee

p>whoAmI(); //Person 

Dynamic binding: Virtual is used to declare the method, and decision is made in runtime based on the  type of object it points to.


Employee * e = new Employee(); 
Person * p = e;
e
>whoAmI(); //Employee

p>whoAmI(); //Employee 

6.   Smart Pointer
   Smart pointer is a class that wraps a C++ 'RAW" CLASS, and aims to manage the life cycle of the object being pointed to.  No need to worry about forgetting to delete the object and memory leak. 
  1. Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  2. Use shared_ptr when you want multiple pointers to the same resource
  3.   share pointer : share ownership,  who should own the pointer
  unique pointer:  

No comments:

Post a Comment