0% found this document useful (0 votes)
22 views44 pages

Ilovepdf Merged

The document provides an introduction to file management in C programming, explaining the importance of files for data preservation, reusability, and portability. It details the types of files (text and binary), file operations, and functions for reading and writing data. Additionally, it covers the basics of C++ programming, including its features, applications, and structure, along with examples of input/output operations.

Uploaded by

meetvaghasiya287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views44 pages

Ilovepdf Merged

The document provides an introduction to file management in C programming, explaining the importance of files for data preservation, reusability, and portability. It details the types of files (text and binary), file operations, and functions for reading and writing data. Additionally, it covers the basics of C++ programming, including its features, applications, and structure, along with examples of input/output operations.

Uploaded by

meetvaghasiya287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

INTRODUCTION TO FILE

MANAGEMENT

• A file is a container in computer storage devices used for storing


data.

Why files are needed?


• When a program is terminated, the entire data is lost. Storing in a
file will preserve your data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of
time to enter them all. However, if you have a file containing all
the data, you can easily access the contents of the file using a few
commands in C.
• You can easily move your data from one computer to another
without any changes.
4

WHY DO WE NEED
FILE HANDLING /FILE
MANAGEMENT?

• Reusability: The data stored in the file can be accessed,


updated, and deleted anywhere and anytime providing high
reusability.
• Portability: Without losing any data, files can be transferred to
another in the computer system. The risk of flawed coding is
minimized with this feature.
• Efficient: A large amount of input may be required for some
programs. File handling allows you to easily access a part of a
file using few instructions which saves a lot of time and reduces
the chance of errors.
• Storage Capacity: Files allow you to store a large amount of
data without having to worry about storing everything
simultaneously in a program. 5
TYPES OF FILES

In C Programming there are 2 types of files.


1.Text Files.
2.Binary Files.

TEXT FILES

• Text files are the normal .txt files. You can


easily create text files using any simple text
editors such as Notepad.

• When you open those files, you'll see all the


contents within the file as plain text. You can
easily edit or delete the contents.

• They take minimum effort to maintain, are


easily readable, and provide the least security
and takes bigger storage space.

7
BINARY FILES.

• It has an extension of .bin file.


• It can store either 0 or 1 in place of normal
text.
• They can hold a higher amount of data, are not
readable easily, and provides better security
than text files

TEXT FILES AND BINARY FILES.

9
FILE OPERATIONS

• File handling in C enables us to create, update,


read, and delete the files stored on the local file
system through our C program. The following
operations can be performed on a file..

1) Creating a new file


2) Opening an existing file
2) Closing a file
3) Reading from and writing information to a file
4) Moving to a specific location in a file

10

WORKING WITH FILE

• When working with files, you need to declare a


pointer of type file.
• This declaration is needed for communication
between the file and the program.
Declaring Pointer Variable of file:
FILE *fptr;

11
OPENING A FILE - FOR
CREATION AND EDIT

• We are using fopen() function to open a new file


which is included in stdio.h header file.

syntax :ptr = fopen("fileopen","mode");

Ex:fopen("E:\\cprogram\\newprogram.txt","w"
);

• with above sentence if the file named


newprogram.txt doesn’t exists in specified path
this function will create new file and open it in
writing mode.
12

OPENING MODES IN STANDARD I/O

Mode Meaning of Mode During Inexistence of file


If the file does not exist, fopen( )
r Open for reading.
returns NULL.
If the file does not exist, fopen( )
rb Open for reading in binary mode.
returns NULL.
If the file exists, its contents are
w Open for writing. overwritten. If the file does not
exist, it will be created.
If the file exists, its contents are
wb Open for writing in binary mode. overwritten. If the file does not
exist, it will be created.
Data is added to the end of the
a Open for append. file. If the file does not exist, it
will be created.
Data is added to the end of the
ab Open for append in binary mode. file. If the file does not exist, it
will be created.
13
OPENING MODES IN STANDARD I/O

If the file does not exist,


r+ Open for both reading and writing.
fopen( ) returns NULL.

Open for both reading and writing If the file does not exist,
rb+
in binary mode. fopen( ) returns NULL.

If the file exists, its contents


are overwritten. If the file
w+ Open for both reading and writing.
does not exist, it will be
created.
If the file exists, its contents
Open for both reading and writing are overwritten. If the file
wb+
in binary mode. does not exist, it will be
created.

