C++

[Road to DL Engineer] C++ Tutorial ~Basics~

こちらの投稿では下記チュートリアルの目次をご覧いただくと記載のある、Basicsのパートまでを扱うものとします!
それ以降は別の記事にて記載をいたします。

Bear in mind that this post aims to master C++ for beginners.
And most probably containing some mistakes, so please kindly notice me!

Tutorial Link: https://www.tutorialspoint.com/cplusplus/cpp_overview.htm
推薦していただいた参考サイト:http://www.learncpp.com/

Contents

  1. Overview
  2. Environment Setup
  3. Basic Syntax
  4. Data Types
  5. Variables Types
  6. Variable Scope
  7. Constants/Literals
  8. Modifier Types
  9. Storage Classes
  10. Loop Types
  11. Decision Making
  12. Functions
  13. Numbers
  14. Arrays
  15. Strings
  16. Pointers
  17. References
  18. Basic I/O
  19. Data Structures

1. Overview

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.
And it is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.

This language covers 4 important concepts.
1. Encapsulation
2. Data Hiding
3. Inheritance
4. Polymorphism

In fact, C++ is portable, hence once you code then able to run anywhere.
similar to Java!

2. Environment Setup

C++ Compiler

This is an actual C++ compiler, which will be used to compile your source code into final executable program.
Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems.

First, check if you have GCC on your machine.
then try below.

Mac OS X Installation
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.

Windows Installation
To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.

3. Basic Syntax

Before jumping into the actual code, let us brief the basic components in C++.

  1. Object: it has states and behaviour. Ex) a dog has states(colour, name and so on.)
  2. Class: a class can be defined as a template/blueprint describing the behaviours/states of object
  3. Methods: a method is a bbehaviour.
  4. Instance Variables: each object has its unique set of instance variables.

C++ Structure

#include <iostream>
using namespace std;
int main(){
cout << "Hello World!!" << endl;
return 0;
}
  1. [using namespace std;] tells the compiler to use the "std" namespace.
  2. "//" is the notation for commenting.
  3. "int main()" is the main function.
  4. "cout << ..." is the print function!
  5. "return 0": since our main function defined as "int" at first, so must return something integer.

Compile and Execute C++

$ g++ hello.cpp (hello.cpp is your filename!)
$ ./a.out
> Hello World!

Keywords in C++
Screen Shot 2018-03-28 at 17.57.18.png

4. Data Types

Basic Types
Screen Shot 2018-03-28 at 17.59.03.png

Special wrappers for types
1. signed
2. unsigned
3. short
4. long

Screen Shot 2018-03-28 at 18.00.24.png

So, let's move on to how those actually build on memory.

#include <iostream>
using namespace std;

int main() {
   cout << "Size of char : " << sizeof(char) << endl;
   cout << "Size of int : " << sizeof(int) << endl;
   cout << "Size of short int : " << sizeof(short int) << endl;
   cout << "Size of long int : " << sizeof(long int) << endl;
   cout << "Size of float : " << sizeof(float) << endl;
   cout << "Size of double : " << sizeof(double) << endl;
   cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;

   return 0;
}

#output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of wchar_t : 4
  • As you might see, sizeof() operator returns us the size of something.

What is TypeDef??
you can create new name for an existing type using typedef.

#include <iostream>
using namespace std;

int main() {


   typedef int feet;
   cout << "Size of feet : " << sizeof(feet) << endl;

   return 0;
}

#output
Size of feet : 4

enum type??
https://qiita.com/ashdik/items/0a11ac75f07c7f80e97a

5. Variables Types

As we have seen in last section, there are following basic types of variable in C++.
Screen Shot 2018-03-28 at 18.11.50.png

But how to initialise those variables??

Variable Declaration
You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.

#include <iostream>

using namespace std;

extern int a, b;
extern int c;
extern float f;

int main(){
    int a, b;
    int c;
    float f;

    a = 10;
    b = 20;
    c = a + b;
    cout << c << endl;
    f = 70.0/3.0;
    cout << f << endl;
    return 0;
}

#output
30
23.3333

You can define function with some variable types

#include <iostream>

using namespace std;

// function declaration
int func();
int main() {
   // function call
   int i = func();
   cout << i << endl;
}

// function definition
int func() {
   return 10;
}

#output
10

