C++ · programming

C++ programming basics

Class:

Passing classes to functions: when a class instance is passed by reference, changes are reflected in the original.

Recall that assigning one class instance to another copies all fields

Constructors: the same name as the class, can accept parameters, no return value. There can be multiple constructors. If a constructor with parameters is defined, the default constructor is no longer available. Thus, we can define constructors with default arguments, where the argument with default value must be placed at the end.

class Vehicle

{ public:
      Vehicle();
      Vehicle(int ageTemp, int speedTemp);  % overload

      int age;
      int speed;
}
Vehicle::vehicle() %implement
{   speed = 500;
    age = 900;
}
Vehicle::vehicle(int ageTemp, int speedTemp){
    speed = speedTemp;
    age = ageTemp;
}
int main(int argc, const char * argv[]){
    Vehicle bmw( 67, 89);
}

Class pointer

Display *disp = new Display();

Does three things:

  1. It creates a new variable disp, with the type Display*, that is, a pointer to an object of type Display, and then
  2. It allocates a new Display object on the heap, and
  3. It sets the disp variable to point to the new Display object.
Display *disp; disp = new GzDisplay();

You create a variable disp with type Display*, and then create an object of a different typeGzDisplay, on the heap, and assign its pointer to the disp variable.

This will only work if GzDisplay is a subclass of Display. In this case, it looks like an example of polymorphism.

Overload operator 

Vehicle operator+(const Vehicle &parameter);  % declaration
Vehicle Vehicle::operator+(const Vehicle &parameter){
   Vehicle temp;
   temp.speed = speed + parameter.speed;
   temp.age = age + parameter.age;
   return temp;}
Vehicle superBMW = bmw + bmw2;
  1. Operator overloading allows you to redefine the way operator works for user-defined types only (objects, structures). It cannot be used for built-in types (int, float, char etc.).
  2. Two operators = and & are already overloaded by default in C++. For example: To copy objects of same class, you can directly use = operator. You do not need to create an operator function.
  3. Operator overloading cannot change the precedence and associatively of operators. However, if you want to change the order of evaluation, parenthesis should be used.
  4. There are 4 operators that cannot be overloaded in C++. They are :: (scope resolution), . (member selection), .* (member selection through pointer to function) and ?: (ternary operator).

This key word

% inside the constructor
this->speed = tempSpeed;
this->age = tempAge;

Getters and Setters

If getters and setters are not defines, then the attributes and the object are constant, read only.

Static Variables

Static elements are allocated storage only once in a program lifetime in static storage area. If a variable is declared static within a class, then any objects of that class will share the same value of the variable. If inside a function, a static local variable is declared, every time that function is called, it will contain the same value that was previously assigned to it, and within the same area of memory, so we can have persistent values of that variable during the life cycle of the application.

Class Vehicle {
public:
    static int i;}

Vehicle::i = 89;

inside main {
    Vehicle bmw1, bmw2;
    bmw1.i = 900;
    % bmw2.i is 900 now. 
}

Static functions

These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. These functions cannot access ordinary data members and member functions, but only static data members and static member functions.

class X
{
    public:
    static void f()
    {
        // statement
    }
};

int main()
{
    X::f();   // calling member function directly with class name
}

In singleton design pattern.

Template classes

template <class NumType>  //声明一个模板,虚拟类型名为numtype
class Compare {
public:
   NumType first, second
   Compare(NumType a, NumType b);
   }

template <class NumType>  //函数外定义函数,应写成类模板形式
Compare<NumType>::Compare(NumType a, NumType b) {
   first = a; second = b;}

inside main {
   Compare<int> cc(4.5f, 4.7f);}

Copy constructors

class_name (const class_name&);  (remember to use reference to modify variables, use new or strdup to allocate new memory for the new instance). Assigning all fields (default copy constructor) may not be what you want: if we change or delete the field of one instance, the other one will be changed or deleted if we are dealing with pointers.

We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like file handle, a network connection.

Default constructor does only shallow copy. Deep copy is possible only with user defined copy constructor. 

12

Destructors

~ClassName(); no arguments, no return values. It  is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called, (new without delete, memory leak)