Open for both reading and If the file does not exist, it
a+
appending. will be created.

Open for both reading and If the file does not exist, it
ab+
appending in binary mode. will be create
14

CLOSING A FILE

• The file (both text and binary) should be closed


after reading/writing.

• Closing a file is performed using


the fclose() function.

• we will use fclose(fptr); function to close the


particular file.

• Here, fptr is a file pointer associated with the


file to be closed.
15
READING AND WRITING TO A
TEXT FILE

• For reading and writing to a text file, we use the


functions fprintf() and fscanf().

• They are just the file versions of printf() and


scanf(). The only difference is that fprint() and
fscanf() expects a pointer to the structure FILE.

16

READING A TEXT FILE

Function Description

Use formatted string and variable arguments list to take


fscanf()
input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

17
WRITING TO A TEXT FILE

Function Description

Similar to printf(), this function use formatted string


fprintf()
and varible arguments list to print output to the file.

Prints the whole line in the file and a newline at the


fputs()
end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

This functions write the specified amount of bytes to


fwrite()
the binary file. 18

Example 1: Write to a text file

#include <stdio.h>
printf("Enter num: ");
#include <stdlib.h>
scanf("%d",&num);
int main()
{
fprintf(fptr,"%d",num);
int num;
fclose(fptr);
FILE *fptr;
return 0;
// use appropriate location if
}
you are using MacOS or Linux
fptr =
fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

19
Example 2: Read from a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);
return 0;
} 20

Example 3: Read from a text file


