0% found this document useful (0 votes)
6 views63 pages

What Is C++?

C++ is an object-oriented programming language that can be used to create high-performance applications. It was developed as an extension of C and gives programmers high-level control over system resources and memory. C++ is one of the most popular languages and can be found in operating systems, graphical interfaces, and embedded systems due to its portability across platforms. It allows for code reuse through object-oriented programming, lowering development costs.

Uploaded by

sartajalam8023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views63 pages

What Is C++?

C++ is an object-oriented programming language that can be used to create high-performance applications. It was developed as an extension of C and gives programmers high-level control over system resources and memory. C++ is one of the most popular languages and can be found in operating systems, graphical interfaces, and embedded systems due to its portability across platforms. It allows for code reuse through object-oriented programming, lowering development costs.

Uploaded by

sartajalam8023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 63

C++ notes

What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and
memory.

The language was updated 4 major times in 2011, 2014, 2017, and 2020 to
C++11, C++14, C++17, C++20.

Why Use C++


C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.

C++ is an object-oriented programming language which gives a clear structure


to programs and allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C, C# and Java, it makes it easy for programmers to switch


to C++ or vice versa.

C++ Syntax
Let's break up the following code to understand it better:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Example explained
Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout (used in line 5). Header files add
functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and
variables from the standard library.

C++ Output (Print Text)


The cout object, together with the << operator, is used to output values/print
text:

Example

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code. Comments
can be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not
be executed).

C++ Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

C++ Variables
Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords),
for example:

● int - stores integers (whole numbers), without decimals, such as 123 or


-123
● double - stores floating point numbers, with decimals, such as 19.99 or
-19.99
● char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
● string - stores text, such as "Hello World". String values are surrounded
by double quotes
● bool - stores values with two states: true or false

int myNum = 5; // Integer (whole number without


decimals)

double myFloatNum = 5.99; // Floating point number (with decimals)

char myLetter = 'D'; // Character

string myText = "Hello"; // String (text)

bool myBoolean = true; // Boolean (true or false)

Constants
When you do not want others (or yourself) to change existing variable values,
use the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):

Example

const int myNum = 15; // myNum will always be 15

myNum = 10; // error: assignment of read-only variable 'myNum'

C++ User Input


You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number, which is stored in the
variable x. Then we print the value of x:

Example
int x;

cout << "Type a number: "; // Type a number and press enter

cin >> x; // Get user input from the keyboard

cout << "Your number is: " << x; // Display the input value

C++ Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

int x = 100 + 50;

Operator Name Description Example

+ Addition Adds together two x+y


values

- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two x*y


values

/ Division Divides one value x/y


by another
% Modulus Returns the division x%y
remainder

++ Increment Increases the value ++x


of a variable by 1

-- Decrement Decreases the --x


value of a variable
by 1

Assignment Operators
Assignment operators are used to assign values to variables.

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.
Operator Name Exampl
e

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators
As with comparison operators, you can also test for true (1) or false (0) values
with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical Returns true if both x < 5 && x <


and statements are true 10

|| Logical Returns true if one x < 5 || x <


or of the statements is 4
true

! Logical Reverse the result, !(x < 5 && x


not returns false if the < 10)
result is true

C++ Strings
Strings are used for storing text.

A string variable contains a collection of characters surrounded by double


quotes:

Example
Create a variable of type string and assign it a value:

string greeting = "Hello";

To use strings, you must include an additional header file in the source code,
the <string> library:

Example

// Include the string library

#include <string>

// Create a string variable

string greeting = "Hello";

String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:

Example
string firstName = "John ";

string lastName = "Doe";

string fullName = firstName + lastName;

cout << fullName;

String Length
To get the length of a string, use the length() function:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.length();
cout << "The length of the txt string is: " << txt.size();

Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].

string myString = "Hello";


cout << myString[0];
// Outputs H

Change String Characters


To change the value of a specific character in a string, refer to the index
number, and use single quotes:

Example
string myString = "Hello";

myString[0] = 'J';

cout << myString;

// Outputs Jello instead of Hello

Strings - Special Characters


Because strings must be written within quotes, C++ will misunderstand this
string, and generate an error:

string txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string
characters:

Escape character Result Description

\' ' Single quote

\" " Double quote


\\ \ Backslash

The sequence \" inserts a double quote in a string:

Example

string txt = "We are the so-called \"Vikings\" from the north.";

Sr.No Function & Purpose

strcpy(s1, s2);

Copies string s2 into string s1.