6. Variable Scope

  1. Inside a function or a block which is called local variables.
  2. In the definition of function parameters which is called formal parameters.
  3. Outside of all functions which is called global variables.

Local Variables

#include <iostream>
using namespace std;

int main () {
   // Local variable declaration:
   int a, b;
   int c;

   // actual initialization
   a = 10;
   b = 20;
   c = a + b;

   cout << c;

   return 0;
}

#output
30

Global Variables

#include <iostream>
using namespace std;

// Global variable declaration:
int g;

int main () {
   // Local variable declaration:
   int a, b;

   // actual initialization
   a = 10;
   b = 20;
   g = a + b;

   cout << g;

   return 0;
}

#output
30

7. Constants/Literals

Constants refer to fixed values that the program may not alter and they are called literals.
three types of usages of const
http://nonbiri-tereka.hatenablog.com/entry/2014/07/04/095118

#include <iostream>
using namespace std;

int main() {
   cout << "Hello\tWorld\n\n";
   return 0;
}

#output
Hello   World

Defining Constants

There are 2 simple ways to define constants.
Define Processors

#include <iostream>
using namespace std;

#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'

int main() {
   int area;  

   area = LENGTH * WIDTH;
   cout << area;
   cout << NEWLINE;
   return 0;
}

#output
50

Const Keyword

#include <iostream>
using namespace std;

int main() {
   const int  LENGTH = 10;
   const int  WIDTH  = 5;
   const char NEWLINE = '\n';
   int area;  

   area = LENGTH * WIDTH;
   cout << area;
   cout << NEWLINE;
   return 0;
}

#output
50

8. Modifier Types

The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int. It automatically implies int. For example, the following two statements both declare unsigned integer variables.

#include <iostream>
using namespace std;

/* This program shows the difference between
   * signed and unsigned integers.
*/
int main() {
   short int i;           // a signed short integer
   short unsigned int j;  // an unsigned short integer

   j = 50000;

   i = j;
   cout << i << " " << j;

   return 0;
}

# output
-15536 50000

Like we have seen before, short int only accepts the number between -32768 and 32768.

9. Storage Classes

A storage class in C++ defines the scope of variables.
There are four types of classes.
1. auto
2. register
3. static
4. extern
5. mutable

1. auto

{
   int mount;
   auto int month;
}
# both has same storage class

2. register
Good for quick access, like counters in programme on RAM.

{
   register int miles;
}

3. static

#include <iostream>

// Function declaration
void func(void);

static int count = 10; /* Global variable */

int main() {
   while(count--) {
      func();
   }

   return 0;
}

// Function definition
void func( void ) {
   static int i = 5; // local static variable
   i++;
   std::cout << "i is " << i ;
   std::cout << " and count is " << count << std::endl;
}

#output
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

Since we are defines count as global, it has been affected by all action to this variables, increment or decrement as well.

4. extern

(main.cpp)

int count;
extern void write_extern();

int main() {
   count = 5;
   write_extern();
}

(support.cpp)

#include <iostream>

extern int count;

void write_extern(void) {
   std::cout << "Count is " << count << std::endl;
}
$ g++ main.cpp support.cpp -o write
$ ./write
# output
5

10. Loop Types

Screen Shot 2018-03-29 at 11.26.46.png

Types for loop styles
Screen Shot 2018-03-29 at 11.27.09.png

Loop Control Statement
Screen Shot 2018-03-29 at 11.27.49.png

11. Decision Making

Screen Shot 2018-03-29 at 11.29.06.png
Screen Shot 2018-03-29 at 11.29.21.png

12. Functions

Before calling actual function in the main loop, we must declare the functions above, then it becomes callable.

#include <iostream>
using namespace std;

int max(int num1, int num2);

int main(){
    int a = 100;
    int b = 200;
    int ret;

    ret = max(a, b);
    cout << "Max value is : " << ret << endl;
    return 0;
}

int max(int num1, int num2){
    int result;
    if(num1 > num2)
        result = num1;
    else
        result = num2;
    return result;
}
#output
Max value is : 200

13. Numbers

#include <iostream>
using namespace std;