class String{
private: 
    char *s;
    int size; 
public:
    String(char *); // constructor 
    ~String();      // destructor 
}; 
String::String(char *c) 
{ size = strlen(c); 
  s = newchar[size+1]; 
  strcpy(s,c);} 
String::~String() 
{delete []s; }

Friend function

Access modifiers

default is private, public: can be accessed from anywhere; private: can only be accessed within the class. Struct in C: default is public

Basic ideas of object-oriented programming:

  1. OOP allows programmers to pack away details into neat, self-contained boxes (objects) so that they can think of the objects more abstractly and focus on the interactions between them. From my own perspective, building programs is like constructing a building. We need to have bricks (objects/boxes) firstly, then use them to build. However, in procedural programming, there are no bricks, we need use “sands” to build directly.
  2. 3 primary features: encapsulation, inheritance, polymorphism.
  3. Encapsulation: wrapping up of data and function together into a single unit. This feature keeps the data safe from outside interference and misuse. This led to a concept of data hiding.
  4. Inheritance: each derived class/subclass/low-level class inherits the attributes of its base class/super class. This process allows codes to be reused between related types. We can define overriding methods in derived classes.                                                   Access modifiers in inheritance:3
  5. Polymorphism: allowing a value to be one of several types, and determining at runtime which functions to call on it based on its type. We need to define virtual function and pure virtual function in the base class (have to implement in the derived class). With virtual function defined, the function in derived class has priority to be called, and the compiler will search for the function to call through the inheritance relationship.
  6. Friend Functions and Friend Classes

Memory management:

  1. Scoping and memory: when a variable goes out of scope, that memory is no longer guaranteed to store the variable’s value. If a pointer points to a local variable, then the value is not available out of its scope, and the pointer will become a dangling pointer.
  2. New operator: another way to allocate memory, where the memory will remain allocated until you manually de-allocate it. It returns a pointer to the newly allocated memory. The memory is in heap not stack, and the size of the memory can be a variable but not constant.
  3. Delete operator: when the variable is no longer useful, de-allocate the memory using delete, to prevent memory waste and memory leak. Do not use memory after deletion, and do not delete memory twice. If one uses new to define member variables, then one must define a copy constructor, in case of affecting one variable when changing or deleting the other variable.                                                                             int *x = new int; delete x; (delete the value x points to)                                                             int *pArr = new int[i];  delete [] pArr; (i is a variable with user input)

 

string streams: #include<string> #include<sstream>

if () {} else if () {} else {}

for (int i = 0; i<8; i++) {}

while() {}

do{} while() run at least once

goto Statement

Overload functions: different functions with the same names, different parameters, an example of polymorphism

Function templates: DataType instead of explicitly setting data types of arguments

template<class DataType>

DataType Multiplication(DataType a, DataType b) {

return a*b;}

Namespace: functions and variables belong to different namespaces

References and Pointers A pointer is a 4 byte int variable.  A pointer contains an address and points to a value. * is the contents of/dereference operator, get the value stored at the address held by the pointer; & is the address of operator. Declare a pointer: int* p; string* p; Example:

int x = 25; int* p = &x; cout<<p<<endl;   %the address of x

cout<< *p << endl; % the value of x

advantage: use large data structures outside it’s allowed scope without being copied

Delete Operator: delete p; p = NULL; no longer use the pointer, deallocate an object’s memory

Struct: C++中的 struct 和 class 基本是通用的,唯有几个细节不同:

  • 使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
  • class 继承默认是 private 继承,而 struct 继承默认是 public 继承
  • class 可以使用模板,而 struct 不能

Type aliase: typedef float f;

Unions: memory can only store one value at a time, but can be different types

Union Number { int i; double d; bool hello;}

Enumerator: An enumeration is a user-defined data type that consists of integral constants (wraps a static constant of specified type).

enum season { spring, summer, autumn, winter };

 

STL (standard template library)

https://blog.csdn.net/piaoxuezhong/article/details/54348787

  • Container: sequence containers (Deques – double ended queue, Lists – double ended linked list) | associated containers (sets, )
  • Iterator
  • Algorithm

 

What is vtable? What are virtual functions? What is virtual memory(OS)? A tree mirroring question, string manipulation questions, OOP design question.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s