Lesson 01-C++ Basic Concepts

Introduction to C++

History and Development of C++

  • Origin: C++ was designed by Bjarne Stroustrup around 1979, initially called “C with Classes.”
  • Development: In 1983, the language was officially named C++. It evolved from the C language by adding object-oriented features.
  • Standardization: The first official C++ standard, ISO/IEC 14882:1998, was published in 1998.
  • Subsequent Versions: The C++ standard has been continuously updated, including C++03, C++11, C++14, C++17, C++20, and beyond, each introducing new features and improvements.

Application Domains of C++

  • System Programming: Operating systems, device drivers, embedded systems.
  • Game Development: Game engines, game logic, graphics rendering.
  • High-Performance Computing: Scientific computing, financial modeling, big data processing.
  • Desktop Applications: User interfaces, office software, multimedia editing.
  • Network Services: Server-side programming, network protocol implementation.

Compiler Selection and Installation

Common Compilers:

  • GCC (GNU Compiler Collection): Suitable for Linux and Unix systems.
  • Clang: Based on LLVM, with cross-platform support.
  • Microsoft Visual C++: Designed for the Windows platform.
  • Intel C++ Compiler: Optimized for high-performance computing scenarios.
  • Dev-C++: A free integrated development environment with a built-in MinGW compiler.

Installation Example: Using Dev-C++ as an example, the installation steps are as follows:

  • Download the Dev-C++ installation package.
  • Double-click the installer and select the installation language.
  • Follow the wizard to complete the installation process.
  • Launch Dev-C++ and configure the environment (e.g., font, shortcuts).

Familiarizing with the Compiler

g++:

  • Compile: g++ --std=c++11 ch01.cpp -o main
  • Run: ./main
  • Check Exit Status: echo $?
  • Compile Multiple Files: g++ ch2.cpp Sales_item.cc -o main

Run g++ --help to view compiler options:

Usage: g++ [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase
  --help                   Display this information
  --target-help            Display target specific command line options
  --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]
                           Display specific types of command line options
  (Use '-v --help' to display command line options of sub-processes)
  --version                Display compiler version information
  -dumpspecs               Display all of the built in spec strings
  -dumpversion             Display the version of the compiler
  -dumpmachine             Display the compiler's target processor
  -print-search-dirs       Display the directories in the compiler's search path
  -print-libgcc-file-name  Display the name of the compiler's companion library
  -print-file-name=<lib>   Display the full path to library <lib>
  -print-prog-name=<prog>  Display the full path to compiler component <prog>
  -print-multiarch         Display the target's normalized GNU triplet, used as
                           a component in the library path
  -print-multi-directory   Display the root directory for versions of libgcc
  -print-multi-lib         Display the mapping between command line options and
                           multiple library search directories
  -print-multi-os-directory Display the relative path to OS libraries
  -print-sysroot           Display the target libraries directory
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers
  -Wa,<options>            Pass comma-separated <options> on to the assembler
  -Wp,<options>            Pass comma-separated <options> on to the preprocessor
  -Wl,<options>            Pass comma-separated <options> on to the linker
  -Xassembler <arg>        Pass <arg> on to the assembler
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor
  -Xlinker <arg>           Pass <arg> on to the linker
  -save-temps              Do not delete intermediate files
  -save-temps=<arg>        Do not delete intermediate files
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components
  -pipe                    Use pipes rather than intermediate files
  -time                    Time the execution of each subprocess
  -specs=<file>            Override built-in specs with the contents of <file>
  -std=<standard>          Assume that the input sources are for <standard>
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries
  -B <directory>           Add <directory> to the compiler's search paths
  -v                       Display the programs invoked by the compiler
  -###                     Like -v but options quoted and commands not executed
  -E                       Preprocess only; do not compile, assemble or link
  -S                       Compile only; do not assemble or link
  -c                       Compile and assemble, but do not link
  -o <file>                Place the output into <file>
  -pie                     Create a position independent executable
  -shared                  Create a shared library
  -x <language>            Specify the language of the following input files
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension

Run g++ -v --help for a more comprehensive list of commands.
Additional commonly used options include:

