0% found this document useful (0 votes)
5 views

Unit 1_System programming

The document provides an overview of systems programming, focusing on C++ as a primary language used for developing software that controls computer operations. It covers various programming paradigms, C++ syntax, data types, operators, and control structures, emphasizing the importance of efficient resource management in software development. Additionally, it outlines the process of compiling and executing C++ programs, along with examples of coding practices.

Uploaded by

titanus9067
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 1_System programming

The document provides an overview of systems programming, focusing on C++ as a primary language used for developing software that controls computer operations. It covers various programming paradigms, C++ syntax, data types, operators, and control structures, emphasizing the importance of efficient resource management in software development. Additionally, it outlines the process of compiling and executing C++ programs, along with examples of coding practices.

Uploaded by

titanus9067
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

21ECC112J – Systems

Programming
Course Credit : 4
Theory : 9 Hours
What is Systems Programming
Systems programming is the process of developing software that makes a computer
system work. It involves writing programs that control the computer's operations, such
as the operating system, firmware, and network software.
C++ is one of the most popular and widely used languages for systems programming,

What systems programmers do?


• Develop software for operating systems, control programs, and database
management systems
• Ensure that software uses resources efficiently
• Develop software that provides services to other software
Unit 1 – Multi-Paradigm Programming
❖ C++ namespaces, references, exceptions, new/delete, C++
classes & inheritance, dynamic polymorphism
❖ C++ templates, static polymorphism, C++ functions and
lambdas, C++ threads and atomics
❖ Practice: Develop and practice C++ application programs
using classes, inheritance, functions and threads.
Introduction to Programming Paradigms

Paradigm can also be termed as method to solve some problem or do


some task.

Programming paradigm is a method to solve a problem using tools and


techniques that are available to us using a programming language.

The programming language need to follow some strategy when they are
implemented and this methodology/strategy is referred as paradigms.
Introduction to Programming Paradigms
❖ Imperative Programming ❖ Functional Programming
❖ Imperative programming consists of sets of ❖ Here we subdivide the program execution into
detailed instructions that are given to the functions, as a way of improving modularity and
organization and code maintainability.
computer to execute in a given order. Step by
step instructions are given. ❖ Functions are treated as first-class citizens, meaning
that they can be assigned to variables, passed as
❖ C : developed by Dennis Ritchie and Ken Thompson arguments, and returned from other functions.
Fortran : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E ❖ They are pure functions, no side effects and strict
Kurtz control flow.
❖ JavaScript : developed by Brendan Eich
Example: Python: developed by __________, Haskell :
define squared_sum (x,y): developed by Lennart Augustsson, Dave Barton Scala :
developed by Martin Odersky
sum = x+y Example:
squared= sum^2 define squared_sum (x,y):
return squared return (x+y)^2