#include <stdio.h>
int main()
{

FILE* demo;
int display;
demo = fopen("demo_file.txt", "r");

while (1) {
display = fgetc(demo);

if (feof(demo))
break;

printf("%c", display);
}

fclose(demo);

return 0;
} 21
Example 4: Read from a binary file
#include <stdio.h>
#include <stdlib.h> // else it will return a pointer
to the file.
struct threeNum { for (n = 1; n < 5; ++n) {
int n1, n2, n3; fread(&num,
}; sizeof(struct threeNum), 1,
int main() fptr);
{ printf("n1: %d\tn2:
int n; %d\tn3: %d\n", num.n1,
struct threeNum num; num.n2,
FILE* fptr; num.n3);
if ((fptr = }
fopen("C:\\program.bin", fclose(fptr);
"rb")) == NULL) {
printf("Error! opening return 0;
file"); }
// If file pointer will
return NULL Output
// Program will exit. n1: 1 n2: 5 n3: 6
exit(1); n1: 2 n2: 10 n3: 11
} n1: 3 n2: 15 n3: 16 22
n1: 4 n2: 20 n3: 21

FSEEK()

• If we have multiple records inside a file and


need to access a particular record that is at a
specific position,
• so we need to loop through all the records
before it to get the record.
• Doing this will waste a lot of memory and
operational time.
• To reduce memory consumption and
operational time we can use fseek() which
provides an easier way to get to the required
data.
• fseek() function in C seeks the cursor to the
given record in the file.

23
Example : use of fseek() in C
#include <stdio.h>
Syntax :
int main() int fseek(FILE *ptr, long int offset,
{ int pos);
FILE* fp;
fp = fopen("test.txt", "r");

// Moving pointer to end


fseek(fp, 0, SEEK_END);

// Printing position of pointer


printf("%ld", ftell(fp));

return 0;
}

24

REWIND()

• The rewind() function is used to bring the file


pointer to the beginning of the file.
• It can be used in place of fseek() when you want
the file pointer at the start.

Syntax :
rewind (file_pointer);

25
Example: the use of rewind

#include <stdio.h>

int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w+");
fprintf(fptr, "Geeks for Geeks\n");

// using rewind()
rewind(fptr);

// reading from file


char buf[50];
fscanf(fptr, "%[^\n]s", buf);

printf("%s", buf);

return 0;
}
26
INTRODUCTION TO C++

• C++ is a general-purpose, object-oriented programming


language developed by Bjarne Stroustup, essentially an
extension of the C language that added features like
inheritance, polymorphism, and abstraction
• More powerful for complex software development; it's widely
used for applications requiring high performance and
flexibility across various industries, including game
development, system programming, and scientific
computing.

HISTORY

• Origin:
C++ was created in the late 1970s at Bell Laboratories by
Bjarne Stroustup, initially called "C with Classes" with the
aim to enhance the capabilities of the C language by
incorporating object-oriented programming concepts.
• Evolution:
Over time, C++ has gone through several revisions and
standardizations, with the ISO C++ Standards Committee playing a
key role in maintaining compatibility across different
implementations.

5
KEY FEATURES OF C++

• Object-Oriented Programming:
C++ fully supports object-oriented paradigms like classes, objects, inheritance, polymorphism, and
encapsulation, enabling code reusability and modularity.
• Memory Management:
Allows for direct memory manipulation through pointers, providing fine-grained control over
memory allocation, which can be crucial for performance-critical applications.
• Generic Programming:
C++ supports templates, which enable writing generic code that can work with different data
types, promoting code flexibility.
• High Performance:
Due to its low-level control and efficient compilation, C++ is often preferred for applications where
speed is critical.
• Platform Independence:
C++ code can be compiled and run on various operating systems with minimal modifications,
making it portable.
6

APPLICATIONS OF C++

• Game Development:
C++ is widely used to create high-performance game engines due to its speed and control over graphics
rendering.
• System Programming:
Operating systems, device drivers, and embedded systems often utilize C++ because of its ability to
directly interact with hardware.
• Scientific Computing:
Numerical simulations and complex algorithms in fields like physics and engineering are frequently
implemented in C++ due to its computational efficiency.
• High-Frequency Trading:
C++ is often used for high-performance trading systems due to its ability to handle large volumes of
data quickly.
• Desktop Applications:
C++ can be used to develop complex graphical user interface applications across different platforms.
7
SETTING UP DEVELOPMENT
ENVIRONMENT (IDES, COMPILERS)

• https://www.youtube.com/watch?v=s6pXKE91_hE

BASIC STRUCTURE OF A C++ PROGRAM

• A basic C++ program structure includes a "main" function where the core logic resides,
utilizes data types to define variable types (like integers, floats, characters), uses variables to
store data, and interacts with the user through input (using "cin") and output (using "cout")
operations within the standard input/output stream.
• Key elements:
1. Header Inclusion:
#include <iostream>: This line includes the standard input/output library, allowing you to
use "cin" and "cout" for basic input and output.
2. Namespace Declaration:
using namespace std;: This line allows you to use standard library elements like "cin" and
"cout" without the "std::" prefix.
3. Main Function:
int main() { ... }: The "main" function is the entry point of your program, where the
execution starts.
9
DATA TYPES

• int: Stores whole numbers (integers) like 1, 2, -5


• float: Stores decimal numbers (floating-point) with single
precision
• double: Stores decimal numbers with double precision
• char: Stores a single character like 'a', '!'
• bool: Stores a boolean value (true or false)

10

VARIABLES AND BASIC INPUT/OUTPUT

• Declaration and Initialization:


data_type variable_name = value;
Example: int age = 25;

• Input (Reading from User):


cin >> variable;
Example: cin >> user_name;
• Output (Displaying to User):
cout << expression;
Example: cout << "Hello, " << user_name << "!" << endl;

11
EXAMPLE PROGRAM

#include <iostream>
using namespace std;
int main( )
{
string name;
int age;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old."
<< endl;
return 0;
}
12

CONTROL STRUCTURES IN C++

The work of control structures is to give flow and logic to


a program. There are three types of basic control
structures in C++.
1.Sequence Structure
Sequence structure refers to the sequence in which
program execute instructions one after another. An
example diagram for the sequence structure is shown in
figure 1.

Figure 1

13
CONTROL STRUCTURES IN C++

2. Selection Structure
Selection structure refers to the execution of instruction
according to the selected condition, which can be either
true or false. There are two ways to implement selection
structures, by “if-else statements” or by “switch case
statements”. An example diagram for selection structure
is shown in figure 2.

Figure
2

14

CONTROL STRUCTURES IN C++

3. Loop Structure
Loop structure refers to the execution of an instruction in
a loop until the condition gets false. An example diagram
for loop structure is shown in figure 3.

Figure
3

15
IF ELSE STATEMENTS IN C++

If else statements are used to implement a selection structure. An example


program for if-else is shown in figure 4.
Figure
4

16

IF ELSE STATEMENTS IN C++

As shown in figure 4, we declared a variable “age” and used “cin" function to gets its value from the user at run
time. At line 10 we have used "if” statement and give a condition “(age<18)” which means that if the age entered
by the user is smaller than "18” the output will be “you cannot come to my party” but if the age is not smaller
than “18” the compiler will move to the next condition.
At line 13 we have used “else if” statement and given another condition “age==18" which means that if the age
entered by the user is equal to "18” the output will be “you are a kid and you will get a kid pass to the party” but
if the age is not equal to the “18” the compiler will move to the next condition.
At line 16 we have used “else" condition which means that if none of the above condition is "true" the output will
be "you can come to the party”.

OUTPUT:

As can be seen in figure 5, that when we entered the age "81" which was greater
than 18, so it gives us the output "you can come to the party”. The main thing to 17
note here is that we can use as many “else if” statements as we want.
Figure
5
SWITCH CASE STATEMENTS IN C++

In switch-case statements, the value of the variable is tested with all the cases. An example program for
the switch case statement is shown in figure 6.

Figure 18

SWITCH CASE STATEMENTS IN C++

As shown in figure 4, we passed a variable “age” to the switch statement. The switch statement will compare the
value of variable “age" with all cases. For example, if the entered value for variable "age” is “18”, the case with
value “18” will be executed and prints “you are 18”. The keyword “break" will let the compiler skips all other
cases and goes out of the switch case statement. An output of the following program is shown in figure 6.

As shown in figure 7, we entered the value “18” for the


variable “age", and it gives us an output "you are 18” and
“Done with switch case”. The main thing to note here is
that after running the “case 18” is skips all the other cases Figure
7
due to the “break” statement and printed “Done with
switch case” which was outside of the switch case
statement. 19
LOOPS IN C++

20

LOOPS IN C++

INFINITE LOOP

21
Procedural Vs Object Oriented
Programming

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided into In object-oriented programming, the program is divided
small parts called functions. into small parts called objects.

Object-oriented programming follows a bottom-up


Procedural programming follows a top-down approach.
approach.

Object-oriented programming has access specifiers like


There is no access specifier in procedural programming.
private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way of Object-oriented programming provides data hiding so it is
hiding data so it is less secure. more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming.

In procedural programming, there is no concept of data In object-oriented programming, the concept of data hiding
hiding and inheritance. and inheritance is used.

Procedural Vs Object Oriented


Programming

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the function is more important In object-oriented programming, data is more important
than the data. than function.

Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.

Procedural programming is used for designing Object-oriented programming is used for designing large
medium-sized programs. and complex programs.

Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.

Code reusability absent in procedural programming, Code reusability present in object-oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Introduction to Object-Oriented
Programming (OOP) concepts

● Object-Oriented Programming or OOPs refers to languages that use objects in


programming.
● Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc in programming.
● The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.

OOPs Concepts:
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
4

Introduction to Object-Oriented
Programming (OOP) concepts

1. Class: A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: 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, Car is the class, and wheels, speed limits, mileage are their properties.
2. Object: It is a basic unit of Object-Oriented Programming and represents the real-life entities. 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. An object has an identity, state, and behavior.
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 type of
response returned by the objects.
For example: “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark, Sleep,
and Eats.

5
Introduction to Object-Oriented
Programming (OOP) concepts

3. Data Abstraction: Data abstraction is one of the most essential and important features of
object-oriented programming. Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or implementation. Consider a real-life example
of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the
car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the
speed is increasing, he does not know about the inner mechanism of the car or the implementation of the
accelerator, brakes, etc in the car. This is what abstraction is.
4. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. In Encapsulation, the variables or data
of a class are hidden from any other class and can be accessed only through any member function of
their class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.

Introduction to Object-Oriented
Programming (OOP) concepts

5. Inheritance: Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability


of a class to derive properties and characteristics from another class is called Inheritance. When we write
a class, we inherit properties from other classes. So when we create a class, we do not need to write all
the properties and functions again and again, as these can be inherited from another class that possesses
it. Inheritance allows the user to reuse the code whenever possible and reduce its redundancy.

7
Introduction to Object-Oriented
Programming (OOP) concepts

6. Polymorphism: The 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. For example, A person
at the same time can have different characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different situations. This is called
polymorphism.

Introduction to Object-Oriented
Programming (OOP) concepts

7. Dynamic Binding: In dynamic binding, the code to be executed in response to the function call is
decided at runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main advantages of
inheritance is that some derived class D has all the members of its base class B. Once D is not hiding any
of the public members of B, then an object of D can represent B in any context where a B could be used.
This feature is known as subtype polymorphism.
8. Message Passing: It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves specifying
the name of the object, the name of the function, and the information to be sent.

9
Defining Class in C++

A class is defined in C++ using the keyword class followed by the name of the class. The
following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};
Example
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
10

};