int main () {
   // number definition:
   short  s;
   int    i;
   long   l;
   float  f;
   double d;

   // number assignments;
   s = 10;      
   i = 1000;    
   l = 1000000; 
   f = 230.47;  
   d = 30949.374;

   // number printing;
   cout << "short  s :" << s << endl;
   cout << "int    i :" << i << endl;
   cout << "long   l :" << l << endl;
   cout << "float  f :" << f << endl;
   cout << "double d :" << d << endl;

   return 0;
}

#output
short  s :10
int    i :1000
long   l :1000000
float  f :230.47
double d :30949.4

Math Operations

#include <iostream>
#include <cmath>
using namespace std;

int main () {
   // number definition:
   short  s = 10;
   int    i = -1000;
   long   l = 100000;
   float  f = 230.47;
   double d = 200.374;

   // mathematical operations;
   cout << "sin(d) :" << sin(d) << endl;
   cout << "abs(i)  :" << abs(i) << endl;
   cout << "floor(d) :" << floor(d) << endl;
   cout << "sqrt(f) :" << sqrt(f) << endl;
   cout << "pow( d, 2) :" << pow(d, 2) << endl;

   return 0;
}

#output
sin(d) :-0.634939
abs(i)  :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2) :40149.7

Random Number

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main(){
    int i, j;
    srand( (unsigned) time(NULL));
    for(i = 0; i < 10; i++){
        j = rand();
        cout << "Random Number : " << j << endl;
    }
    return 0;
}

#output
Random Number : 402555230
Random Number : 1172262560
Random Number : 1201868342
Random Number : 570040312
Random Number : 742974517
Random Number : 1702783561
Random Number : 1316229805
Random Number : 645284888
Random Number : 510695266
Random Number : 1910682250

14. Arrays

#include <iostream>
#include <iomanip>
using namespace std;
using std::setw;

int main(){
    int n[10];
    for(int i = 0; i < 10; i++){
        n[i] = i + 100;
    }
    cout << "Element" << setw(13) << "value" << endl;
    for(int j = 0; j < 10; j++) {
        cout << setw(7) << j << setw(13) << n[j] << endl;
    }
    return 0;
}

#output
Element        value
      0          100
      1          101
      2          102
      3          103
      4          104
      5          105
      6          106
      7          107
      8          108
      9          109
P46652:src norio.kosa

Set field width : setw()

15. Strings

C++ provides two types of string representations.
- C-style character string
- String class in C++

C-style character string
Screen Shot 2018-03-29 at 18.05.25.png

#include <iostream>

using namespace std;

int main () {

   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Greeting message: ";
   cout << greeting << endl;

   return 0;
}
#output
Greeting message: Hello

C++ supports some functions enhancing our coding.
Screen Shot 2018-03-29 at 18.08.20.png

#include <iostream>
#include <cstring>

using namespace std;

int main () {

   char str1[10] = "Hello";
   char str2[10] = "World";
   char str3[10];
   int  len ;

   // copy str1 into str3
   strcpy( str3, str1);
   cout << "strcpy( str3, str1) : " << str3 << endl;

   // concatenates str1 and str2
   strcat( str1, str2);
   cout << "strcat( str1, str2): " << str1 << endl;

   // total lenghth of str1 after concatenation
   len = strlen(str1);
   cout << "strlen(str1) : " << len << endl;

   return 0;
}
#output
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

The String class in C++

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "World";
    string str3;
    int len;

    str3 = str1;
    cout << "str3" << str3 << endl;

    str3 = str1 + str2;
    cout << "string concatenation" << str3 << endl;

    len = str3.size();
    cout << "size of str3" << len << endl;

    return 0;
}
#output
str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10

16. Pointers

Pointers in c++ is a memory for storing information, and can be accessed by "&"(ampersand). And pointer is a variable whose value is the address of another variable.#include

#include <iostream>

using namespace std;

int main(){
    int var1;
    char var2[10];
    cout << "Address of var1 variable" << endl;
    cout << &var1 << endl;

    cout << "Address of var2 variable" << endl;
    cout << &var2 << endl;
    return 0;
}
#output
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6

How to use pointer
We can initialise the pointer variable with the asterisk, which is being used to designate a variable as a pointer.
And then assign some value(address of other variables) to it. Finally we can access it with asterisk.

#include <iostream>

using namespace std;