// squared_sum(2,3) = 25 Square_sum(2,3) = 25
Introduction to Programming Paradigms
❖ Object-Oriented Programming ❖ Generic programming
❖ Object-oriented programming allows to organize code into
classes, objects, inheritance, and polymorphism, making it ❖ Allows to write code that works with different
easier to model complex systems and reuse code.
types of data, using templates, containers, and
❖ Example
algorithms, making it more efficient and
#include <iostream> expressive.
using namespace std;
class person { ❖ Multi paradigm
char name[20]; ❖ supports more than one programming paradigm
int id;
public:
void getdetails() {}
};
int main()
{
person p1; // p1 is a object
return 0;
}
Why C++ for Systems Programming
C++ is not only a low-level language, but also a multi-paradigm language that
supports object-oriented and generic programming.
C++ comes with a rich and powerful standard library that provides a wide range
of functionality, such as input/output, strings, containers, algorithms,
exceptions, threads, and smart pointers.
C++ is known for its high performance and efficiency, which are crucial for
systems programming.
C++ is a compiled language, which means it translates code into machine code
that runs directly on the hardware, without any intermediate layer or overhead.
C++ is a dynamic language adding new features like lambda expressions, auto
type deduction, range-based for loops that make it more user friendly
C Vs C++
C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to the C language.
C++ is a combination of procedural programming as well as object oriented programming. Objects
consists of Data in form of it's characteristics and are coded in the form of methods.
In object oriented programming computer programs are designed using the concept of objects that
interact with the real world.
C++ Syntax
#include <iostream>: . It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output #include <iostream>
library functions. # is the directive. It allows us to include objects such as
cin and cout, cerr etc using namespace std;
using namespace std: This is used to import the entirety of the std int main()
namespace into the current namespace of the program. Means that {
names for objects and variables can be used from the standard library. It
is also used as additional information to differentiate similar functions. cout <<"Hello World.";
int main(): The function main is called just as in C. Any code inside its return 0;
curly brackets {} will be executed. Execution of every C++ program
}
begins with the main() function, no matter where the function is located in
the program. S Better alternative
cout: is an object used to print a particular text after << in quotes. In our #include <iostream>
example it will output "Hello World". (for personal reference we can say it
int main()
is similar to printf in c)
return 0: Terminates the function main. This statement is used to return a {
value from a function and indicates the finishing of a function. std::cout <<"Hello World";
Note: return 0;
1) Every C++ statement ends with a semicolon ';' }
2) Compiler ignores white spaces. Multiple line spaces are used to make
C++ Syntax
cout object, together with the << operator, is used to output
values/print text.
In order to insert a new line after each object declaration \n or #include <iostream>
end1 is used. using namespace std;
cin is used to get user input. This is paired along with the int main() {
extraction operator (>>) // Comment
Comments are used by the programmer to make the code cout << "Demo Code.\n";
understandable so that is can be improvised later and to make it cout << "I am learning C++" <<end1;
more readable. It can also be used to prevent execution when
cout << "print text";
testing alternative code.
return 0;
Single line comments: Single-line comments are initiated with
two forward slashes (//). This comments the entire line after the }
two slashes.
Multi Line comments: Multi-line comments start with /* and ends
with */ .
The text in between both of these will not be executed by the
compiler. Hence comments can we written in multiple lines
In class assignment

write a letter to your future self.


Write C++ code to output the following
pattern in the terminal: Name the file letter.cpp. In letter.cpp, let’s
add the following:
Dear Self,
Goal(s) for yourself.
Name and date.
Solution to in class assignments
Compile and Execute
C++ is a compiled language. That means that to get a C++ program to run, you must first translate it from a human-
readable form to something a machine can “understand.” That translation is done by a program called a compiler.
When you program in C++, you mainly go through 4 phases during development:
1. Code — writing the program
2. Save — saving the program
3. Compile — compiling via the terminal
4. Execute — executing via the terminal
Compile: A computer can only understand Machine code. Machine code is a low level programming
language in the form of hexadecimal or binary instructions that execute computer programs on the
computers CPU. A compiler can translate the C++ programs that we write into machine code and
create a machine code file.
C++ Variables and Identifiers
Variables are defined as 'a data item that may take on more than
one value during the run time of a program'. Variable has to be of
a specified data type. Syntax:
int: Stores all kinds of integers e.g. 12, 873 type variable= value;
double: Stores floating point numbers which are decimals
e.g. 12.3, 16.1 Example
char: Stores single letters, or we can say characters of a double num=5;
string e.g. 'G', 'g'
string: Collection of characters makes a string. These are
Rules for constructing identifier names:
written in double quotes e.g."Demo Code"
bool: Stored values are either true or false. Shorthand for 1) Can consist of letters, digits and
'Boolean'. underscores
Identifiers are the names of functions, variables, structures etc. 2) Must begin with a letter or an
(the elements we define) used to identify them.All c++ identifiers underscore
must be identified with unique names. 3) These are case sensitive
Examples include x,y as well as age, num etc. 4) Whitespaces or special characters like
!, #, %, etc. Are not allowed
5) Reserved words such as int or cout
cannot be used as names
Example – Data Types
#include <iostream>
// Print variable values
#include <string>
cout << "int: " << _Num << "\n";
using namespace std;
cout << "float: " << _Float << "\n";
int main () {
cout << "double: " << _Double<< "\n";
// Creating variables
cout << "char: " << _Letter << "\n";
int _Num = 5; // Integer
cout << "bool: " << _Bool << "\n";
float _Float = 5.99; // Floating point number
cout << "string: " << _String << "\n";
double _Double = 9.98; // Floating point number
return 0;
char _Char= 'G'; // Character
}
bool _Bool = true; // Boolean Space each data type occupies

string _String = "Namaste"; // String Int - 4 bytes