Syntax to Create an Object

We can create an object of the given class in the same way we declare the variables of
any other inbuilt data type.
ClassName ObjectName;
Example: MyClass obj;
In the above statement, the object of MyClass with name obj is created.

Accessing Data Members and Member Functions

The data members and member functions of the class can be accessed using the dot(‘.’)
operator with the object. For example, if the name of the object is obj and you want to
access the member function with the name printName() then you will have to write:
obj.printName( );

11
// C++ program to illustrate how create a simple class and object
#include <iostream>
#include <string>
using namespace std;

// Define a class named 'Person'


class Person {
public:
// Data members
string name;
int age;
// Member function to introduce the person
void introduce()
{
cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;
}
};
Output
int main()
{ Hi, my name is Alice and I
// Create an object of the Person class am 30 years old.
Person person1;
// accessing data members
person1.name = "Alice";
person1.age = 30;
// Call the introduce member method
person1.introduce();
return 0; 12

Access Modifiers/Specifiers

In C++ classes, we can control the access to the members of the class using
Access Specifiers. Also known as access modifier, they are the keywords that
are specified in the class and all the members of the class under that access
specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
1. Public: Members declared as public can be accessed from outside the
class.
2. Private: Members declared as private can only be accessed within the
class itself.
3. Protected: Members declared as protected can be accessed within the
class and by derived classes.

If we do not specify the access specifier, the private specifier is applied to every
member by default.

13
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h> // include all the standard libraries
using namespace std;
class Geeks {
private:
string geekname;
// Access specifier
public:
// Member Functions()
void setName(string name) { geekname = name; }

void printname() { cout << "Geekname is:" << geekname; }


};
int main()
{
// Declare an object of class geeks Output
Geeks obj1; Geekname is:Abhi
// accessing data member
In this example, we cannot access
// cannot do it like: obj1.geekname = "Abhi";
the data member geekname outside
obj1.setName("Abhi");
the class. If we try to access it in
// accessing member function
the main function using dot
obj1.printname();
operator, obj1.geekname, then
return 0;
program will throw an error.
} 14

Member Function in C++ Classes

There are 2 ways to define a member function:


● Inside class definition
● Outside class definition

Till now, we have defined the member function inside the class, but we
can also define the member function outside the class. To define a
member function outside the class definition,
● We have to first declare the function prototype in the class
definition.
● Then we have to use the scope resolution:: operator along
with the class name and function name.

15
// C++ program to demonstrate member function definition outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
string geekname;
int id; Output
// printname is not defined inside class definition
Geekname is: xyz
void printname();
// printid is defined inside class definition Geek id is: 15
void printid() { cout << "Geek id is: " << id; }
};
Note that all the member functions defined
// Definition of printname using scope resolution operator :: inside the class definition are by default
void Geeks::printname() inline, but you can also make any
{
cout << "Geekname is: " << geekname; non-class function inline by using the
} keyword inline with them. Inline functions
int main() are actual functions, which are copied
{
Geeks obj1; everywhere during compilation, like
obj1.geekname = "xyz"; pre-processor macro, so the overhead of
obj1.id = 15; function calls is reduced.
// call printname()
obj1.printname(); Note: Declaring a friend function is a
cout << endl; way to give private access to a
// call printid()
obj1.printid(); non-member function.
return 0; 16

Constructors

Constructors are special class members which are called by the compiler every time
an object of that class is instantiated. Constructors have the same name as the class
and may be defined inside or outside the class definition.
There are 4 types of constructors in C++ classes:
● Default Constructors: The constructor that takes no argument is called default
constructor.
● Parameterized Constructors: This type of constructor takes the arguments to
initialize the data members.
● Copy Constructors: Copy constructor creates the object from an already
existing object by copying it.
● Move Constructor: The move constructor also creates the object from an
already existing object but by moving it.

17
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id; Output
//Default Constructor Default Constructor called
Geeks()
{ Geek id is: -1
cout << "Default Constructor called" << endl; Parameterized Constructor called
id=-1;
} Geek id is: 21
//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
} Note: If the programmer does not define
}; the constructor, the compiler automatically
int main() {
creates the default, copy and move
// obj1 will call Default Constructor
Geeks obj1; constructor.
cout <<"Geek id is: "<<obj1.id << endl;
// obj2 will call Parameterized Constructor
Geeks obj2(21);
cout <<"Geek id is: " <<obj2.id << endl;
return 0; 18

Destructors

● Destructor is another special member function that is called by the compiler


when the scope of the object ends. It deallocates all the memory previously
used by the object of the class so that there will be no memory leaks. The
destructor also have the same name as the class but with tilde(~) as prefix.

19
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id; Output
//Definition for Destructor Destructor called for id: 0
~Geeks() Destructor called for id: 1
{
cout << "Destructor called for id: " << id <<endl; Destructor called for id: 2
} Destructor called for id: 3
};
Destructor called for id: 4
int main() Destructor called for id: 7
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here
return 0;
} // Scope for obj1 ends here 20