strcat(s1, s2);

Concatenates string s2 onto the end of string s1.


strlen(s1);

Returns the length of string s1.

strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if

s1>s2.

strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
Max and min
The max(x,y) function can be used to find the highest value of x and y:

Example

cout << max(5, 10);

And the min(x,y) function can be used to find the lowest value of x and y:

Example

cout << min(5, 10);

C++ <cmath> Header


Other functions, such as sqrt (square root), round (rounds a number) and log
(natural logarithm), can be found in the <cmath> header file:

Example

// Include the cmath library


#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

The if Statement
Use the if statement to specify a block of C++ code to be executed if a
condition is true.

Syntax

if (condition) {

// block of code to be executed if the condition is true

else {

// block of code to be executed if the condition is false

The else if Statement


Use the else if statement to specify a new condition if the first condition is
false.

int time = 22;


if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed.

This is how it works:

● The switch expression is evaluated once


● The value of the expression is compared with the values of each case
● If there is a match, the associated block of code is executed
● The break and default keywords are optional, and will be described
later in this chapter

The example below uses the weekday number to calculate the weekday name:

Example

int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)

C++ Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

C++ While Loop


The while loop loops through a block of code as long as a specified condition is
true:

Syntax

while (condition) {

// code block to be executed

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

C++ For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Example
for (int i = 0; i < 5; i++) {

cout << i << "\n";

The foreach Loop


There is also a "for-each loop" (introduced in C++ version 11 (2011), which is
used exclusively to loop through elements in an array (or other data sets):

int myNumbers[5] = {10, 20, 30, 40, 50};


for (int i : myNumbers) {
cout << i << "\n";

C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:


Example

for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

cout << i << "\n";

C++ Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example

for (int i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
cout << i << "\n";
}

C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should store:

string cars[4];

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

int myNum[3] = {10, 20, 30};

Get the Size of an Array


To get the size of an array, you can use the sizeof() operator:

int myNumbers[5] = {10, 20, 30, 40, 50};

cout << sizeof(myNumbers);

Result:

20

Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays.

To declare a multi-dimensional array, define the variable type, specify the name
of the array followed by square brackets which specify how many elements the
main array has, followed by another set of square brackets which indicates how
many elements the sub-arrays have:
string letters[2][4];

As with ordinary arrays, you can insert values with an array literal - a
comma-separated list inside curly braces. In a multi-dimensional array, each
element in an array literal is another array literal.

string letters[2][4] = {

{ "A", "B", "C", "D" },

{ "E", "F", "G", "H" }

};

C++ Structures
Structures (also called structs) are a way to group several related variables into
one place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, string,
bool, etc.).

Create a Structure
To create a structure, use the struct keyword and declare each of its members
inside curly braces.

After the declaration, specify the name of the structure variable (myStructure in
the example below):
struct { // Structure declaration

int myNum; // Member (int variable)

string myString; // Member (string variable)

} myStructure; // Structure variable

Access Structure Members


To access members of a structure, use the dot syntax (.):

Example

Assign data to members of a structure and print it:

// Create a structure variable called myStructure

struct {

int myNum;

string myString;

} myStructure;
// Assign values to members of myStructure

myStructure.myNum = 1;

myStructure.myString = "Hello World!";

// Print members of myStructure

cout << myStructure.myNum << "\n";

cout << myStructure.myString << "\n";

Creating Pointers
You learned from the previous chapter, that we can get the memory address of
a variable by using the & operator:

Example

string food = "Pizza"; // A food variable of type string

cout << food; // Outputs the value of food (Pizza)


cout << &food; // Outputs the memory address of food (0x6dfed4)

Modify the Pointer Value


You can also change the pointer's value. But note that this will also change the
value of the original variable:

Example
string food = "Pizza";

string* ptr = &food;

// Output the value of food (Pizza)

cout << food << "\n";

// Output the memory address of food (0x6dfed4)

cout << &food << "\n";

// Access the memory address of food and output its value (Pizza)

cout << *ptr << "\n";

// Change the value of the pointer

*ptr = "Hamburger";

// Output the new value of the pointer (Hamburger)

cout << *ptr << "\n";

// Output the new value of the food variable (Hamburger)


cout << food << "\n";

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.

Create a Function
C++ provides some pre-defined functions, such as main(), which is used to
execute code. But you can also create your own functions to perform certain
actions.

To create (often referred to as declare) a function, specify the name of the


function, followed by parentheses ():

Example Explained
● myFunction() is the name of the function
● void means that the function does not have a return value. You will learn
more about return values later in the next chapter
● inside the function (the body), add code that defines what the function
should do

Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and
a semicolon ;

In the following example, myFunction() is used to print a text (the action),


when it is called:

Example
Inside main, call myFunction():

// Create a function

void myFunction() {

cout << "I just got executed!";

int main() {

myFunction(); // call the function

return 0;

// Outputs "I just got executed!"

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as
variables inside the function.

Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma:
void myFunction(string fname) {

cout << fname << " Refsnes\n";

int main() {

myFunction("Liam");

myFunction("Jenny");

myFunction("Anja");

return 0;

Pass By Reference
In the examples from the previous page, we used normal variables when we
passed parameters to a function. You can also pass a reference to the function.
This can be useful when you need to change the value of the arguments:

Example
void swapNums(int &x, int &y) {

int z = x;

x = y;
y = z;

int main() {

int firstNum = 10;

int secondNum = 20;

cout << "Before swap: " << "\n";

cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum and
secondNum

swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";

cout << firstNum << secondNum << "\n";

return 0;

Pass Arrays as Function Parameters


You can also pass arrays to a function:

Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {

cout << myNumbers[i] << "\n";

int main() {

int myNumbers[5] = {10, 20, 30, 40, 50};

myFunction(myNumbers);

return 0;

Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:

Example

int myFunction(int x)

float myFunction(float x)

double myFunction(double x, double y)

Consider the following example, which have two functions that add numbers of
different type:

Example
int plusFuncInt(int x, int y) {

return x + y;

double plusFuncDouble(double x, double y) {

return x + y;

int main() {

int myNum1 = plusFuncInt(8, 5);

double myNum2 = plusFuncDouble(4.3, 6.26);

cout << "Int: " << myNum1 << "\n";

cout << "Double: " << myNum2;

return 0;

}
Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:

Example
int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

int main() {

int result = sum(10);

cout << result;

return 0;

}
C++ Files
The fstream library allows us to work with files.

To use the fstream library, include both the standard <iostream> AND the
<fstream> header file:

Example

#include <iostream>

#include <fstream>

There are three classes included in the fstream library, which are used to
create, write or read files:

Class Description

ofstream Creates and writes to files

ifstream Reads from files

fstream A combination of ofstream and ifstream: creates,


reads, and writes to files

Create and Write To a File


To create a file, use either the ofstream or fstream class, and specify the
name of the file.

To write to the file, use the insertion operator (<<).

Example
#include <iostream>

#include <fstream>

using namespace std;

int main() {

// Create and open a text file

ofstream MyFile("filename.txt");

// Write to the file

MyFile << "Files can be tricky, but it is fun enough!";

// Close the file

MyFile.close();

Read a File
To read from a file, use either the ifstream or fstream class, and the
name of the file.

Note that we also use a while loop together with the getline() function
(which belongs to the ifstream class) to read the file line by line, and to
print the content of the file:

Example
// Create a text string, which is used to output the text file

string myText;

// Read from the text file

ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the
file line by line

while (getline (MyReadFile, myText)) {

// Output the text from the file

cout << myText;

// Close the file

MyReadFile.close();

C++ Exceptions
When executing C++ code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.

When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw an exception
(throw an error).

C++ try and catch


Exception handling in C++ consist of three keywords: try, throw and
catch:

The try statement allows you to define a block of code to be tested for
errors while it is being executed.

The throw keyword throws an exception when a problem is detected,


which lets us create a custom error.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}

Handle Any Type of Exceptions (...)


If you do not know the throw type used in the try block, you can use
the "three dots" syntax (...) inside the catch block, which will handle
any type of exception:

Example
try {

int age = 15;

if (age >= 18) {

cout << "Access granted - you are old enough.";

} else {

throw 505;

catch (...) {

cout << "Access denied - You must be at least 18 years old.\n";


}

C++ What is OOP?


OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and functions.

Object-oriented programming has several advantages over procedural


programming:

● OOP is faster and easier to execute


● OOP provides a clear structure for the programs
● OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
● OOP makes it possible to create full reusable applications with less code
and shorter development time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.

C++ What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and
objects:

class

Fruit
objects

Apple

Banana

Mango

Another example:

class

Car

objects

Volvo

Audi

Toyota
So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and
functions from the class.

C++ Classes/Objects
C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car has
attributes, such as weight and color, and methods, such as drive and brake.

Create an Object
In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object
name.

To access the class attributes (myNum and myString), use the dot syntax (.) on
the object:

Example

Create an object called "myObj" and access the attributes:

class MyClass { // The class

public: // Access specifier

int myNum; // Attribute (int variable)

string myString; // Attribute (string variable)

};
int main() {

MyClass myObj; // Create an object of MyClass

// Access attributes and set values

myObj.myNum = 15;

myObj.myString = "Some text";

// Print attribute values

cout << myObj.myNum << "\n";

cout << myObj.myString;

return 0;

Class Methods
Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:

● Inside class definition


● Outside class definition

Inside Example
class MyClass { // The class

public: // Access specifier

void myMethod() { // Method/function defined inside the class

cout << "Hello World!";

}
};

int main() {

MyClass myObj; // Create an object of MyClass

myObj.myMethod(); // Call the method

return 0;

Outside Example
class MyClass { // The class

public: // Access specifier

void myMethod(); // Method/function declaration

};

// Method/function definition outside the class

void MyClass::myMethod() {

cout << "Hello World!";

int main() {

MyClass myObj; // Create an object of MyClass

myObj.myMethod(); // Call the method

return 0;

Constructor in C++ is a special method that is invoked automatically at the


time of object creation. It is used to initialize the data members of new
objects generally. The constructor in C++ has the same name as the class
or structure. Constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object which is why it is
known as constructors.
• Constructor is a member function of a class, whose name is same as the
class name.
• Constructor is a special type of member function that is used to initialize
the data members for an object of a class automatically, when an object of
the same class is created.
• Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as
constructor.
• Constructor do not return value, hence they do not have a return type.
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}

void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we create
the object of the class
s.display();
return 0;

Types of Constructors

1. Default Constructors: Default constructor is the constructor which


doesn’t take any argument. It has no parameters. It is also called a
zero-argument constructor.

​ CPP
// Cpp program to illustrate the

// concept of Constructors

#include <iostream>

using namespace std;

class construct {

public:

int a, b;

// Default Constructor

construct()

a = 10;

b = 20;

};

int main()

// Default constructor called automatically

// when the object is created

construct c;

cout << "a: " << c.a << endl << "b: " <<
c.b;
return 1;

Output
a: 10

b: 20

Parameterized Constructors: It is possible to pass arguments to


constructors. Typically, these arguments help initialize an object when it is
created. To create a parameterized constructor, simply add parameters to it
the way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

// Parameterized Constructor

Point(int x1, int y1)

x = x1;

y = y1;

int getX() { return x; }

int getY() { return y; }

};

int main()

// Constructor called

Point p1(10, 15);


// Access values assigned by constructor

cout << "p1.x = " << p1.getX()

<< ", p1.y = " << p1.getY();

return 0;

Output
p1.x = 10, p1.y = 15

Copy Constructor:

A copy constructor is a member function that initializes an object using


another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with
parameters ) for a class, a default constructor( without parameters ) should
also be explicitly defined as the compiler will not provide a default
constructor in this case. However, it is not necessary but it’s considered to
be the best practice to always define a default constructor.
Copy constructor takes a reference to an object of the same class as an
argument.
// Example: Explicit copy constructor

#include <iostream>
using namespace std;

class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor


{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1; copy constructor called


obj2.display();
return 0;
}

Output
ID=10
ID=10

Destructor:

A destructor is also a special member function as a constructor. Destructor


destroys the class objects created by the constructor. Destructor has the
same name as their class name preceded by a tilde (~) symbol. It is not
possible to define more than one destructor. The destructor is only one
way to destroy the object created by the constructor. Hence destructor
can-not be overloaded. Destructor neither requires any argument nor
returns any value. It is automatically called when the object goes out of
scope. Destructors release memory space occupied by the objects created
by the constructor. In destructor, objects are destroyed in the reverse of
object creation.
#include <iostream>
using namespace std;
int count = 0;
class Test {
public:
Test()
{
count++;
cout << "\n No. of Object created:\t" << count;
}

~Test()
{
cout << "\n No. of Object destroyed:\t" << count;
--count;
}
};

main()
{
Test t, t1, t2, t3;
return 0;
}
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
Access Specifiers
he public keyword is an access specifier. Access specifiers define how
the members (attributes and methods) of a class can be accessed. In
the example above, the members are public - which means that they
can be accessed and modified from outside the code.

However, what if we want members to be private and hidden from the


outside world?

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
● protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes. You will learn
more about Inheritance later.

Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside the
class). If you want others to read or modify the value of a private
member, you can provide public get and set methods.

Access Private Members


To access a private attribute, use public "get" and "set" methods:

Example
#include <iostream>
using namespace std;

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}

Why Encapsulation?
● It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better
control of your data, because you (or others) can change one part
of the code without affecting other parts
● Increased security of data

Inheritance
In C++, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:

● 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.

In the example below, the Car class (child) inherits the attributes and methods
from the Vehicle class (parent):

// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}

Multilevel Inheritance
A class can also be derived from one class, which is already derived
from another class.

In the following example, MyGrandChild is derived from class MyChild


(which is derived from MyClass).

Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Derived class (child)


class MyChild: public MyClass {
};

// Derived class (grandchild)


class MyGrandChild: public MyChild {
};

int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}

Multiple Inheritance
A class can also be derived from more than one base class, using a
comma-separated list:

Example

// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Another base class


class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}

Polymorphism
he word “polymorphism” means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
A real-life example of polymorphism is a person who at the same time can have
different characteristics. A man at the same time is a father, a husband, and an
employee.

Types of Polymorphism
● Compile-time Polymorphism.
● Runtime Polymorphism.
Types of Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.

A. Function Overloading

When there are multiple functions with the same name but different parameters,
then the functions are said to be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a
feature of object-oriented programming providing many functions to have the
same name but distinct parameters when numerous tasks are listed under one
function name. There are certain Rules of Function Overloading that should be
followed while overloading a function.
#include <bits/stdc++.h>

using namespace std;


class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " <<
x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " <<
x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " <<
x << ", " << y << endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64

Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading. For example, we can make
use of the addition operator (+) for string class to concatenate two strings. We
know that the task of this operator is to add two operands. So a single operator
‘+’, when placed between integer operands, adds them and when placed
between string operands, concatenates them.
Below is the C++ program to demonstrate operator overloading:
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0,
int i = 0)
{
real = r;
imag = i;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print()
{
cout << real << " + i" <<
imag << endl;
}
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9

Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism. The
function call is resolved at runtime in runtime polymorphism. In contrast, with
compile time polymorphism, the compiler determines which function call to bind
to the object after deducing it at runtime.

A. Function Overriding

Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
#include <bits/stdc++.h>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class" <<
endl;
}

void show()
{
cout << "show base class" <<
endl;
}
};

class derived : public base {


public:

// print () is already virtual function in


// derived class, we could also declared as
// virtual void print () explicitly
void print()
{
cout << "print derived class" <<
endl;
}

void show()
{
cout << "show derived class" <<
endl;
}
};

// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at


// runtime (Runtime polymorphism)
bptr->print();

// Non-virtual function, binded


// at compile time
bptr->show();

return 0;
}
Output
print derived class
show base class

Pure Virtual Functions and Abstract


Classes in C++
Sometimes implementation of all function cannot be provided in a base class
because we don’t know the implementation. Such a class is called abstract class.
A pure virtual function (or abstract function) in C++ is a virtual function for which
we can have implementation, But we must override that function in the derived
class, otherwise the derived class will also become abstract class

A complete example:
A pure virtual function is implemented by classes which are derived from a
Abstract class. Following is a simple example to demonstrate the same.
#include<iostream>
using namespace std;

class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};

int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called

Templates in C++ with Examples


A template is a simple yet very powerful tool in C++. The simple idea is to pass
the data type as a parameter so that we don’t need to write the same code for
different data types.C++ adds two new keywords to support templates:
‘template’ and ‘type name’. The second keyword can always be replaced by the
keyword ‘class’.
How Do Templates Work?
Templates are expanded at compiler time. This is like macros. The difference is,
that the compiler does type-checking before template expansion. The idea is
simple, source code contains only function/class, but compiled code may contain
multiple copies of the same function/class.
Function Templates
We write a generic function that can be used for different data types. Examples of
function templates are sort(), max(), min(), printArray().
#include <iostream>
using namespace std;

// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}

int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;

return 0;
}
Output
7
7
g

Class Templates
Class templates like function templates, class templates are useful when a class
defines something that is independent of the data type. Can be useful for classes
like LinkedList, BinaryTree, Stack, Queue, Array, etc.
#include <iostream>
using namespace std;

template <typename T> class Array {


private:
T* ptr;
int size;

public:
Array(T arr[], int s);
void print();
};

template <typename T> Array<T>::Array(T arr[], int s)


{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}

template <typename T> void Array<T>::print()


{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Output
1 2 3 4 5

You might also like