Float - 4 bytes
Double - 8 bytes
Float occupies 4 bytes however double occupies 8 bytes. The precision of float is Char - 1 byte
only six decimal digits, while double variables have a precision of about 15 digits . Bool – 1 byte
C++ Operators
Operators are used in C++ to perform desired operations on particular values or variables.
C++ operators:
• Arithmetic operators
• Assignment operators: These are used to assign values to variables.
• Relational operators:These are used to compare to values. These return values as either
true (1) or false (0)
• Logical operators
• Bitwise operators:
• Steps to performing Bitwise Operation
• Convert the numbers into Binary
• Perform Operation
• Convert answer into Decimal

The order of priority given to these operators are:


Assignment > Arithmetic > Relational > Logical > Bitwise
C++ Operators
Strings
Strings are a collection of characters joint together.
They are defined within double quotes. In order to
include strings in C++ it is necessary to declare an #include <iostream>
additional header file <string>. #include <string>
Syntax: string name_of_the_string= "text“ using namespace std;
A string in C++ is actually an object, which contain int main() {
functions that can perform certain operations on strings. string str1 = “Your Name?";
cout << str1;
String Length: The length of a string is found using the
length() function. cout << "The length of the string is: " << str1.length();
cout << str1[3];
Access Characters of a string: A particular character
cin >>name;
of a string can be accessed by the index number inside
cout <<"Your name is”<<name;
the square brackets[ ]. These signify the position of the
character. return 0;
}
Alter string characters: Index numbers inside square
brackets can be used to change string character.
Input a string from a User: Note: The cin function will
only read a single word and the not multiple words.
String Concatenation: '+' operator is used to add
Math and Boolean
The max(x,y) and min(x,y) can be used to find the highest and lowest values, respectively of x and y.
In order to introduce other math functions we need to include <cmath> header file
#include <cmath>
sqrt() : Finds the square root of a number
round() : rounds a number
log() : Finds the logarithm of the number.
sin() , cos() , tan() , exp() , pow() and many more including most trigonometric functions.
Boolean Expressions:
These give values as either yes or no, on or off, true or false.
#include <iostream>
using namespace std;
int main() {
bool theSunIsHot = true;
bool everyoneLikesmonkeys = false;
cout << theSunIsHot << "\n";
cout << everyoneLikesmonkeys;
return 0;
}
Arithmetic an logical Operators
Conditional Statements #include <iostream>
The conditional statement keywords: using namespace std;
int main() {
Use if to execute the code block if the the
int age = 18; #include <iostream>
condition is true
if (age > 18) { using namespace std;
Use else to execute the code block, if the same
cout << "Eligible to Vote"; int main() {
condition is false
} else {
Use else if to execute a new condition to test, if int age = 18;
cout << "Not Eligible";
the previous condition is false if (age < 18) {
}
What can the different conditions be? return 0; cout << "Too young.";
Less than: a<b } } else if (age > 81) {
Less than or equal to: a<=b cout << "Too old.";
Greater than: a>b } else {
Greater than or equal to: a>=b cout << "Just right.";
Equal to a==b }
Not Equal to: a!=b return 0;
}
Syntax #include <iostream>
Switch switch (variable) { using namespace std;
case 1:
int main() {
//code block
Switch statement is used to select one of many code int day = 3;
break;
blocks to be executed. This can be used as an substitute switch (day) {
case 2:
for if.. else statements and vica-versa.
//code block case 1:
Important Keywords
break; cout << "Monday";
break: it breaks out of the switch block so that all the default: break;
codes of other cases aren't executed. //code block case 2:
default: This sets a standard code, which is executed if }
none of the other cases are executed. cout << "Tuesday";
#include <iostream> break;
Break and Continue
using namespace std; case 3:
Break: break statement can also be used to jump out of
int main() {
a loop. cout << "Wednesday";
for (int i = 0; i <= 10; i++) {
Continue: The continue statement breaks one time break;
if (i == 6) {
repetition of the loop if a specified condition occurs and continue; case 4:
continues with the next iteration in the loop. cout << "Thursday";
}
cout << i << "\n"; break;
} }
return 0; return 0;
}
}
Conditional Statements
Loops #include <iostream>
syntax using namespace std;
There are three kinds of loops; while, do while and for. These while ( condition ) { int main() {
are used to repeat a particular code of block multiple times until //code block
int i = 0;
the condition satisfies. }
while (i < 6) {
The Do while Loop Syntax
do {
cout << i << "\n";
This loop will execute the code block once before checking if
//code block i++;
the condition is true, then for the second time it will repeat the
loop as long as the condition is true. Hence the condition is } }
tested after execution. while (condition); return 0;
}
For Loop #include <iostream> #include <iostream>
This is the most used loop using namespace std; using namespace std;
Syntax int main() { int main() {
for (Variable value; Condition; increment/decrement operator) { for (int i = 0; i <= 5; i++) { int i = 0;
//code block cout << i << "\n"; do {
} } cout << i << "\n";
return 0; i++;
} } while (i < 6);
return 0;
}
Array #include <iostream>
#include <string>
Arrays follow contiguous memory allocation ( a using namespace std;
classical memory allocation model that assigns a int main()
process consecutive memory block ). They are used to {
store multiple values in a single variable.
string fruits[3] = {"Banana", "Mango", "Apple"};
Value in the square bracket specifies the number of
for(int i = 0; i < 4; i++) {
elements in the array
cout << fruits[i] << "\n";
Note: Array's size doesn't have to be defined inside the
square bracket. But if it is not defined it will only be as }
big as the elements that are inserted into it.. return 0;
}
Way to Define a array. #include <iostream>
For strings #include <string>
string fruits[3] = {"Banana", "Mango, "Apple"}; using namespace std;
string fruits[] = {"Banana", "Mango", "Apple"}; int main()
{
For number string fruits[3] = {"Banana", "Mango", "Apple"};
int Num[3] = {10, 56, 12}; fruits[0] = "Orange";
cout << fruits[0];
return 0;
}
#include <iostream>
References #include <string>
References using namespace std;
The & operator is used to create references.
References are like alias of a variable. i.e you can refer int main()
same variable via the reference variable. {
Memory Address //Initialising References
string subject= "Math"; Output:
When a variable is created in C++, it occupies some Math
string &study = subject;
memory and hence it is allocated a particular location, Math
where it is stored. & is used to get the memory address cout << subject << "\n";
of a variable; which is the location of where the variable cout << study << "\n";
is stored. The location is in hexadecimal form. return 0;
}
Example:
string subject="Math"; //subject is the variable #include <iostream>
string &study= subject; //Reference to subject #include <string>
Output:
using namespace std; 0x5dged3
Now either 'subject or study can be used to refer to int main() {
the subject variable. Hence value of it which is maths string food = "Panipuri";
The output of the cout
can be got by any of these two methods. cout << &food; is the memory address
Read the & in these declarations as reference. Read return 0; of the first byte of the
as study is a string reference initialized to variable food
}
“subject”
Pointers
#include <iostream>
A pointer is a variable that stores the memory address as
its value. #include <string>
using namespace std;
The pointer is created using *. It points to an address of
//Initialising Pointers
the same datatype variable. The address is then
int main() {
assigned to the pointer. Usually memory addresses are
represented in hexadecimal. string food = "Panipuri"; // A string variable
string *p = &food;// A pointer variable that stores the address of food
// Output the value of food
Note: cout << food << "\n";
* Does two different things in the code: // Output the memory address of food
cout << &food << "\n";
When used in declaration (string* p), it creates a
// Output the memory address of food with the pointer
pointer variable and points to an address.
cout << ptr << "\n";
When not used in declaration, it act as a operator
return 0;
which gives the value at a given address.
}
Variable A Output:
Panipuri
Memory Address 1050 1051 1052 1053
0x7def3
Value in Memory
0x7def3
In class questions
Initalising a pointer
int a = 10; Pointrers References
int *p = &a;
// OR Initialising
int *p;
p = &a;