Encapsulation

• Encapsulation, in object-oriented programming, refers to the practice of bundling data


(variables) with the methods that operate on that data within a class, effectively
"hiding" the internal details of an object and only allowing access to its data through
controlled methods called "accessors" (getters) and "mutators" (setters), thus ensuring
data integrity and preventing unauthorized direct modification; this concept is also
known as "data hiding."

• Key points about encapsulation:


Data Hiding:
By making data members private within a class, only the methods defined within that
class can directly access and manipulate them, preventing external code from modifying
the data without going through the designated access methods.
Accessors (Getters):
Public methods that provide a way to retrieve the value of a private data member,
allowing controlled access to the data without directly accessing the variable itself.
Mutators (Setters):
Public methods that allow modification of a private data member, often including
21
validation checks to ensure data integrity before updating the value.
Encapsulation

● Benefits of Encapsulation:
Improved code maintainability:
By hiding internal implementation details, changes to the class structure can be made
without affecting external code that interacts with it.

Data integrity:
Validation checks within mutators can prevent invalid data from being assigned to
variables, ensuring data consistency.

Modular design:
Encapsulation promotes the creation of well-defined, independent objects that can be
easily reused in different parts of the application.

22

Inheritance

• In object-oriented programming, inheritance allows a new class (derived class) to


