OOP Summary

Preliminaries

Linux Basics

  • Change Password: passwd
  • shutdown: sudo shutdown -h 3 (broadcast to all users in 3 mins)
  • reboot: sudo reboot -r now
  • create an empty file: touch file-name
  • Display file contents: cat/more/less/head/tail file-name
  • find name of current directory: pwd

Command-line Arguments

Access argv and envp in the main routine

int main(int argc, char **argv, char **envp)
  • argc : Number of arguments in the list
  • envp : Shell reads in environment variables into envp list; can be omitted if not needed

Compilation and multiple-file projects

options for g++

  • -o filename : specify the output filename
  • -E : Stop after the preprocessing stage (只進行預編譯)
  • -S : Stop before assembling (生成彙編代碼,不進行彙編)
  • -c : do not run the linker (不進行鏈接)

Declaration

A function (函數) or variable (變量) can be defined only once, but can be declared many times.

  • Variable declaration: extern int x;
  • Function declaration: extern void sum (int argc, char* argv[]);

Include Header Files

  • Preprocessor directive (預編譯命令) #include

    • Angle brackets <> : typically for system headers
    • Double quotes " " : First search in current directory where the compilation is launched

    Suggestion: include related header files in all the source files, wherever the declared functions are either defined or referenced (引用).

Makefile

Separate Compilation

  • Different source files (.cpp) (源文件) are compiled separately into different relocatable object files(.o or obj) (可重定位的目標文件)

    g++ -c main.cpp -o main.o
    
  • The relocatable object files are linked into the executable object file (可執行目標文件) by a tool called linker (鏈接器)

    g++ main.o sum.o product.o -o test.exe
    

make and Makefile

A tool called make is introduced to manage the compilation process.

  • Dependency rule (依賴規則)
    • Defined by comparing the modification dates of the source/header files (比較文件的更新日期)
    • When a dependency rule is satisfied, the corresponding (compilation/linking) commands will be executed.
test.exe: product.cpp sum.cpp main.cpp functions.h
	g++ product.cpp sum.cpp main.cpp -o test.exe