int i = 3;
// A pointer to variable i or "stores the address of i"
int *ptr = &i;
// A reference (or alias) for i.
int &ref = i;
References Vs Pointers
Functions
The purpose of creating a function is so that a block of
code can be executed multiple times when a function is #include <iostream>
called. using namespace std;
Data known as parameters is passed into the function. void myFunction()
The function main() is predefined and is mandatory in {
program. However there are other functions which are cout << "We are learning functions";
user defined. }
Function Calling int main()
To call a function we are to write the function's name {
followed by brackets () and a semicolon; myFunction();
Note: The function can be called multiple times and that's return 0;
what makes it useful. }

Output:
How to create a function? We are learning functions
Syntax:
void nameFunction() { Note: If a user-defined function as in the above example is
//code block declared after the main() function the code will throw an error.
It is because C++ works from top to bottom in a sequential
} flow.
Note: Void means the function doesn't have a return
value.
Function Parameters
Data can be passed to a function as a parameter. These
are variables inside of functions. These are specified #include <iostream>
withing the brackets with their datatypes. #include <string>
using namespace std;
Syntax:
void myFunction(string name)
void function( datatype variable; datatype variable;)
{
{ cout << name << " \n";
//code block }
} int main()
{
myFunction("Honey");
myFunction("sam");
myFunction("Anja");
return 0;
How to create a function? }
Syntax:
Output:
void nameFunction() { Honey
//code block sam
} Anja
Note: Void means the function doesn't have a return
value. Note: Honey is an argument , however name is a parameter
#include <iostream>
Function Parameters using namespace std;
Return Values void swapNums(int &x, int &y) {
In the following example the keyword return is used. int z = x;
Using int instead of void helps us to derive a return x = y;
value. However as discussed earlier void doesn't return a y = z;
value.
}
Call by Reference
int main() {
You can also pass a reference to the function by using
int firstNum = 10;
pointers
int secondNum = 20;
#include <iostream> cout << "Before swap: " << "\n";
using namespace std;
cout << " "<<firstNum <<“ " <<secondNum << "\n";
int myFunction(int x, int y)
swapNums(firstNum, secondNum);
{
return x + y; cout << "After swap: " << "\n";
} cout << " "<<firstNum << " "<<secondNum << "\n";
int main() return 0;
{ }
int z = myFunction(2, 3);
Before swap:
cout << z; Output:
10 20
return 0; 5
After swap:
}
20 10
Call by value and call by reference in C++
Call by reference
There are two ways to pass value or data to function In call by reference, original value is modified because we pass reference
Call by value : original value is not modified. (address).
⚫Here, address of the value is passed in the function, so actual and formal
In call by value, value being passed to the function is locally stored by arguments share the same address space. Hence, value changed inside
the function parameter in stack memory location. If you change the the function, is reflected inside as well as outside the function.
value of function parameter, it is changed for the current function only.
It will not change the value of variable inside the caller method such
as main().
// Swap function to demonstrate call by
// C++ Program to implement Swapping using Call by function Reference method
#include <iostream> #include<iostream>
using namespace std;
// Swap function to demonstrate call by value method using namespace std;
void swap(int x, int y) void swap(int *x, int *y)
{ {
int t = x;
x = y; int swap;
y = t; swap=*x;
cout << "After Swapping in function x: " << x *x=*y;
<< ", y: " << y << endl;
} *y=swap;
// Driver Code }
int main() int main()
{
int x = 1, y = 2; {
cout << "Before Swapping: "; int x=500, y=100;
cout << "x: " << x << ", y: " << y << endl; swap(&x, &y); // passing value to function
swap(x, y); Output
cout << "After Swapping in driver code: "; cout<<"Value of x is: "<<x<<endl;
Before Swapping: x: 1, y: 2
cout << "x: " << x << ", y: " << y << endl; cout<<"Value of y is: "<<y<<endl;
return 0;
After Swapping in function x: 2, y: 1
return 0;
} After Swapping in driver code: x: 1, y: 2
}
Functions contd..
Function Overloading
This property is special to C++. Using Function overloading #include <iostream>
multiple functions can have the same name with different using namespace std;
parameters. void add(int a, int b){
Note: It is better to over load one function instead of defining two cout << "sum = " << (a + b);
functions to do the same thing.
}
Remember multiple functions can have the same name until their
void add(int a, int b, int c){
datatype or parameters differ.
cout << endl << "sum = " << (a + b + c);
Function overloading can be considered as an example of a
polymorphism feature in C++. }
// Driver code
#include <iostream> int main(){
using namespace std; add(10, 2);
void add(int a, int b){
add(5, 6, 4);
cout << "sum = " << (a + b);
}
return 0;
} Output:
void add(double a, double b){
cout << endl << "sum = " << (a + b);
sum = 12
} sum = 15
// Driver code
int main(){
add(10, 2);
add(5.3, 6.2);
Output:
return 0;
sum = 12
}
sum = 11.5
Function Overloading
Advantages of function overloading:
⚫ Improves code readability and allows code reusability.
⚫ It saves memory space, consistency, and readability.
⚫ It speeds up the execution of the program
⚫ Code maintenance also becomes easy.
⚫ Function overloading brings flexibility to code.

Disadvantage of function overloading:


⚫ Function declarations that differ only in the return type cannot be overloaded
Illustration:
int fun();
float fun();
It gives an error because the function cannot be overloaded by return type only.
⚫ Member function declarations with the same name and the same parameter types cannot be overloaded if any of them is a static
member function declaration.
⚫ The main disadvantage is that it requires the compiler to perform name mangling on the function name to include information
about the argument types.
Object Oriented Programming in C++
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc.
Class in C++
The building block of C++ that leads to Object-Oriented programming is a Class.
It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating
an instance of that class.
⚫ Class in C++ is a blueprint representing a group of objects which shares some common properties and behaviors..

Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc.
So here, the Car is the class, and wheels, speed limits, and mileage are their properties.

Object
An Object is an identifiable entity with some characteristics and behavior.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Objects take up space in memory and have an associated address.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data.
Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted
and the type of response returned by the objects.
Class in C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented Programming

#include <iostream>
using namespace std;
class person {
char name[20]; //data member or attributes
int id;
public: //access specifiers
void getdetails() {} //member method
};
int main()
{
person p1; // p1 is a object
return 0; Attributes and Methods are accessed by creating an object of the class and
} using the dot syntax (.)
Example to illustrate simple Class and object in C++
// C++ program to illustrate how create a simple int main()
//class and object
{
// Create an object of the Person class
#include <iostream>
#include <string> Person person1;
using namespace std; // accessing data members
// Define a class named 'Person' person1.name = "Alice";
class Person { person1.age = 30;
public: // Call the introduce member method
// Data members
person1.introduce();
string name;
return 0;
int age;
} Output
// Member function to introduce the person Hi, my name is Alice and I am 30 years old.
void introduce()
{
cout << "Hi, my name is " << name << "
and I am "
<< age << " years old." << endl;
Attributes and Methods are accessed by creating an object of the class and
}
using the dot syntax (.)
};
Example to illustrate simple Class and object in C++
#include<iostream>
#include<string>
using namespace std;

// Create a Car class with some attributes


class Car {
public:
string brand;
string model;
int year;
};

int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values Output


cout << carObj1.brand << " " << BMW X5 1999
carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << Ford Mustang 1969
carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Inside and Outside Functions
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition: Define a function inside the class
Outside class definition: Define a function outside the class. Declare it inside the class and then define it outside of the class.
This is done by specifiying the name of the class, followed the scope resolution :: operator, followed by the name of the
function:
// Outside Function
#include <iostream>
using namespace std;
//Inside Function
class MyClass { // The class class Car {
public: // Access specifier public:
void myMethod() { // Method/function defined int speed(int maxSpeed);
inside the class };
cout << "Hello World!";
}
int Car::speed(int maxSpeed) {
};
return maxSpeed;
int main() { }
MyClass myObj; // Create an object of int main() {
MyClass Car myObj; // Create an object of Car
myObj.myMethod(); // Call the method cout << myObj.speed(200); // Call the method with an
return 0;
argument
} return 0;
Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is created.
To create a constructor, use the same name as the class, followed by parentheses ():
class Car { // The class
class Car { // The class
public: // Access specifier
public: // Access specifier
string brand; // Attribute
string brand; // Attribute
string model; // Attribute
string model; // Attribute
int year; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
Car(string x, string y, int z) { //
};
Constructor with parameters
// Constructor definition outside the class
brand = x;
Car::Car(string x, string y, int z) {
model = y;
brand = x;
year = z;
model = y;
}
year = z;
};
}
int main() {
int main() {
// Create Car objects and call the constructor with different values
// Create Car objects and call the constructor
Car carObj1("BMW", "X5", 1999);
with different values
Car carObj2("Ford", "Mustang", 1969);
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year
// Print values
<< "\n";
cout << carObj1.brand << " " << carObj1.model <<
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year
" " << carObj1.year << "\n";
<< "\n";
cout << carObj2.brand << " " << carObj2.model <<
return 0;
" " << carObj2.year << "\n";
return 0; }
}
Access Specifiers
In C++, there are three access specifiers:
⚫ public - members are accessible from outside the class
⚫ private - members cannot be accessed (or viewed) from outside the class. By default, all members
of a class are private if you don't specify an access specifier:
⚫ protected - members cannot be accessed from outside the class, however, they can be accessed in
inherited classes.

