C++

The logic of KDE is written in C++. The visual aspects of it are written in QML. QML is like HTML and CSS all rolled into one. You can embed JavaScript in QML. QML enables you to create beautiful User Experiences (UX). C++ makes that UX useful. C++ is also used for many other reasons and you can get a very good paying job if you understand how to use it well.

This story is a very light introduction to C++, designed to introduce you to the patterns and get the ideas imprinted into your long-term memory. It is just the beginning of your investigation of computer science, website design and artificial intelligence.

The C++ Structure

C++ has structure and logic. The three basic elements of C++ are reserved keywords, operators and punctuation. C++ includes 95 reserved keywords and syntax to use them in a meaningful way. Reserved keywords have only one meaning and trying to change that will not be productive.

Operators are core ingredients of C++ functions. Some are symbols, like +, _, >>, =>, etc. Others are words, like sizeof. Operators are classified into these categories:

• Logical Operators
• Mathematical Operators
• Relational Operators
• Conditional Operators
• Bitwise Operators
• Assignment Operators
• sizeof operator

Assignment operators assign a value to a variable. Assignment always takes place from right to left. You assign the value on the right, to the variable on the left.

Mathematical operators do what you expect, except that = is the assignment operator and == is the mathematical operator that indicates equality. * means multiplication and % means modulo, which is the remainder of a division operation. For one thing, modulo enables you to determine that a number is odd or even. x += y is the same as x = x + y. b != a means b is not equal to a.

Use logical operators to make a logical condition between two expressions, such as true or false, have a single relational result, such as if or how the program will execute going forward.

• && means and
• || means or

? is a conditional operator that tells your program to do one thing if a condition is true, such as a > b, and do something else if the condition is false.

C++ uses bitwise operators to change variables according to their bit-level, to speed up operations. Bitwise operators indicate that data is extracted and stored somewhere.

Unary operators, ++ and – – are used to increment and decrement a value.

Punctuation is another important aspect of C++. How and when to use curly braces { }, parenthesis ( ), square brackets [ ] , double quotes “ “ and single quotes ‘ ‘ and others, is an important aspect of understanding C++.

Data Types and Variables

Variables are core features of every program. They are an abstraction of memory allocation. C++ allows you to use pre-defined variable names and types, rather than calling very long and hard to remember memory addresses. Each variable reserves a specific amount of memory, in a specific place in memory, which you can use in your code. You can name a variable anything you want to.

There are several different kinds of variables.

• int
• long
• long long
• char
• bool
• double
• long double
• float
• void

are a few of the most common ones. There are a few more.

You cannot use C++ reserved keywords as variable names. You cannot use the same name for different variables within the same scope. Variable names must begin with a letter, not a number. Variable names cannot contain blank spaces.

After declaring and naming a variable, you have to initialize it. Use curly braces for modern C++ initialization. For example, in the following comparison, double declares the variable type, rate is the variable name. The C++ style looks like: double rate {18.6}; rather than the C style: double rate 18.6; or the constructor style: double rate (18.6); .

Variables can be local or global in scope. Local variables can only be used within the function in which they are declared. Global variables can be used anywhere in your program. Global variables are initialized to zero by default. Local variables do not have any default initialization value, which can cause problems. Initialize your variables.

Use local variables most of the time. Keeping them close to where you need them. Global variables can not only be used anywhere in your program, but they can also be changed by code anywhere in your program.

Constants are variables that cannot be changed. Declare a constant variable with the keyword const.

if and else if statements

You can use if statements to control the flow of your program and to enable you to make decisions in your program. if statements evaluate a statement that is either true or false and then the program proceeds accordingly. You can use if statements to enable your program to respond to user’s input. if statements can be nested.

else if statements enable you to test multiple conditions. If case 1 is true execute, else if case 2 is true execute, else execute case 3. For example, if you are less than 15, you are too young to work, else if you are less than 70 you are working age, else you are past working age.

Strings

Include strings in your program with the, #include <string>, command. You can declare strings as a constant or a variable. Strings can be an array of char elements, a vector of char elements or a special datatype holding an entire string. char are individual characters, such as letters, numbers and symbols. Strings always end with a null character, \0, which tells the computer that that is the end of a word.

You can manipulate and concatenate strings in a variety of ways. You can enable the user of your program to set the value of a string, while your program is running.

Arrays

An array is a fixed range or collection of elements. Arrays always have the same type of data. It can be a list of variables of the same kind, like int, char or double, etc. Never mix data types in an array. You can directly access every single element in an array.