Dependency rule: if test.exe does not exist or is older than any of the files after the colon(😃, the following command (g++ …) will be executed.

an example:

test.exe: product.o sum.o main.o
	g++ product.o sum.o main.o -o test.exe
product.o: product.cpp functions.h
	g++ -c product.cpp -o product.o
sum.o: sum.cpp functions.h
	g++ -c sum.cpp -o sum.o
main.o: main.cpp functions.h
	g++ -c main.cpp -o main.o

More on Makefile

  • Default target is all
  • If one specific target is needed: make test1.exe

There are tools for automatically generating the makefile, such as cmake.

Library

Static library (Linux)

A particular file of archive format (with .a suffix), which is a collection of concatenated relocatable object files, with a header describing the size and location of each object file.

g++ -static main.o test.a -o test.out
g++ -static main.o -L. -ltest -o test.out

-static: tells the linker to build a fully linked executable object file without any further linking at load time

Shared Library

An object module (with .so suffix) loaded at an arbitrary memory address (內存地址) and linked with a program in memory, at either run time (運行期) or load time (啓動期). This is called dynamic linking (動態鏈接)

g++ -c -fPIC sum.cxx -o sum.o
g++ -shared -o libtest.so product.o sum.o

Class

variables and function are encapsulated (封裝) into a structure called class.

Key features of OOP:

  • Abstraction (抽象)
  • Encapsulation (封裝) (information hiding)
  • Inheritance (繼承)
  • Polymorphism (多態)

Object & Abstraction

Member Variable and Member Function

class Bird{
	public:
		void fly();
		void sing();
		void eat(); //Member Functions
	private:
		std::string name_;
		std::string color_;
		float weight_;
		float height_; //Member Variables
};

Access Control to Class Members

  • Do not restrict class designers (設計者)

  • Restrict class users (使用者)

    Example:

    ClassName objectName;
    objectName.memberVariable = XX; //should be restricted
    objectName.memberFunction(YY); //without restrict
    

Public Members

  • accessible from objects by class users
  • the interface (接口) between class designers and the class users
  • When no keyword is given
    • Default access control for class is private
    • Default access control for struct is public

Private Members

  • only accessible within member functions by class designers
  • This enables the information hiding (信息隱藏) for the class designers

Protected Members

  • Similar access control to private
  • Different from private for the derived classes
    • Used in inheritance (繼承)

Definition of Member Functions

Member function

  • Declared inside the class definition (類聲明內部)
  • Typically defined outside the class definition
    • With scope resolution operator ::

Inline function

Functions less than 10 lines can be declared inline to improve efficiency

#ifndef BIRD_H_
#define BIRD_H_ //Preprocessor directive
#include <iostream>
#include <string>
class Bird {
	public:
		void setSpeed(float speed) {
			speed_ = speed;
		}//inline functions
	private:
		float speed_;
};
#endif
#include "bird.h"
using namespace std;
void Bird::fly(float time) {
	float distance = speed_ * time;
	cout << name_ << " flies distance: " << distance << endl;
}

Encapsulation

  • Integrate attribute and behavior into an entity

  • Improve safety

    • Set different access control (訪問權限控制) for different members.
    • Class users can only access public members (also called interfaces, 接口)
  • Decouple (解耦) between class users and designers

this Pointer

  • Keyword this : points to the address(地址) of the current object.

  • Usage

    Return current object’s address from its member functions

    • Typically used in operator overloading(e.g., =): return *this;
class Bird {
	public:
		void fly(float time);
		Bird* setName(char *name) {
			name_ = name;
			return this;
		}
	private:
		std::string name_;
};
//User program:
Bird b;
b.setName(“Eagle")‐>fly(10.0);

Constructor (構造函數)

Lifetime (生命期) or scope (作用域) of objects

Constructor (ctor, 構造函數) and destructor (dtor, 析構函數) are introduced for better SAFETY (安全性)

  • Special member functions for initialization (初始化) and cleanup (清除).

  • Automatically called by the compiler (編譯器) when an object is being created (創建) or deleted (銷燬)

  • Constructors and destructor are typically public

    call constructor/destructor by new/delete

Why constructor is necessary?

  • Constructor provides a place to ensure certain task be executed, such as member initialization, along with object creation (對象創建時進行初始化)

  • Avoids the careless/wrong usage of a class

Constructor is automatically called by the compiler when the object is being created for definition of an object:

ClassA a; //Stack object
ClassA *pA = new ClassA; //Heap object 
  • Constructors have the same name as the class

  • Parameters can be provided in constructor for initialization

    class Tree {
    		int height_;
    	public:
    		Tree() { height_ = 0; } // Constructor 1
    		Tree(int h) { height_ = h; } // Constructor 2
    };
    

Default Constructor

a special constructor without function arguments (above. Constructor 1)

When no constructor is defined in a class, the compiler will synthesize (合成) a default constructor, called a default default constructor

Using default keyword for Default Constructor

The use of the default keyword is preferred in modern C++ code

class Tree {
		int height_{0};
	public:
		Tree() = default; //equals to Tree(){}
};

Member Initializer List

class Tree {
		int height_ {0}, year_ {0};
	public:
		Tree(int h, int y) : year_{y}, height_{h} { }
};

enjoys better efficiency

Keyword explicit

Single-parameter constructor enables the implicit type conversion (隱式類型轉換)

To forbid such conversions, use keyword explicit.

class Tree {
		int height_{0};
	public:
		Tree(int h):height_{h} {}
	//explicit Tree(int h):height_{h} {}
}; //…
void foo(Tree t){
	//…
}
foo(5); //works if no explicit keyword, error if explicit is used

Delegating Constructor

Depends on other constructors for the initialization

class Tree {
		int height_, size_;
	public:
		Tree(int h) : height_{h} { }
		Tree() : Tree {h} { size_ = 0; }//Delegating constructor
};

Destructor (析構函數)

Clean up the resource (memory) occupied by the object. A special function called destructor(prepare-to-die) is introduced for cleanup.

Destructor is automatically called by compiler when:

  • An object goes out of its scope
  • Using delete: ClassA *pA = new ClassA; delete pA;
  • In modern C++, we can use std::unique_ptr<> and std::shared_ptr<> instead of new and delete.

DON’T explicitly call (顯式調用) the destructor unless necessary.

pA->~ClassA(); // works but NOT recommended 
  • Destructor
    • Name of destructor is the same as the class, preceded by ~
    • No function parameters
    • There should be only one destructor
    • The destructor needs to be public to be automatically called

When is a destructor necessary?

  • To free (釋放) member variables allocated on the heap (堆)
  • Free other occupied resources (socket, printer, etc.)

Default Keyword

the same as previous

Stack vs. Heap Variables

  • Stack (棧) and Heap (堆) are memory (內存) fragments for storing the variables of the program.

  • Stack

    • Limited size of several kilobytes (千字節) to megabytes (兆) depending on the system (系統) and compiler settings.
    • Store local variables of different functions
    • Example of variables on stack: int i; double val; ClassA a;
    • **Stack overflow (棧溢出) **may occur for large array variables (e.g., int a[100000000];) and deep recursive functions (遞歸函數)
  • Heap

    • The size of heap is much larger than stack: so large array variables(數組變量)should be defined on heap

    • How to define variables on the heap?

      int num = 1000000; // on stack
      int *arr = new int[num]; delete []arr; // on heap
      int *arr = (int*)malloc(sizeof(int)*num); free(arr); // on heap
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章