class MyClass {
public: // Public access specifier class MyClass {
int x; // Public attribute
int x; // Private attribute
private: // Private access specifier
int y; // Private attribute int y; // Private attribute
}; };

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
C++ Encapsulation
Encapsulation: to make sure that "sensitive" data is hidden from users. T
Declare class variables/attributes as private (cannot be accessed from outside the class).
To read or modify the value of a private member, provide public get and set methods.

class Employee {
private:
// Private attribute The salary attribute is private, which have restricted access.
int salary;
The public setSalary() method takes a parameter (s) and assigns it to the
public:
salary attribute (salary = s).
// Setter
void setSalary(int s) {
salary = s; The public getSalary() method returns the value of the private salary
} attribute.
// Getter
int getSalary() { Inside main(), we create an object of the Employee class.
return salary;
Now we can use the setSalary() method to set the value of the private
}
attribute to 50000.
};
Then we call the getSalary() method on the object to return the value.
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
C++ Inheritance
In C++, it is possible to inherit attributes and methods from one class to another.
⚫ derived class (child) - the class that inherits from another class
⚫ base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
//Multilevel Inheritance
// Base class // Base class (parent)
class Vehicle { class MyClass {
public: public:
string brand = "Ford"; void myFunction() {
void honk() { cout << "Some content in parent class." ;
cout << "Tuut, tuut! \n" ; }
} };
}; The Car class
(child) inherits the
attributes and // Derived class (child)
// Derived class class MyChild: public MyClass {
class Car: public Vehicle { methods from the
Vehicle class };
public:
string model = "Mustang"; (parent)
// Derived class (grandchild)
}; class MyGrandChild: public MyChild {
};
int main() {
Car myCar; int main() {
myCar.honk(); MyGrandChild myObj;
cout << myCar.brand + " " + myCar.model; myObj.myFunction();
return 0; return 0;
} }
C++ Inheritance Access // Base class
class Employee {
In C++, there are three access specifiers: protected: // Protected access specifier
⚫ public - members are accessible from outside int salary;
the class };
⚫ private - members cannot be accessed (or // Derived class
viewed) from outside the class. By default, all class Programmer: public Employee {
members of a class are private if you don't public:
specify an access specifier: int bonus;
⚫ protected - members cannot be accessed void setSalary(int s) {
from outside the class, however, they can salary = s;
be accessed in inherited classes. }
int getSalary() {
return salary;
}
};