inherit properties and behaviors from an existing class (base class), creating a
hierarchical relationship; the main types of inheritance are single, multiple, and
multilevel, with access control mechanisms like public, protected, and private defining
how members of the base class can be accessed by the derived class, while member
functions are methods that can be inherited and potentially overridden in the derived
class.

• Types of Inheritance:
Single Inheritance:
A derived class inherits from only one base class, providing a simple "is-a" relationship.
Multiple Inheritance:
A derived class inherits from multiple base classes, allowing it to combine features from
various sources.
Multilevel Inheritance:
A class inherits from a derived class which itself inherits from another base class,
creating a chain of inheritance.
23
Encapsulation

● Access Control:
Public:
Members declared as public can be accessed from anywhere, including outside the class
and in derived classes.
Protected:
Members declared as protected can be accessed within the derived class and its
subclasses, but not from outside the class hierarchy.
Private:
Members declared as private can only be accessed within the class they are defined in, not
even by derived classes.

● Member Functions:
Inherited Member Functions:
When a class inherits from another, it automatically inherits all the member functions
(methods) of the base class.
Overriding Member Functions:
A derived class can redefine a member function inherited from the base class, allowing it
to provide a specialized implementation while maintaining the same function signature.
24

Key points to remember

● Inheritance promotes code reuse by allowing derived classes


to leverage functionalities from the base class.
● Access control mechanisms ensure data protection by
limiting how members of a class can be accessed by other
classes, including derived classes.
● When designing a class hierarchy, carefully consider which
access specifier is appropriate for each member variable and
function to maintain encapsulation.

25
Polymorphism

● In object-oriented programming, "polymorphism" refers to the ability of an object to