-h FILENAME, -soname FILENAME: Set internal name of shared library
-I PROGRAM, --dynamic-linker PROGRAM: Set PROGRAM as the dynamic linker to use
-l LIBNAME, --library LIBNAME: Search for library LIBNAME
-L DIRECTORY, --library-path DIRECTORY: Add DIRECTORY to library search path

Obtaining Program Status:

  • Windows: echo %ERRORLEVEL%
  • UNIX: echo $?

First C++ Program

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Explanation:

  • #include <iostream>: Includes the input/output stream header.
  • std::cout: Standard output stream object.
  • <<: Insertion operator, used to output text.
  • std::endl: Line break, equivalent to \n.
  • return 0;: Indicates successful program termination.

Comments

Single-Line Comment:

// This is a single-line comment

Multi-Line Comment:

/*
This is a
multi-line comment
*/

Input and Output

Output:

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Input:

#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    std::cout << "You entered: " << number << std::endl;
    return 0;
}

Explanation:

  • std::cin: Standard input stream object.
  • >>: Extraction operator, used to read input.

C++ Basic Overview

Built-in Data Types

Integer Types:

  • char: 8-bit signed integer.
  • short: Typically 16-bit signed integer.
  • int: Typically 32-bit signed integer.
  • long: At least 32-bit signed integer.
  • long long: At least 64-bit signed integer.
  • unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long: Corresponding unsigned integer types.

Floating-Point Types:

  • float: Single-precision floating-point.
  • double: Double-precision floating-point.
  • long double: Extended-precision floating-point.

Boolean Type:

  • bool: Boolean value, can be true or false.

Character Types:

  • char: Character type.
  • wchar_t: Wide character type, typically used for Unicode characters.

Void Type:

  • void: Empty type, used to indicate no type.

Dynamic Memory Allocation and Pointers

Dynamic Memory Allocation:

  • Use new and delete operators to allocate and deallocate memory.
  • new allocates memory and returns a pointer to it.
  • delete frees previously allocated memory.

Pointers:

  • A pointer is a special variable that stores a memory address.
  • Use the * operator to access the value pointed to by a pointer.
  • Use the & operator to obtain a variable’s address.
#include <iostream>

int main() {
    int *p = new int; // Allocate memory
    *p = 10;          // Assign value
    std::cout << *p << std::endl; // Output
    delete p;         // Deallocate memory
    return 0;
}

Object-Based Design

  • Encapsulates data and behavior into objects.
  • Objects are created by defining classes.
  • Classes can include data members and member functions.
#include <iostream>

class Point {
public:
    Point(int x, int y) : x_(x), y_(y) {} // Constructor
    void print() const { std::cout << "(" << x_ << ", " << y_ << ")" << std::endl; }

private:
    int x_; // Data member
    int y_; // Data member
};

int main() {
    Point p(1, 2);
    p.print(); // Outputs (1, 2)
    return 0;
}

Object-Oriented Design

  • Inheritance: A class can derive from another class.
  • Polymorphism: Allows subclasses to override parent class behavior.
  • Encapsulation: Hides internal details of an object, exposing only necessary interfaces.
  • Abstract Class: A class that cannot be instantiated, used to define interfaces.
#include <iostream>

class Shape {
public:
    virtual void draw() const = 0; // Pure virtual function
    virtual ~Shape() {}           // Virtual destructor
};

class Circle : public Shape {
public:
    void draw() const override { std::cout << "Drawing a circle." << std::endl; }
};

int main() {
    Circle c;
    c.draw(); // Outputs Drawing a circle.
    return 0;
}

Generic Design

  • Uses templates to implement generic programming.
  • Templates can be applied to functions and classes.
#include <iostream>
#include <vector>

template<typename T>
void print(const std::vector<T>& vec) {
    for (const auto& elem : vec) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::vector<int> v = {1, 2, 3};
    print(v); // Outputs 1 2 3
    return 0;
}

Exception-Based Design

  • Use try blocks to catch potential exceptions.
  • Use throw to raise exceptions.
  • Use catch blocks to handle exceptions.
#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) throw std::runtime_error("Division by zero.");
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

Vectors

  • std::vector is a dynamic array in the C++ Standard Library.
  • Supports automatic resizing (growth and shrinkage).
  • Provides methods for inserting, deleting, and searching elements.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    v.push_back(6); // Add element
    std::cout << "Size: " << v.size() << std::endl; // Outputs Size: 6
    return 0;
}
Share your love