int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary()
<< "\n";
cout << "Bonus: " << myObj.bonus <<
"\n";
return 0;
}
C++ Polymorphism // Base class
class Animal {
⚫ Polymorphism means "many public:
forms", and it occurs when we void animalSound() {
have many classes that are related cout << "The animal makes a sound
to each other by inheritance. \n";
⚫ Inheritance lets us inherit }
attributes and methods from };
another class.
⚫ Polymorphism uses those methods // Derived class
to perform different tasks. This class Pig : public Animal {
allows us to perform a single action public:
in different ways. void animalSound() {
cout << "The pig says: wee wee \n";
}
};
base class :Animal
method : animalSound(). // Derived class
Derived classes of Animals: Pigs, class Dog : public Animal { int main() {
public: Animal myAnimal;
Cats, Dogs, Birds - And they also
void animalSound() { Pig myPig;
have their own implementation of Dog myDog;
cout << "The dog says: bow wow \n";
an animal sound (the pig oinks, }
and the cat meows, etc.): }; myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
To read a file
C++ Files #include <iostream>
#include <fstream>
Using fstream library we can work with files. That library using namespace std;
function can be included by using <fstream>
int main () {
There are 3 objects included in this library. // Create a text file
ofstream: Creates and writes in files ofstream MyFileWrite ("filename.txt");
ifstream: Reads from file // Write to the file
fstream: Capable of creating, reading and writing in files. MyFileWrite << "Hello File!";
// Close the file
Create and write in file
MyFileWrite.close ();
#include <iostream> // Create a text string, which is used to output the text file
#include <fstream> string RandomText;
using namespace std; // Read from the text file
int main () { ifstream MyFileRead ("filename.txt");
//create and open a text file // Use a while loop together with the getline() function to
read the file line by line
ofstream MyFile ("filename.txt");
while (getline (MyFileRead, RandomText)) {
//Write to the file // Output the text from the file
MyFile << "Hello File"; cout << RandomText;
//close the file }
MyFile.close(); // Close the file
return 0; MyFileRead.close ();
return 0;
}
Exception handling in C++ consist of three keywords:
C++ Exceptions try, throw and catch:
The try statement allows you to define a block of code to
When executing C++ code, different errors can occur: be tested for errors while it is being executed.
coding errors made by the programmer, errors due to The throw keyword throws an exception when a problem is
wrong input, or other unforeseeable things. detected, which lets us create a custom error.
When an error occurs, C++ will normally stop and The catch statement allows you to define a block of code
generate an error message. The technical term for this to be executed, if an error occurs in the try block.
is: C++ will throw an exception (throw an error). The try and catch keywords come in pairs:

//C++ Exceptions
try {
int age = 15;
if (age >= 18) {
We use the try block to test some code: If the age variable is less than
cout << "Access granted - you are old enough.";
18, we will throw an exception, and handle it in our catch block.
} else {
throw (age); In the catch block, we catch the error and do something about it. The
} catch statement takes a parameter: in our example we use an int
variable (myNum) (because we are throwing an exception of int type in
} the try block (age)), to output the value of age.
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n"; If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be
cout << "Age is: " << myNum; greater than 18), the catch block is skipped:

}
#include <iostream>
C++ Date and Time #include <ctime> // Import the ctime library
using namespace std;
The <ctime> library allows us to work with dates and times.
To use it, you must import the <ctime> header file: int main () {
The time() function gives us a timestamp representing the struct tm datetime;
current date and time. We can use the ctime() function to time_t timestamp;
show the date and time that a timestamp represents:
datetime.tm_year = 2023 - 1900; // Number of years since 1900
datetime.tm_mon = 12 - 1; // Number of months since January
datetime.tm_mday = 17;
Hours are represented in 24-hour format. 11pm would be represented as 23. datetime.tm_hour = 12;
The months go from 0 to 11. For example, December would be represented datetime.tm_min = 30;
as 11 rather than 12. datetime.tm_sec = 1;
Years are represented relative to the year 1900. The year 2024 would be // Daylight Savings must be specified
represented as 124 because 124 years have passed since 1900.
// -1 uses the computer's timezone setting
datetime.tm_isdst = -1;

The time() function can only create a timestamp for the current timestamp = mktime(&datetime);
date, but we can create a timestamp for any date by using the
cout << ctime(&timestamp);
mktime() function.
return 0; Output
The mktime() function converts a datetime structure into a } Sun Dec 17 12:30:01 2023
timestamp.
// thread example
#include <iostream> // std::cout
C++ Threads #include <thread>
void foo()
// std::thread

Thread {
Class to represent individual threads of execution. // do stuff...
}
void bar(int x)
A thread of execution is a sequence of instructions that can be
{
executed concurrently with other such sequences in
// do stuff...
multithreading environments, while sharing a same address
}
space.
int main()
Threads allow multiple functions to execute concurrently.
{
std::thread first (foo); // spawn new thread that calls foo()
An initialized thread object represents an active thread of std::thread second (bar,0); // spawn new thread that calls bar(0)
execution; Such a thread object is joinable, and has a unique
thread id. std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
} Output
main, foo and bar now execute concurrently...
foo and bar completed.
// function template
#include <iostream>
C++ Templates using namespace std;
Function templates are special functions that can
template <class T>
operate with generic types. T GetMax (T a, T b) {
This allows us to create a function template whose T result;
functionality can be adapted to more than one type or result = (a>b)? a : b;
class without repeating the entire code for each type.
In C++ this can be achieved using template parameters.
return (result);
A template parameter is a special kind of parameter that }
can be used to pass a type as argument: just like regular int main () {
function parameters can be used to pass values to a
function, template parameters allow to pass also types to int i=5, j=6, k;
a function. long l=10, m=5, n;
function template GetMax() twice. The first time with k=GetMax<int>(i,j);
arguments of type int and the second one with n=GetMax<long>(l,m);
arguments of type long.
cout << k << endl;
The compiler has instantiated and then called each time
the appropriate version of the function. cout << n << endl; Output
As you can see, the type T is used within the GetMax() return 0; 6
template function even to declare new objects of that } 10
type:
T result;
// function template II
#include <iostream>

C++ Templates(Contd) using namespace std;

template <class T>


function template GetMax() is called without explicitly T GetMax (T a, T b) {
specifying the type between angle-brackets <>. The
return (a>b?a:b);
compiler automatically determines what type is needed
on each call. }

int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m);
The use of function templates and template parameters
cout << k << endl;
is a great C++ resource to produce cleaner code, as it
prevents function duplication. cout << n << endl;
return 0;
} Output
6
10

You might also like