int main () {
   int  var = 20;   // actual variable declaration.
   int  *ip;        // pointer variable 

   ip = &var;       // store address of var in pointer variable

   cout << "Value of var variable: ";
   cout << var << endl;

   // print the address stored in ip pointer variable
   cout << "Address stored in ip variable: ";
   cout << ip << endl;

   // access the value at the address available in pointer
   cout << "Value of *ip variable: ";
   cout << *ip << endl;

   return 0;
}
#output
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

17. References

The difference between pointers and references can be described three points below.
1. No NULL references.
2. After initilisation, reference cannot change their reference to others.
3. While a reference must be initialised when it is created, pointers can be initialised at any time.
Good conceptual explanation here

#include <iostream>

using namespace std;

int main () {
   // declare simple variables
   int    i;
   double d;

   // declare reference variables
   int&    r = i;
   double& s = d;

   i = 5;
   cout << "Value of i : " << i << endl;
   cout << "Value of i reference : " << r  << endl;

   d = 11.7;
   cout << "Value of d : " << d << endl;
   cout << "Value of d reference : " << s  << endl;

   return 0;
}

#output
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

18. Basic I/O

#include <iostream>

using namespace std;

int main() {
   char name[50];

   cout << "Please enter your name: ";
   cin >> name;
   cout << "Your name is: " << name << endl;

}
#output
Please enter your name: 
Your name is Allen

19. Data Structures

Structures allow us to define variables that combine several data items of the different kind.

Defining a Structure

#include <iostream>
#include <cstring>

using namespace std;

struct Books {
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

int main(){
    struct Books book;

    strcpy(book.title, "this is it!!");
    strcpy(book.author, "Norio Kosaka");
    strcpy(book.subject, "C++ Programming");
    book.book_id = 19999;

    // Print book info
   cout << "Book title : " << book.title <<endl;
   cout << "Book author : " << book.author <<endl;
   cout << "Book subject : " << book.subject <<endl;
   cout << "Book id : " << book.book_id <<endl;

   return 0;
}
#output
Book title : this is it!!
Book author : Norio Kosaka
Book subject : C++ Programming
Book id : 19999

Structures as Function Arguments
We can pass the structure to function.

#include <iostream>
#include <cstring>

using namespace std;
void printBook( struct Books book );

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

int main() {
   struct Books Book1;        // Declare Book1 of type Book
   struct Books Book2;        // Declare Book2 of type Book

   // book 1 specification
   strcpy( Book1.title, "Learn C++ Programming");
   strcpy( Book1.author, "Chand Miyan"); 
   strcpy( Book1.subject, "C++ Programming");
   Book1.book_id = 6495407;

   // book 2 specification
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Yakit Singha");
   strcpy( Book2.subject, "Telecom");
   Book2.book_id = 6495700;

   // Print Book1 info
   printBook( Book1 );

   // Print Book2 info
   printBook( Book2 );

   return 0;
}
void printBook( struct Books book ) {
   cout << "Book title : " << book.title <<endl;
   cout << "Book author : " << book.author <<endl;
   cout << "Book subject : " << book.subject <<endl;
   cout << "Book id : " << book.book_id <<endl;
}

#output
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Pointers to Structures
As an argument, we can pass the address of structure to function as well.
Then inside function, we have to specify the address to access the data stored.

#include <iostream>
#include <cstring>

using namespace std;
void printBook( struct Books *book );

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};
int main() {
   struct Books Book1;        // Declare Book1 of type Book
   struct Books Book2;        // Declare Book2 of type Book

   // Book 1 specification
   strcpy( Book1.title, "Learn C++ Programming");
   strcpy( Book1.author, "Chand Miyan"); 
   strcpy( Book1.subject, "C++ Programming");
   Book1.book_id = 6495407;

   // Book 2 specification
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Yakit Singha");
   strcpy( Book2.subject, "Telecom");
   Book2.book_id = 6495700;

   // Print Book1 info, passing address of structure
   printBook( &Book1 );

   // Print Book1 info, passing address of structure
   printBook( &Book2 );

   return 0;
}

// This function accept pointer to structure as parameter.
void printBook( struct Books *book ) {
   cout << "Book title : " << book->title <<endl;
   cout << "Book author : " << book->author <<endl;
   cout << "Book subject : " << book->subject <<endl;
   cout << "Book id : " << book->book_id <<endl;
}

#output
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700