take on multiple forms, essentially allowing the same function to behave differently
depending on the context, achieved through mechanisms like function overloading
and virtual functions, which are categorized as either static binding (compile-time) or
dynamic binding (runtime) depending on when the function to be called is
determined;
● "virtual functions" are declared in a base class and overridden in derived classes to
enable dynamic binding, while "pure virtual functions" are virtual functions with no
implementation, forcing derived classes to provide their own definition, making the
base class an "abstract class" that cannot be directly instantiated;
● "function overloading" and "operator overloading" are ways to achieve static binding
by defining multiple functions with the same name but different parameter lists,
allowing the compiler to choose the appropriate function based on the arguments
provided at compile time.
2

Key points

Static Binding (Compile-time Polymorphism):


● Achieved through function overloading and operator overloading.
● The compiler decides which function to call based on the arguments provided at
compile time.
● Considered faster as the decision is made during compilation.

Dynamic Binding (Runtime Polymorphism):


● Achieved using virtual functions declared in a base class and overridden in derived
classes.
● The actual function to be called is determined at runtime based on the object's actual
type.

3
Key points

Virtual Functions:
● A member function declared with the "virtual" keyword in a base class.
● When a pointer to a base class object points to a derived class object, calling a virtual
function on the pointer will invoke the derived class's overridden version.

Pure Virtual Functions:


● A virtual function declared with "= 0" in the base class, meaning it has no
implementation and must be overridden by derived classes.
● A class containing at least one pure virtual function is considered an "abstract class".

Abstract Class:
● A class that cannot be directly instantiated and is meant to be used as a blueprint for
derived classes to implement.

class Animal {
public:
virtual void speak() { // Virtual function
cout << "Generic animal sound" << endl;
}
};

class Dog : public Animal {


public:
void speak() override { // Overridden virtual function
cout << "Woof!" << endl;
}
};

class Cat : public Animal { Output: "Woof!"


public: (dynamic dispatch)
void speak() override {
cout << "Meow!" << endl;
}
};

int main() {
Animal *ptr = new Dog(); // Pointer to base class pointing to a derived class object
ptr->speak();
} 5
Function and Operator Overloading

C++ allows you to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator
overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a
previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the
most appropriate definition to use, by comparing the argument types you have used
to call the function or operator with the parameter types specified in the definitions.
The process of selecting the most appropriate overloaded function or operator is
called overload resolution.

#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
Output:
int main(void) { Printing int: 5
printData pd; Printing float: 500.263
// Call print to print integer Printing character: Hello C++
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
} 7
Function Overloading in C++

You can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.

Operator Overloading in C++

Overloaded operators are functions with special names: the keyword "operator" followed by the symbol
for the operator being defined. Like any other function, an overloaded operator has a return type and a
parameter list.
Box operator+(const Box&);

declares the addition operator that can be used to add two Box objects and returns final Box object. Most
overloaded operators may be defined as ordinary non-member functions or as class member functions. In
case we define above function as non-member function of a class then we would have to pass two
arguments for each operand as follows −
Box operator+(const Box&, const Box&);

#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
9
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume(); Output:
cout << "Volume of Box1 : " << volume <<endl; Volume of Box1 : 210
// volume of box 2 Volume of Box2 : 1560
volume = Box2.getVolume(); Volume of Box3 : 5400
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
} 10

Templates

● In C++, "templates" refer to a mechanism that allows you to


write generic code that can be adapted to different data types
at compile time, with "function templates" creating generic
functions and "class templates" creating generic classes,
while "template specialization" enables you to provide
custom implementations for specific data types within a
template by overriding the default behavior; essentially
tailoring the template for particular situations.

11
Function Templates

• A function template is a generic function definition that uses a


placeholder type parameter (like T) to represent the data type that can be
substituted at compile time.
• This allows you to write a single function that can operate on different
data types without needing to re-implement the logic for each type.
• Example:

template <typename T>


void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}

12

#include <iostream>
using namespace std;

// Template function to swap two values


template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}

int main() {
// Example with integers
int x = 10, y = 20;
cout << "Before swap (int): x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap (int): x = " << x << ", y = " << y << endl;

// Example with floats


float a = 1.5f, b = 2.75f;
cout << "Before swap (float): a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap (float): a = " << a << ", b = " << b << endl;

return 0;
} 13
Class Templates