Declare the array size with square brackets [ ]. Use curly braces { } to contain the array itself. Access each element using the index position. The first element is always #0. The last element is the size of the array – 1. You can create multi-dimensional arrays.

Vectors are dynamic arrays. You cannot normally change the size of an array. A vector is an array that you can change the size of. You can expand a vector elastically, as your program needs it to expand and contract. Include vectors in your program with the #include statement in the header of the program.

Loops

Loops, iterations or repetitions are synonyms describing major building blocks that C++ programs are made of. Loops enable your program to run over and over again as the environment changes. For example, while you are counting up or down. You can change some factor of your program for each iteration of the loop. Looping can happen a specified number of times, for as long as a vector has elements, or forever.

for loops iterate a specified number of times. while loops perform an action while a condition is true and stops when the condition is false. The condition must be true before the loop begins. do…while loops perform an action while a condition is true and stops when the condition is false. The condition must be true after the loop starts. In other words, a while loop will not start unless the condition is true. A do…while loop will run at least once. Nested loops refer to loops within loops.

Switch Case Statements

The switch case statement allows you to set several values for your variable to test. Each value is a case. Switching is moving on to the next value once a previous value is evaluated.

Conditional Ternary Operator ?:

The conditional ternary operator, ?:, is similar to the if-else structure. It evaluates two expressions using the syntax (conditional expression) ? expression 1 : expression 2 . If the first expression is true, the condition expression returns the value of expression 1. if it is false the condition expression returns the value of expression 2.

Infinite Loops

Infinite loops run forever. It runs with one expression that always evaluates to true. Operating systems use infinite loops to constantly run and operate. You can use a break statement to stop an infinite loop. If you accidentally get an infinite loop running, press ctrl c to stop it.

Functions

Every C++ program has at least one function, the main function. Functions can be built into your IDE. They can be part of the C++ standard libraries and classes. They can be third party functions. You can create your own custom functions. Predefined functions enable you to accomplish tasks without having to write a complete program to accomplish that task. They are reusable modules that you can build your program with.

Your function’s names must have meaning and are usually verbs, written in capitalized words with underscores connecting them, like Return_Value, or Calculate_Total. The body of your function is a statement between curly braces { }, describing what the function does. Parameters are the list of variables your function will use. The type of parameter must be specified. Functions may return any type of value, including void, which is no value.

The compiler must know the details about the function before the function is called. You can define a function normally, int main (), for example, or you can create a function prototype for more complicated functions. Function definition and function call are important features of functions.

Function overloading is using the same function to accomplish different purposes. Polymorphism is an important part of C++. Passing a function by reference is using {int &Parameter}, for example, to refer to the memory address of the parameter, rather than the parameter itself. This enables you to change the parameter to a value other than the value assigned when the parameter was initialized.

C++ functions work with a last in/ first out (LIFO) stack. You push data onto the top of the stack and pop data off the top of the stack. Inline code, inline void print, for example, involves writing the code into your main application, without using a distinct function.

Pointers

Variables have a type name, a value and a location, i.e., where they are stored in memory. Pointers are variables. The value of the variable is an address in memory. The address the pointer points at, may also be a variable. The pointer needs to know what type of data the variable is.

Pointers enable you to access data outside the scope of your function. They work very well with arrays. You can use pointers to dynamically allocate memory on the heap. Every computer program has a stack and a heap. The stack is data stored in memory temporarily, in a first in/ last out configuration, like a stack of books. In order to get to any data in the middle of the stack, you have to take everything above it off first.

The heap can be allocated dynamically, and it works well with pointers. When reading and writing to and from memory, the heap is a little slower than the stack, because it is piled up randomly. Unlike the stack, there is no restriction on the size of variables.

You also need to deallocate memory from the heap when you are finished using it, otherwise, you create a memory leak, which is memory allocated for a purpose that is no longer valid. It is just sitting there not doing anything, other than preventing the memory from being used for anything else.

Declaring a pointer is like declaring a variable, except with an asterisk * at the beginning of the variable name. Example:

variable_type *pointer_name (nullptr)

nullptr points nowhere.

Initialize pointers to make sure they only point to a specific memory address or to no address at all. Use the address operator, &, to access the address a pointer is pointing at. You can also initialize pointers to point at a variable or a function.

Dereferencing a pointer involves using the asterisk, *, operator for accessing the data a pointer points at. Lvalues are values that hold a specific location in memory.

int num {100};