• A class template is a generic class definition that uses type parameters to


define the structure of a class, allowing you to create different class
instances with different data types.
• This is particularly useful for creating container classes like vectors or
lists that can store various data types.
• Example:

template <typename T>


class MyArray {
public:
void add(T element) { /* ... */ }
T get(int index) { /* ... */ }
private:
std::vector<T> data;
};

14

#include <iostream> int main() {


using namespace std; // Creating objects of class template with
different data types
// Class template definition Box<int> intBox(10);
template <typename T> Box<double> doubleBox(5.5);
class Box { Box<string> stringBox ("Hello, Templates!");
private:
T value; // Displaying values
public: cout << "intBox contains: " <<
// Constructor intBox.getValue() << endl;
Box(T val) : value(val) {} cout << "doubleBox contains: " <<
doubleBox.getValue() << endl;
// Getter function cout << "stringBox contains: " <<
T getValue() { stringBox.getValue() << endl;
return value;
} // Modifying and displaying updated values
intBox.setValue(20);
// Setter function cout << "Updated intBox contains: " <<
void setValue(T val) { intBox.getValue() << endl;
value = val;
} return 0;
}; } 15
Template Specialization

• Template specialization allows you to provide a custom implementation


for a template when a specific type is used as a template argument.
• This enables you to optimize code for particular data types while still
maintaining the generic nature of the template.
• Types of Specialization:

Full Specialization: Defining a complete implementation for a specific


type, overriding the default template behavior for that type.

Partial Specialization: Specifying a custom implementation for a


subset of template parameters, allowing fine-grained control over
different scenarios.

16

Key points to remember

• When using templates, the compiler will automatically generate the


appropriate code for the given data type at compile time.
• Template specialization is a powerful tool for tailoring template
behavior to specific data types, especially when performance
optimizations are needed for particular cases.
• Template arguments can be not only types but also non-type parameters
like integer constants, allowing for even more flexibility.

17
Exception handling

● In programming, exception handling involves using


"try-catch" blocks to identify and manage potential errors
(exceptions) that might occur during code execution, where
the "try" block contains the code that could throw an
exception, and the "catch" block handles the exception if it
occurs; "throwing an exception" is the act of signaling an
error by using the "throw" keyword, and an "exception
specification" (mainly in C++) is a mechanism to explicitly
declare which types of exceptions a function might throw,
allowing for better code clarity and error detection.

18

Key components of exception handling

● Try block: This block encloses the code that might potentially
throw an exception.
● Throw statement: When an error occurs within the "try" block, the
"throw" keyword is used to signal the exception, often passing an
exception object containing details about the error.
● Catch block: This block is executed if an exception is thrown
within the "try" block, and it allows you to handle the exception
based on its type.

19
How it works?

● Execution in "try" block: The code within the "try" block is


executed normally.
● Exception thrown: If an exception occurs within the "try" block,
the program control immediately jumps to the appropriate "catch"
block.
● Exception handling in "catch" block: The "catch" block that
matches the type of the thrown exception is executed, allowing you
to perform error recovery actions such as logging the error or
providing user feedback.

20

Exception specifications (C++ specific)

● Purpose:
In C++, exception specifications are used to explicitly state which
types of exceptions a function may throw, enabling the compiler to
check if a function is potentially throwing exceptions that are not
handled by the calling code.
● Syntax:
A function can be declared with an exception specification using the
"throw()" keyword, followed by a list of exception types that the
function might throw.

21
Example

int divide(int numerator, int denominator) {


if (denominator == 0) {
throw std::runtime_error("Division by zero"); // Throw an exception
}
return numerator / denominator;
}

int main() {
try {
int result = divide(10, 0);
std::cout << result << std::endl; // This line will not be reached
} catch (const std::runtime_error& e) { // Catch the specific exception
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
22

Key points to remember

• Specific exception handling:


Always try to catch specific exception types rather than using a
generic "catch" block to ensure proper error handling.
• Exception hierarchy:
When designing your own exception classes, consider creating an
inheritance hierarchy to categorize different types of exceptions.
• Stack unwinding:
When an exception is thrown, the program execution unwinds the
call stack, automatically cleaning up resources allocated in the
function calls leading up to the exception.

23

You might also like