num is an lvalue. An rvalue, like 100, is a literal and cannot be assigned on the left side of an assignment statement. You can use pointers to dynamically allocate memory during runtime.

You can use const (Constant) to point to constant values, in which case, we can change the pointer’s value. You can also use const to create constant pointers, which cannot be changed.

Dynamic memory allocation via a function – creates a function that creates an array during run time. Define an unsigned int for size and another int to set the value of the array’s elements.

Initialize pointers to prevent them from pointing towards garbage. Avoid wild pointers, which remain in your program after the memory address they are pointing at is already released.

Memory leaks involve failure to release allocated memory, by deleting the allocation. Removing a pointer to allocated memory leaves an orphan memory. Use smart pointers and atomic pointers to solve some of these problems.

Object Oriented Programming

Object oriented programming is a way to manage complex programs by breaking them into smaller chunks, which you can call and use over and over again. You can create modules, such as classes and objects.

Classes are a particular kind of program that you can plug into your main program. Objects are particular instances of a class. For example, you can create a class of professors. Each professor, with their name, the course they teach, and the time and place they teach the course, is an object.

Classes and objects can be public, private or protected. A public class can be accessed by anyone, from anywhere. Only members of the class or friends of the class have access to private classes. Protected classes can only be accessed and used by inheritance.

Constructors and destructors are special methods in a class. Methods are functions. There are interface methods, constructor methods and implementation methods. They are all similar and implementation methods are the most common.

Constructors always have the same name as the class. They do not require any return type and they can be overloaded. Constructors are good for initializing things.

Destructors also have the same name as the class, except they start with a tilde ~. Destructors are used to free up memory, save data to a file or database, or anything else you want to execute when you exit a class.

Constructors allocate storage dynamically. Destructors free up memory when called. Always initialize your objects to a default value

When you copy an object, you create a new object. You can use a shallow or deep copy. Shallow copies are the default method. When copying a raw pointer, shallow copying copies the pointer, but not what the pointer points at. Deep copying copies the pointer and the data the pointer points at, while allocating storage on the heap. You can use move semantics to move an object instead of copying it

Static Class Members

You can declare static functions and class members. When a static variable is used, the variable will use the same memory for all instances of the class, so no matter who uses it, the content and value will be the same in all cases.

The “this” keyword is a pointer that points to an object and can be used by non-static class members to determine if two objects are the same, or to access data members or methods, etc.

Friends of a class is a function or another class that has access to private class members, even though the function or class is not a member of the class it is a friend of. Friends must be explicitly declared in the class, with the keyword friend.

Operator Overloading

You can overload most operators to use them as part of a user defined class. Overloading operators defines the way operators will be used in user defined types, like they are used with the built-in types. The assignment operator will be automatically defined by the constructor if you do not define it. Other operators must be defined explicitly.

Encapsulation

Encapsulation, inheritance and polymorphism are fundamental concepts in C++. Encapsulation enables you to not have to expose the inner details of your class. Data hiding allows you to only provide the access necessary to use your function. The function itself is a black box. You can use it to accomplish tasks, you just cannot see how it does what it does. Using getters and setters allows you to control private data members. You should only use them when you really need to fine-tune access to the class.

Inheritance

Inheritance is often used in C++ to create new classes, using existing classes. The newly created class inherits the behavior and data of the class it is inherited from. Single inheritance is a class created from a single class. Multiple inheritance is a class created from two or more source classes.

Generalization Involves combining several classes with similar functionality into a single class. Specialization is the opposite, creating classes with more specific attributes, methods and functionality. Hierarchy is how you organize your code’s inheritance relationships from top to bottom.

Polymorphism

There are several types of polymorphism, which all work with inheritance. The default and most common type of binding in C++, static binding, is the compiler knowing how to bind the correct methods and data members. Sometimes you will want to control exactly what happens during run time by using pointers, references and declaring virtual functions. Polymorphism gives you a more abstract way for writing your programs.

Virtual functions allow you to override methods into subclasses during runtime. An example of compile time polymorphism is overloading operators and functions. Run time polymorphism is overriding functions. It is also called dynamic polymorphism, which is an example of virtual functions. Virtual functions enable you to dynamically redefine the way base class functions work.

Concrete classes can be instantiated into an object. Abstract base classes cannot be instantiated into an object. For example, you might not be able to just create an account, you have to create a particular kind of account.

C++ Logic

There is a lot more to C++ than this superficial introduction. Read the manual. Practice writing C++ code for applications. Build desktop applications using C++, QML and JavaScript.