Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Topics

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

Topics:

 Programs Structure and Working


 Variables and Comments
 Variable Declaration
 Types of Comments
 Datatypes in C++ = Primitive, Non-primitive, Derived
 Scope of Variable ( Local & Global )
 Rules for Variable Names
 Basic Input Output
 Header Files ( System & User-Defined )
 Operators
 Reference Variables
 Typecasting
 Constants, Manipulators and Operator Precedence
 Control Structures or Conditional Statements
 Pointers in C++
 Double Pointer or Pointer to Pointer
 Arrays and Pointer Arithmetics
 Structure, Union and Enum
 Functions and Function Prototypes
 Call by Value and Call by Reference
 Inline Functions, Default Arguments and Constant Arguments
 Recursion and Recursive Functions
 Function Overloading
 Object Oriented Programming
 Classes and Objects
 Access Modifiers
 Nesting of Member Functions
 Object Memory Allocation
 Static Variables & Methods
 Array of Object
 Passing Object as Argument to the Function
 Friend Functions
 Friend Classes and Member Friend Function
 Constructors
 Parameterized and Default Constructor
 Constructor Overloading
 Constructors with Default Arguments
 Dynamic Initialization of Objects Using Constructors
 Copy Constructor
 Destructor
 Inheritance
 Syntax and Visibility Mode
 Multiple Inheritance
 Ambiguity Resolution in Inheritance
 Virtual Base Class
 Constructors in Derived Classes
 Initialization List in Constructors
 Dynamic Memory Allocation and De-allocation using Pointers
 Pointers to Objects and Arrow Operator
 Array of Objects
 This Pointer
 Polymorphism
 Base Class Pointers to Derived Classes
 Virtual Functions
 Abstract Base Class & Pure Virtual Functions
 File I/O
 Reading and Writing in Files
 Templates
 Templates with Multiple Parameters
 Templates with Default Parameters
 Function Template and Function Template with Parameters
 Member Function Templates & Overloading Template
Functions
 Standard Template Library ( STL )
 Containers in STL
 Vectors in STL
 List in STL
 Map in STL
 Function Objects (Functors)
- C++ NOTES –

PROGRAM STRUCTURE AND WORKING :

C++ Program  Compiler(G++)  .exe File (For execution)

#include<iostream>

using namespace std;

int main()

cout<<”Hello World”;

return 0;

Here, iostream is the header file which is important for the cpp programs to
perform input, output and many other operations , and it is added to the
program by including it using #include.

main() is the starting function and ‘int’ denotes its return type i.e. Integer. Cpp
doesn’t consist of “void main()”.

“std” is the standard namespace which is used throughout the program,


iostream consist of the function “cout” for outputting the data on to the
terminal. We use the “cout” method with the “std” for specifying its
appropriate operation.

If the line “using namespace std;” is not specified, then we should use the
methods with “std” explicitly, e.g. std::cout<<”Hello world!”;

VARIABLES AND COMMENTS :

Variables are the containers to store the values of different types.

Comments are strings to provide more info. about any block of code.
Variable Declaration Syntax :

Datatype variable_name = value;

OR

Datatype variable_name;

Types of Comments

Single line comment  e.g. //This is single line comment.

Multi line comment  e.g. /* This is multi line comment */

Datatypes in C++

1)Primitive/Primary/Built-in Datatypes

char ( 1 byte ) : Stores single character

string ( user definable ) : Stores string of characters

bool ( 1 byte ) : To denote true or false ( 1 or 0 )

byte ( 1 byte ) : Stores a byte number

int ( 2/4 bytes ) : Stores an integer number of 2/4 bytes size

float ( 4 bytes ) : Stores floating point number of 4 bytes size

double ( 8 bytes ) : Stores floating point number with higher precesion

long ( 8 bytes ) : Can be used solely or with int, float or double

short (2 bytes ) : Can be used solely or with int, float or double

signed ( 4 bytes ) : Can be used with char, int, float & double. ((+,-) values)

unsigned ( 4 bytes ) : Can be used with char, int, float & double. (+ values only)
2)Non-Primitive/Secondary/User-defined Datatypes

struct, union and enum

3)Derived Datatypes

Arrays, Functions and Pointers

Scope of Variables

Local Scope : Within the specific function or block of code

Global Scope : Throughout the program, within all the block of codes.

Note : We can have the local and global variables with same name, but it can
create confusion sometimes. Also, whenever called in the function or any block
of code, the local variable will be considered for use and the global variables
value will be ignored. So it is recommended to create global and local variables
with different names. But if we want to access the global variable value then
we use the scope resolution operator i.e. ( :: ) e.g. ::variable_name.

Rules for variable names

Variable name can range from 1 to 255 characters.

Begins with alphabet or underscore ( _ )

Can contain alphanumeric characters and underscores ( _ )

Variable names are case sensitive

No spaces and special character allowed

Don’t use any reserved keyword in C++


Basic Input/Output in C++

C++ comes with libraries (iostream) which helps us in performing input/output.


In C++ sequence of bytes corresponding to input and output are commonly
known as streams.

Input Stream : Direction of flow of bytes takes place from input device (e.g.
keyboard) to the main memory.

Output Stream : Direction of flow of bytes takes place from main memory to
the output device (e.g. Display)

E.g. Sum of two user provided numbers.

#include<iostream>
using namespace std;

// cout --> Function for displaying output.


// cin --> Function for taking input.

// ( << ) This symbol used with cout is called Insertion


operator.
// ( >> ) This symbol used with cin is called Extraction
operator

int main()
{
int num1, num2;
cout<<"Enter the value of num1 : \n";
cin>>num1;

cout<<"\nEnter the value of num2 : \n";


cin>>num2;

cout<<"\nSum of two numbers is : "<<num1+num2;


return 0;
}
Header Files in C++

Two types of header files :

1)System header files : It comes with the compiler

We can include the system header file as below:

#include<iostream>

NOTE : Refer “cppreference.com” for knowing all system header files and
other stuff related to C++

2)User defined header files : It is written by the programmer

We can include the user defined header file as below:

#include “filename.extension”

Operators in C++

Arithmetic Operators ( +, -, *, /, % )

Increment-Decrement Operators ( ++, -- ) ( pre-increment & post-increment )

Relational/Comparison Operators ( <, <=, >, >=, ==, != )

Logical Operator ( &&, ||, ! )

Conditional/Terinary Operator ( Exp1 ? Exp2 : Exp3; )

Assignment Operators ( Simple : (=) , Compound : (+=, -=, *=, /=, %=) )

Special Operator ( ( , ), ( & (address of variable)), ( sizeof ) )

Bitwise Operator ( &, |, ^ (XOR), << (L Shift), >> (R Shift), ~ (One’s Compliment))

Scope Resolution Operator ( :: ) ( e.g. = ::Global_Variable)


NOTE : Arithmetic operations between different datatype values :

int & int = int

float & int = float

float & float = float

Reference Variables in C++

If we refer a single value/literal with multiple variable names i.e. multiple


variable names will point or refer to a single value, then it is called as reference
variables.

We can create reference variable using the special operator ( & ).

e.g. Below both x and y will have the same value. Address of x and y is same.

float x = 123;

float & y = x;

Here, x and y are the same variable but with two different names, y is not the
copy of the x. They both have the same address.

NOTE : When passing the decimal-point value to a function or block of code,


such value by default is of the double datatype, therefore we can append some
character/suffix at the end of the value/literal to specify it as of a particular
datatype. For e.g. 3.14 is double by default and 3.14f or 3.14F is now a float
datatype value. We can append ‘L or l’ for long double type.

Typecasting in C++

Convert the variable from one datatype to another.

e.g. Use datatypes within brackets i.e. (datatype) to typecast the variable.

float var = 10.923;

int casted = (int)var;


You can also do the typecasting similar to python.

e.g. Use the datatype and pass the variable in brackets.

int var = 10;

float casted = float(var);

Constants, Manipulators and Operator Precedence

Constants are the values which can’t be changed. We use the ‘const’ keyword
to create a constant variable.

e.g. Here, ‘var’ is a constant and its value cannot be changed in the program.

const int var = 154;

Manipulators are the keywords or characters which helps to format your data
display or decide how the data/information should be printed or displayed.
There are many manipulators but two are mostly used:

endl = To get to new line ( cout<<”hello”<<endl<<”world”; )

setw(value) = To set the field width ( cout<<setw(2)<<15<<endl<<setw(4)<<1; )

The header file “iomanip” consist of several manipulators and the setw()
manipulator is also provided by the “iomanip” header file. Therefore to use
setw() we need to include the “iomanip” header file.

Operator precedence decides how an arithmetic equation will be


calculated/solved by the C++ program. It is like the ‘BEDMAS’ rule in
mathematics. Here, concept of associativity is also involved.

The precedence is the power of the operators to get resolved first. The
precedence of the operators is as below:

::  (a++, a--, (), [] )  (--a, ++a, &, sizeof)  (*, /, %)  (+, -)


Here, the operators like ( *, /, % ) has more precedence than the operators like
( +, - ) therefore multiplication, division and modulus will be resolved first.

Associativity lies when the operators has the same precedence, for e.g. ( +, - ).
The associativity may flow from left-to-right direction or vice versa, therefore
the operators with same precedence are resolved as per their occurrences
from left to right or right to left depending on to their associativity. The ( +, - )
operators have the associativity from left to right.

e.g. int c = a*5+b-d+10;  ((((a*5)+b)-d)+10)

Control Structures or Conditional Statements in C++

There are three types of control structures :

Sequence Structure  Procedural structure i.e. Functions

Selection Structure  (if-else, Nested if-else, if-else-if ladder, switch case)

Loop Structure  for, while, do-while

Pointers in C++ :

Pointer is a variable which stores the reference/address of the other variables.

E.g. Here, a pointer p points to the address of a variable var.

int var = 10;

int *p = &var;

NOTE : The datatype of the pointer variable should be the same as the
datatype of the variable whose address is been stored by the pointer. In the
above example it is ‘int’.

*p var
200 10

Add : 100 Add : 200


Now, to print the address of ‘var’ we can do it by printing ‘&var’ or ‘p’.

To print the value of ‘var’, we can do it by printing the ‘var’ variable directly or
using the dereference operator i.e. ‘*p’. ( output is 10 )

To print the address of the pointer variable, we can print ‘&p’.

Double Pointer or Pointer to Pointer

Pointer that points to another pointer is called as the double pointer or the
pointer to pointer.

E.g.

int var = 10;

int *p = &var;

int **p2 = &p;

NOTE : Here, var=10, p=&var, *p=10, p2=&p, *p2=p, **p2=10;

Arrays and Pointer Arithmetic in C++

Arrays are the contiguous and equal blocks of memory which stores the values
of homogenous/specific datatype.

All values can be accessed by indexing in a serial order.

E.g. int var[3] = {1,2,3};

The above code creates 3 blocks of memory of 4 bytes each as the int datatype
holds up the values of 4 bytes. These blocks have contiguous memory
addresses, for e.g. 100, 104, 108. The arrays can be traversed by indexing and
the index of first block is 0.

NOTE : In the concept of arrays, the name of the array itself denotes the
memory address of the first block of the array. In the case of the above
example, “var” denotes the address of the first memory block of the array. If
we use “&var” to denote memory address then it will give an error.

We can get the pointer to the fist block of the array as follows :

E.g. int var[3] = {1,3,5};

int *p = var;

Now we can perform the pointer arithmetic’s on pointer “p”.

Here, p++ or p += 1 will increment the pointer to the memory address of the
next block in the array and p-- or p -= 1 will do the vice versa.

We can dereference the pointer (*p) to get the value stored at that address.

Pointer Arithmetic Formula :

new_address = current_address + i * sizeof(datatype)

i is the number of increment or decrement, for e.g. p += i or p -= i

current_address is holded by the pointer p.

Structure, Union and Enum in C++

These are the user defined datatypes in C++.

Structure is used to create a template or blueprint to store multiple values of


different datatype. It is creating a new datatype which combines various built-
in datatypes to store multiple values in it.

E.g.

struct emp

int ID;

string name;

};
Now, “struct emp” is a datatype which can be used to create multiple variables
as shown below :

struct emp var1, var2, var3 ;

We can also create variables while declaring the structure as below :

struct emp{

int ID;

string name;

} var1, var2, var3;

It is just like creating an object for a class. We can access the elements of the
structure using the dot(.) operator. For e.g. var1.ID and var1.name

You can shorten the name of your struct datatype created by using typedef
keyword which is used to replace the name of the datatype to another name.

E.g.

typedef struct employee{

int ID;

string name;

} emp;

Now, we can use the datatype “emp” (shortened) to create variables as shown
below :

emp var1, var2, var3;

NOTE : The size of the structure is the sum of the sizes of the elements in it.
This is because each element/variable in the structure gets an amount of
memory size based upon its datatype. Each element has its separate memory.
Union is similar to struct but the difference in between both is that, the
elements in the union don’t have the separate memory. All the elements
shares the memory among themselves. The size of the union is equal to the
size of the largest element in it. The size of the largest element in the union is
shared by all the elements in it.

If we assign the value to an element in the Union, it utilizes the memory. Then
we can perform the operations on that particular element immediately after
the value is assigned to it. After that we can assign the value to next element
and perform operations over it, meanwhile the value assigned to the previous
element will be vanished as the memory is now utilized by the new element.

E.g.

union employee

int ID;

float sal;

};

union employee emp;

emp.ID = 10; // ID is now set, all the memory is allocated now.

cout<<emp.ID<<endl;

emp.sal = 100000f // memory is now taken from ID and allocated to sal.

cout<<emp.sal<<endl;

Enum is a list of items where the items has sequential numbers assigned to it
starting from 0, 1, 2 … n. Therefore, the first item in enum stores 0, second
item stores 1 and so on. Now you can assign these items to any variable to
assign the number associated with them.

The list of items in the enum consist of a name and all the items are enclosed
between the curly brackets { item1, item2, item3 … itemN }.
E.g.

enum Meal{ breakfast, lunch, dinner };

cout<<breakfast<<endl; // 0

cout<<lunch<<endl; // 1

cout<<dinner<<endl; // 2

Functions and Function Prototypes in C++

Library Functions ( Functions in the libraries )

main() Function ( Start of the execution of program )

User defined Function ( parameterized or non-parameterized )

Function Prototyping is used when you write the user-defined functions below
the main() function. Function prototyping should be done to avoid error in
such cases.

E.g.

int sum( int , int ); // This is function prototyping…

int diff( int a, int b ); // This is another form of function prototyping…

int main()

cout<<”The sum is : “<<sum(45, 55);

return 0;

int sum(int a, int b) { return a+b; } //Here, a and b are formal parameters.

int diff(int a, int b) { return a-b; } //Here, a and b are formal parameters.
Call by Value and Call by Reference in C++

In call by value method, a copy of the original variable is been made and it is
passed to the function as the argument. On the other hand the function
receives the copy of the actual variable and treats it as its parameter.

In call by reference method, the reference or the address of the variable is


been passed as an argument to the function. On the other hand the function
also receives the address or the reference of the variable as a pointer and
performs operations over the value at that location.

E.g. Call by Value

int increment( int a ){

return ++a; }

int main(){

int value = 10;

cout<<increment(value)

return 0; }

E.g. 1) Call by Reference

int increment( int *a){

*a = *a+1;

return 0; }

int main(){

int value = 10;

cout<<value<<endl; // 10

increment(&value);

cout<<value<<endl; // 11

}
E.g. 2) Call by Reference ( Using the reference variable )

int increment( int &a){

a = a+1;

return 0; }

int main(){

int value = 10;

cout<<value<<endl; // 10

increment(value);

cout<<value<<endl; // 11

Inline Functions, Default Arguments and Constant Arguments

Inline functions are implemented by using the inline keyword. When we call
the function and pass some arguments, then the copy of the arguments is
passed to the function and the value is then processed and returned. It takes a
lot of time. So to reduce the time complexity we can use the inline function.
The inline function does everything( copying of arguments, passing and calling
function etc. ) at the compile time itself thus reducing the time complexity.

E.g.

inline int product( int x, int y ) {

return x*y;

int main() {

cout<<product(50,100)<<endl;

return 0; }
NOTE : Use the inline functions only when the functions implementation is
small and it is been called frequently throughout the program. If we make all
the functions inline or the large functions inline, then it will take up most of the
cache memory and the program size will increase, thus increasing the space
complexity.

Default argument is the function parameter with a pre-provided value to it. We


can pass a new value to the parameter or else the function will use the default
value.

E.g.

void message( string country = “India” ) {

cout<<”I am from <<country<<endl;

int main() {

message();

message(“Sweden”);

NOTE : The default argument should always be written at the last in the
parameters list of the function, i.e. at the right most side.

E.g. int function( par1, par2 … parN, default_arguments){ }

Constant arguments are those function parameters whose value cannot be


changed or altered in the function. We use the const keyword to specify the
constant argument in the parameter list of the function.

E.g. int strlength( const string str ) { }


Recursions and Recursive Functions in C++

Function which calls itself repeatedly until the condition is met, then it is called
the Recursive Function.

E.g. Factorial of the number using recursion.

int factorial( int num ){

if( num<=1 ){

return 1;

return num * factorial( num – 1 );

Function Overloading in C++

Consist of multiple functions with same name but different parameter list.

E.g.

int add( int a, int b ){

return a+b;

int add( int a, int b, int c){

return a+b+c;

int main(){

cout<<add(25,50)<<endl;

cout<<add(25,50,75)<<endl;

return 0; }
Object Oriented Programming in C++

Concepts in OOP’s :

Classes = Basic template for creating objects

Objects = Basic run time entities

Variables and Methods = Data/Elements of the class

Access Modifiers = To determine the access scope of the class element

Dynamic Binding = Code that executes is not known until the program runs.

Message Passing = Object.message(Information) call format

Four Pillars of OOP’s :

Encapsulation = Combining variables and methods into class.

Inheritance = Class inheriting variables and methods of another classes.

Polymorphism = Function Overloading and Overriding.

Abstraction = Hiding the implementations or data.

Classes and Objects in C++

E.g. Template for employee

Class Employee {

private:

int a,b,c;

public:

int d, e;

void setData( int a1, int b1, int c1 );


void getData() {

cout<<a<<endl<<b<<endl<<c<<endl<<d<<e;

};

void Employee :: setData( int a1, int b1, int c1 ) {

a = a1;

b = b1;

c = c1;

int main() {

Employee obj;

obj.setData(10, 20, 30);

obj.d = 40;

obj.e = 50;

obj.getData();

Access Modifiers in C++

Access modifiers can be used with classes, class variables and methods. Default
access modifier is Public. Following are the accessibility of the class and its
elements with various access modifiers :

Access Modifiers Within the Class Sub Class Outside the Class
Public Yes Yes Yes
Private Yes No No
Protected Yes Yes No
Nesting of Member Functions in C++

Nesting of member functions means to call a function inside another function.

E.g.

void display(string name){

cout<<”Hello ”<<name<<endl;

void read(){

string name;

cout<<”Enter your name : “;

cin>>name;

display(name); //Nesting of Member Function…

Object Memory Allocation in C++

Memory is not allocated when we create classes. It is allocated when the


object is created. Each object has its own copy of class variables and functions
are shared in common so separate copy of methods is not made for each
object.

Static Variables & Methods in C++

Static members are common to all the objects. No separate copy of the static
members are made for separate objects. All the objects shares the same static
variables or methods. The static variables created in methods is by default
initialized to zero(0). The static method in the class can access only the static
variables or other static methods in the class and such static method can be
executed using the name of the class not even creating the object of the class.
Array of objects in C++

If there is a need to create multiple number of objects for a class then we can
use the array of objects to create multiple objects using a single name. Array of
objects is same as creating array of any other datatype like integer or float.

E.g. Creating array of objects of class Employee.

int main() {

Employee obj[5]; // Use these objects by indexing.

return 0;

Passing Object as an Argument to the Function

We can pass the objects as an argument to the function in similar manner to


that we pass any variable of any other datatype to the function.

E.g. Addition of Complex numbers


#include <iostream>
using namespace std;

class complex
{

int a, b;

public:
void setData(int v1, int v2)
{
a = v1;
b = v2;
}

void setDataBySum(complex o1, complex o2)


{
a = o1.a + o2.a;
b = o1.b + o2.b;
}
void printNumber()
{
cout << "Your complex number is : " << a << " + i" << b << endl;
}
};

int main()
{
complex c1, c2, c3;

c1.setData(1, 2);
c1.printNumber();
c2.setData(3, 4);
c2.printNumber();

c3.setDataBySum(c1, c2);
c3.printNumber();
return 0;
}

Friend Function in C++

Friend function is the function with any return type. The friend function can
access the private members of the class and it lies outside the class. However,
we need to declare the friend function inside the class but the implementation
is written outside the class. The friend function is not the member of the class,
it is a separate function outside the class but it has permission to access the
data of the class weather it may be of any access specifier.

E.g. Addition of two complex numbers


#include<iostream>
using namespace std;

class complex
{
int a, b;

public:
friend complex sumComplex(complex o1, complex o2);

void setNumber(int num1, int num2)


{
a = num1;
b = num2;
}

void showNumber()
{
cout<<"Your number is : "<<a<<" + i"<<b<<endl;
}
};

complex sumComplex(complex o1, complex o2)


{
complex obj;
obj.setNumber((o1.a + o2.a),(o1.b + o2.b));
return obj;
}

int main()
{
complex ob1, ob2, sum;
ob1.setNumber(4,8);
ob2.setNumber(5,9);
ob1.showNumber();
ob2.showNumber();

sum = sumComplex(ob1,ob2);
sum.showNumber();
return 0;
}

Friend Classes and Member Friend Function in C++

If we want to access the data of one class into another class then we can use
the friend classes concept in C++. As we make the friend function by declaring
it inside the class, similarly we declare another class as friends in the original
class.

E.g. Addition of complex numbers.


#include<iostream>
using namespace std;

class complex; //Forward Declaration of class. Required to create method "add"


with return type complex in Calculator
class Calculator
{
public:
complex add(complex o1, complex o2); // Forward declaration to access the
variables a and b of complex class
};

class complex
{
int a,b;

public:
// friend complex Calculator :: add(complex o1, complex o2); //Making
friends with an individual method/Member friend function.
friend class Calculator; // This is Friend class.

void setNumber(int val1, int val2)


{
a = val1;
b = val2;
}

void showNumber()
{
cout<<"Your number is : "<<a<<" + i"<<b<<endl;
}
};

complex Calculator :: add(complex o1, complex o2)


{
complex sum;
sum.setNumber((o1.a + o2.a),(o1.b + o2.b));
return sum;
}

int main()
{
complex obj1, obj2, result;
Calculator obj;

obj1.setNumber(4,8);
obj2.setNumber(6,4);

obj1.showNumber();
obj2.showNumber();

result = obj.add(obj1,obj2);
result.showNumber();
return 0;
}

Constructors in C++

Constructor is the special member function which has the same name as the
class name. It is automatically invoked when the object of the class is created.
Constructors are generally used to initialize the private variables of the class.
The code inside the constructor is executed once the object of that class is
created. The Constructor has no return type and should be declared in the
public section of the class.

E.g.
#include<iostream>
using namespace std;

class Sum
{
int a,b;

public:

Sum(int v1, int v2)


{
a = v1;
b = v2;
}

void ShowSum()
{
cout<<"\nThe Addition of Two Numbers is : "<<a+b<<endl;
}
};

int main()
{
Sum obj(10,20);
obj.ShowSum();
return 0;
}
Parameterized and Default Constructors In C++

Parameterized Constructor is the constructor with parameters. We can pass


the parameters to the constructor and initialize them to the variables or can
perform some other task as well. We can pass the arguments to the
constructor in two ways  Implicit Call and Explicit Call.

E.g.
#include <iostream>
using namespace std;

class complex
{
int a, b;

public:
complex(int, int);

void display()
{
cout << "Complex Number is : " << a << " + i" << b << endl;
}
};

complex ::complex(int x, int y)


{
a = x;
b = y;
}

int main()
{
complex a(10, 12); // Implicit Call
complex b = complex(15, 45); // Explicit Call

a.display();
b.display();

return 0;
}

If the constructor of the class is not written and implemented by the user then
the default constructor is executed on creation of the object.
Contructor Overloading in C++

Constructor Overloading includes creating more than two number of


constructors with different parameter list. It is same as the function
overloading.

E.g.
#include<iostream>
using namespace std;

class area
{
public:
area(float side)
{
cout<<"Area of Square is : "<<(side*side)<<endl;
}
area(float base, float height)
{
cout<<"Area of Triangle is : "<<(0.5*(base*height))<<endl;
}
};

int main()
{
area square(10.5); //Implicit Call
area triangle = area(5,10); //Explicit Call
return 0;
}

Constructors with Default Arguments in C++

It is same as the functions with default arguments. The default arguments has
an value assigned to them, if the value to the argument is provided by the user
then that value is used, but if the value is not provided explicitly by the user
then the default value is been used.

E.g.
#include<iostream>
using namespace std;
class Info
{
string name, country;

public:

Info(string nm, string ctry = "India")


{
name = nm;
country = ctry;
}

void display()
{
cout<<"Hello, My name is "<<name<<" and I am from
"<<country<<"."<<endl;
}
};

int main()
{
string name,country;

cout<<"\nEnter Your Name : ";


cin>>name;
cout<<"\nEnter Your Country : ";
cin>>country;

Info obj1(name, country);


Info obj2 = Info("Suraj");

obj1.display();
obj2.display();

return 0;
}

Dynamic Initialization of Objects Using Constructors in C++

It is used in case of the Constructor Overloading, where there are various


constructors with different parameters. The objects are initialized dynamically
at the run time of the program depending on the user input.
E.g.
#include <iostream>
using namespace std;

class Emp
{
public:
Emp() {}

Emp(string empname, float sal);


Emp(int empid, float sal);
};

Emp::Emp(string empname, float sal)


{
cout << "\nEmployee " << empname << " has a salary of " << sal << endl;
}

Emp::Emp(int empid, float sal)


{
cout << "\nEmployee with id " << empid << " has a salary of " << sal <<
endl;
}

int main()
{
string name;
int id;
float salary;

Emp obj1, obj2; // Empty Constructor ( Emp(){} ) Called.

cout << "\nEnter the Employee Name and Salary : ";


cin >> name >> salary;
obj1 = Emp(name, salary);

cout << "\nEnter the Employee Id and Salary : ";


cin >> id >> salary;
obj2 = Emp(id, salary);

return 0;
}
Copy Constructor in C++

Copy Constructor is used to use the copy of the object of a class. We pass the
reference/copy of the object as an argument to the constructor. We can create
a new object using the data of the argument object.

NOTE : Compiler can create maximum of 2 constructors on its own. First one is
the default constructor and second is the copy constructor. If we create our
own constructor in the class then the compiler creates only a copy constructor
if not created. If no constructor is created at all, then compiler creates a
default constructor.

E.g.
#include <iostream>
using namespace std;

class Copy
{
int a;

public:
Copy() { a = 0; } // Default Constructor

Copy(int value)
{
a = value;
}

/*
Copy(Copy &obj) // Copy Constructor
{
cout << "\nCopy Constructor Called!" << endl;
a = obj.a;
}
*/

void show()
{
cout << "Value is : " << a << endl;
}
};

int main()
{
Copy obj1(10), obj2, obj3, obj4;
obj1.show();
obj2.show();

obj3 = obj1; // Copy Constructor Not Called!


obj3.show();

obj4 = Copy(obj2); // Copy Constructor Called (Created by Compiler)


obj4.show(); // Decomment the above created copy constructor and run
again.

Copy obj5 = Copy(obj1); // Copy Constructor Called (Created by Compiler)


obj5.show(); // Decomment the above created copy constructor
and run again.

return 0;
}

Destructors in C++

Destructor is a Function which is opposite to the Constructor. Whenever the


object is created, its constructor is called and then the object gets its memory
allocated for its data and variables. The Destructor on other hand destroys or
frees up all the memory and resources consumed by the object, once the work
of the object is done at the end of the block of code.

Destructor is written as same as the constructor i.e. it has the same name as of
the class with a tilde( ~ ) sign in front of it. Destructor never takes any
argument nor does it returns any value.

E.g.
#include <iostream>
using namespace std;

int count = 0;

class Num
{
public:
Num()
{
count += 1;
cout << "\nConstructor for object number " << count << endl;
}

~Num()
{
cout << "\nDestructor for object number " << count << endl;
count -= 1;
}
};

int main()
{
cout << "\nMain Function Start!\n";
Num n1;

{
cout << "\nEntering Block\n";
Num n2, n3;
cout << "\nExiting Block\n";
}
cout << "\nMain Function End!\n";

return 0;
}

Inheritance in C++

Inheritance is a concept of Object Oriented Programming in C++. It is used to


reuse the classes to make another class. A class( Derieved Class ) can reuse the
variables and methods of another class( Base Class ) thus reducing redundancy
of code and reducing efforts, time and cost.

There are 5 types of inheritance in OOP’s :

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
Inheritance Syntax and Visibility Mode in C++

Syntax for writing the derived class in C++ is as follows:

Class {{derived-class-name}} : {{visibility-mode}} {{base-class-name}}

Body of Class….

};

NOTE : The private members of the base class can never be inherited in the
derived class.

There are three visibility modes in C++  Public, Private & Protected

Default visibility mode is Private Visibility Mode.

Public = It means that the derived class can access the public and protected
members of the base class, but not the private members of the base class. The
protected members of the base class remains protected members in the
derived class and public members of the base class remains public in the
derived class.

Private = It means that the derived class can privately access the public and
protected members of the base class, but cannot access the private members
of the base class. The public and protected members of the base class becomes
private in the derived class.

Protected = It means that the derived class can access the public and protected
members of the base class protectively, but cannot access the private
members of the base class. The public and protected members in the base
class becomes protected in the derived class.

Multiple Inheritance in C++

Syntax of Multiple Inheritance in C++ is as follows :


Class {{derived-class-name}} : {{visibility-mode}} {{base-class-1}} , {{visibility-
mode}} {{base-class-2}} , {{visibility-mode}} {{base-class-n}}

Body of Class….

};

Ambiguity Resolution in Inheritance in C++

Ambiguity arises in the cases of multiple inheritance when two or multiple


base classes have the same function/method in them. Now the ambiguity
arises that which method will be considered or executed in the derived class
which inherits all the base classes with same method.

We need to resolve the ambiguity by using the scope resolution operator for
calling a particular method from a particular class.

E.g.
#include<iostream>
using namespace std;

class Base1
{
public:
void greet()
{
cout<<"\nHello, How are you?"<<endl;
}
};

class Base2
{
public:
void greet()
{
cout<<"\nHi, What's up?"<<endl;
}
};

class Derived : public Base1, public Base2


{
public:
void greet()
{
Base1::greet(); //Ambiguity Resolution

// Base2::greet(); --> This can also be done


}
};

int main()
{
Derived obj;

obj.greet();

return 0;
}

NOTE : When there are methods with same name and signature in the base
class and derived class in the case of single inheritance, then there also occurs
an ambiguity. But in such cases the ambiguity is resolved automatically,
wherein the method written in the derived class is executed when called rather
than executing the method inherited from the base class.

Virtual Base Class in C++

Virtual Base Class is required in the case of Hybrid Inheritance. If a


member(variable or method) of the base class is inherited by two or more
derived classes then each of the derived classes will have a copy of the
member. Now if a class inherits those derived classes then a problem occurs
while inheriting that specific member because each derived class has a copy of
the same member which is to be derived further in a single class. Now the
problem arises that from which class that particular member will be inherited.

Virtual Base Class solves the problem. We can make those derived classes as
virtual base classes. So whenever those derived classes are inherited further by
a class then only a single copy of that member will be allowed to be inherited,
thus eradicating the problem.
Syntax of Virtual Base Class :

Class Derived : virtual public Base

Class Body….

};

E.g.
#include <iostream>
using namespace std;

class Student
{
protected:
int rollno;

public:
void SetRoll(int roll)
{
rollno = roll;
}

void Display()
{
cout << "\nRoll Number : " << rollno << endl;
}
};

class Test : virtual public Student


{
protected:
int Maths, Science, Language;

public:
void SetTestMarks(int m, int s, int l)
{
Maths = m;
Science = s;
Language = l;
}

void ShowTestMarks()
{
cout << "\nMarks in Maths : " << Maths << endl
<< "Marks in Science : " << Science << endl
<< "Marks in Language : " << Language << endl;
}
};

class Sports : virtual public Student


{
protected:
int medical, athletics, game;

public:
void SetSportsMarks(int m, int a, int g)
{
medical = m;
athletics = a;
game = g;
}

void ShowSportsMarks()
{
cout << "\nMarks in Medical : " << medical << endl
<< "Marks in Athletics : " << athletics << endl
<< "Marks in Game : " << game << endl;
}
};

class Result : public Test, public Sports


{
protected:
float testpercent, sportspercent, totalpercent;

public:
void CalculateResult()
{
testpercent = (Maths + Science + Language) / 3;
sportspercent = (medical + athletics + game) / 3;
totalpercent = (testpercent + sportspercent) / 2;
}

void ShowResult()
{
cout << "\nTest Percentage : " << testpercent << "%" << endl
<< "Sports Percentage : " << sportspercent << "%" << endl
<< "Total Percentage : " << totalpercent << "%" << endl;

if (totalpercent >= 35)


cout << "\nResult : Pass" << endl;
else
cout << "\nResult : Fail" << endl;
}
};

int main()
{
Result obj;
int roll;
int tmarks[3];
int smarks[3];

cout << "\nEnter the Roll Number of Student : ";


cin >> roll;

cout << "\nEnter the Marks in Maths : ";


cin >> tmarks[0];
cout << "\nEnter the Marks in Science : ";
cin >> tmarks[1];
cout << "\nEnter the Marks in Language : ";
cin >> tmarks[2];

cout << "\nEnter the Marks in Medical Test : ";


cin >> smarks[0];
cout << "\nEnter the Marks in Athletics : ";
cin >> smarks[1];
cout << "\nEnter the Marks in Game : ";
cin >> smarks[2];

obj.SetRoll(roll);
obj.SetTestMarks(tmarks[0], tmarks[1], tmarks[2]);
obj.SetSportsMarks(smarks[0], smarks[1], smarks[2]);
obj.CalculateResult();

obj.Display();
obj.ShowTestMarks();
obj.ShowSportsMarks();
obj.ShowResult();

return 0;
}

Constructors in Derived Class in C++

We can use constructors in derived classes in C++. If base class constructor


does not have any arguments, there is no need of any constructor in derived
class. But if there are one or more arguments in the base class constructor,
derived class need to pass arguments to the base class constructor. If both
base and derived classes have constructors, base class constructor is executed
first.

In Multiple inheritance, base classes are constructed in the order in which they
appear in the class declaration. In Multilevel inheritance, the constructors are
executed in the order of inheritance.

The constructors for virtual base classes are invoked before an non virtual base
class. If there are multiple virtual base classes, they are invoked in the order
declared. Any non-virtual base class are then constructed before the derived
class constructor is executed.

We can assign values directly to all the variables in case of multilevel


inheritance or multiple inheritance by using the constructors of the base
classes with the constructor of the derived classes. Syntax for the same is given
below :

Syntax : Base1 has variable ‘x’, Base2 has ‘y’ and Derived has ‘z’.

Derived-Constructor(arg1, arg2, arg3) : Base1(arg1), Base2(arg2) {

y = arg3;

The Above Syntax works same as the following code :

Derived-Constructor (arg1, arg2, arg3) {

Base1(arg1);

Base2(arg2);

y = arg3;

E.g.
#include <iostream>
using namespace std;
/*
Case 1:
class B: public A{
//Order of Execution of Constructors --> First A() then B();
}

Case 2:
class C: public A, public B{
//Order of Execution of Constructors --> First A(), then B() and
then C();
}

Case 3:
class A: public B, virtual public C{
//Order of Execution of Constructors --> First C(), then B() and
then A();
}
*/

class Base1
{
int data1;

public:
Base1(int i)
{
data1 = i;
cout << "\nBase1 class constructor called!" << endl;
}
void printdata1()
{
cout << "\nThe value of data1 is : " << data1 << endl;
}
};

class Base2
{
int data2;

public:
Base2(int i)
{
data2 = i;
cout << "\nBase2 class constructor called!" << endl;
}
void printdata2()
{
cout << "\nThe value of data2 is : " << data2 << endl;
}
};

class Derived : public Base2, public Base1


{
int derived1, derived2;

public:
Derived(int a, int b, int c, int d) : Base1(a), Base2(b)
{
derived1 = c;
derived2 = d;
cout << "\nDerived Class constructor called!" << endl;
}

void printdata()
{
cout << "\nThe value of derived1 = " << derived1 << " derived2 = " <<
derived2 << endl;
}
};

int main()
{
Derived obj(10, 20, 30, 40);

obj.printdata1();
obj.printdata2();
obj.printdata();
return 0;
}

Initialization List in Constructors in C++

Syntax for Initialization List in Constructor:

Constructor (argument list) : initialization-section

Assignment + Other Code; //Body of Constructor

}
Initialization Section is used to initialize the variables in the class. We write the
variables as a function and then pass the argument with which it is to be
initialized.

E.g.

class Test

int var1, var2;

public:

Test ( int i, int j ) : var1(i), var2(var1*(i+j))

cout<<”\nInside Constructor!”<<endl;

};

NOTE : Initialization of variables should be done in order of their declaration.


The variable declared first will be initialized first. In above case var1 in declared
first so it should be initialized first to avoid certain problems.

Dynamic Memory Allocation and De-allocation using Pointers in C++

Pointers stores the address of the variables. We can use the “new” and
“delete” keyword in respect to the pointers for the purpose of dynamic
memory allocation.

The “new” keyword is used to allocate memory dynamically for the values of
different datatypes. It is similar to “malloc” and “calloc” in C language.

Syntax:

datatype *p = new datatype( value ); //For Single Value;

datatype *p = new datatype[ no. of elements ]; //For Array;


The “delete” keyword is used to free up the dynamically allocated memory for
any pointer. It is similar to the “free” keyword in the C language.

Syntax:

delete pointer_name; //For Single Value;

delete[] pointer_name; //For Array;

E.g.
#include <iostream>
using namespace std;

int main()
{
int *var1 = new int(25);
float *var2 = new float();
string *var3 = new string();

cout << "\nVar1 = " << *var1 << endl


<< "Var2 = " << *var2 << endl
<< "Var3 = " << *var3 << endl;

*var2 = 85.52;
*var3 = "Pointer";

cout << "\nVar1 = " << *var1 << endl


<< "Var2 = " << *var2 << endl
<< "Var3 = " << *var3 << endl;

delete var1, var2, var3;

cout << "\nVar1 = " << *var1 << endl


<< "Var2 = " << *var2 << endl
<< "Var3 = " << *var3 << endl;

int *arr = new int[3];


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

cout << "\nElements in the array are : " << endl;


for (int i = 0; i < 3; i++)
{
cout << "\n"
<< *arr;
arr += 1; }
delete[] arr;

cout << "\n\nElements in the array are : " << endl;


for (int i = 0; i < 3; i++)
{
cout << "\n"
<< *arr;
arr += 1;
}
return 0;
}

Pointers to Objects and Arrow Operator in C++

The pointer can also be assigned to the objects of the classes. We can use the
variables and methods in the classes by dereferencing the pointer
( (*ptr).method() ). Using the “new” operator we can create the objects
dynamically at the run time and using the “delete” operator we can free the
memory of the object or destroy the object.

Syntax : To dynamically create a object.

Class_name *ptr = new Constructor(arg1, arg2,… argn);

We dereference the pointer using the Dereference operator (*). Another way
of dereferencing the pointer is using the Arrow operator (->). The Arrow
operator allows us to dereference the pointer and use the variables and
methods inside the object.

Syntax :

ptr->method();

ptr->variable;

The above does the same thing as follows :

(*ptr).method();

(*ptr).variable;
E.g.
#include <iostream>
using namespace std;

class Complex
{
int real, imaginary;

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

void display()
{
cout << "\nReal Part is : " << real << endl;
cout << "Imaginary Part is : " << imaginary << "i" << endl;
}
};

int main()
{
Complex obj(10, 20);
Complex *ptr = &obj;
(*ptr).display();

Complex *p = new Complex(20, 10);


p->display();
return 0;
}

Array of Objects in C++

We can create the array of objects in case multiple objects are needed of a
particular class. We can create the array of objects without pointer (at compile
time) or with pointer (at run time). However, while creating the array of object
the only thing is that the respective class should only have a simple
constructor, and no parameterized constructor. You can create methods for
taking parameters instead of creating a parameterized constructor. Therefore,
array of objects can be created of only those classes which has only simple
constructors and no parameterized constructors.

E.g.
#include <iostream>
using namespace std;

class Test
{
int a, b;

public:
void setData(int x, int y)
{
a = x;
b = y;
}

void printData()
{
cout << "\nValues are : " << a << " " << b << endl;
}
};

int main()
{
Test obj[3]; // Array of objects at compile time.

obj[0].setData(10, 20);
obj[0].printData();

obj[1].setData(20, 20);
obj[1].printData();

obj[2].setData(30, 20);
obj[2].printData();

Test *ptr = new Test[3]; //Array of objects at run time.

ptr->setData(20, 10);
ptr->printData();

ptr += 1;
ptr->setData(20, 20);
ptr->printData();

ptr += 1;
ptr->setData(20, 30);
ptr->printData();
return 0;
}

This pointer in C++

“This” is a keyword which is a pointer which points to the object of the class. It
has two use cases:

1. It can be used to denote the member variables of the class while


initialization and can also denote the member functions.

Syntax:

returntype method( datatype var ) {

this->var = var;

2. It can be used to returns object itself if required.

Syntax:

Classname & method( arg1, arg2, … argn ) {

Body….

return *this;

E.g.
#include <iostream>
using namespace std;

class Test
{
int data;

public:
Test &setData(int data)
{
this->data = data;
return *this;
}

void showData()
{
cout << "\nThe data value is : " << data << endl;
}
};

int main()
{
Test obj;

obj.setData(204042).showData(); // setData() returns the object and so we


can call showData();
return 0;
}

Polymorphism in C++

Polymorphism is made up from two words -> Poly (Many) & Morphs (Forms).

Polymorphism means “many forms” of one thing/entity.

Polymorphism is of two types :

1) Static / Compile Time:

The polymorphism that takes place at compile time. It is called as early or


static binding.

There are two types under Compile Time Polymorphism:

 Function Overloading = Functions with same name but different


signatures (returntype and parameter list).

 Operator Overloading = Operators that performs desired operations on


the objects.
2) Dynamic / Run Time:

The polymorphism that takes place at run time. It is called as dynamic binding
or late binding. There are two types under it.

 Virtual Function = Covered in the next topics.

 Function Overriding = Overriding occurs in the case of functions with the


same name and signature (return type & parameter) in both, derived
and the base class. When the object calls for that function, the function
in the derived class is executed. It is called as Function Overriding.

Base Class Pointers to Derived Classes in C++

A pointer of the Base class can be assigned to the object of the derived class.
Therefore the Base Class pointer can point towards the object of the derived
class. This is called as late binding. The derived class has inherited the Base
class with some visibility mode, and so it contains several methods and
variables of the base class in it. Therefore being the base class pointer, it can
only access the inherited members of the base class in the derived class.
E.g.
#include <iostream>
using namespace std;

class Base
{
public:
int base_var;

void display()
{
cout << "\nThe Value of Base Variable = " << base_var << endl;
}
};

class Derived : public Base


{
public:
int derived_var;

void display()
{
cout << "\nThe Value of Derived Variable = " << derived_var << endl;
}
};

int main()
{
Base *base_pointer = new Derived;
Derived *derived_pointer = new Derived;

cout << "\nEnter the value of Base Variable : ";


cin >> base_pointer->base_var;
cout << "\nEnter the value of Derived Variable : ";
cin >> derived_pointer->derived_var;

base_pointer->display();
derived_pointer->display(); //Function Overriding;

return 0;
}
Virtual Functions in C++

We know that, if we create a Base class pointer and assign it to the object of
the derived class then the pointer can only access the members of the base
class which are inherited in the derived class. But it is opposite in the case of
Virtual Function. We can make any function “virtual” in the base class. Now the
base class pointer assigned to the object of the derived class cannot access the
virtual function of the base class inherited in the derived class and it instead
runs/executes the function with the same name of the derived class. It is a
type of run time polymorphism.

Rules for Virtual Function :

1) They are accessed by object pointers.


2) Virtual Function can be a friend of another class.
3) A virtual function in base class might not be used.
4) If a virtual function is defined in a base class, there is no necessity of
redefining it in the derived class.

E.g.
#include <iostream>
using namespace std;

class Base
{
public:
int base_var = 90;

virtual void display()


{
cout << "\nThe Value of Base Variable = " << base_var << endl;
}
};

class Derived : public Base


{
public:
int derived_var = 78;

void display()
{
cout << "\nThe Value of Derived Variable = " << derived_var << endl;
}
};

int main()
{
Base *base_pointer = new Derived;
Base *new_base_pointer = new Base;
Derived *derived_pointer = new Derived;

new_base_pointer->display();
base_pointer->display();
derived_pointer->display(); // Function Overriding;

return 0;
}

Abstract Base Class & Pure Virtual Functions in C++

The base class which is created for the purpose of inheritance ( to add up to its
variables and functions in the derived class ) is called as the Abstract base class.
The abstract base class contains at least one pure virtual function in it. The
pure virtual function is a virtual function which is declared in the base class and
it is initialized to zero (Do Nothing Function). Now it becomes
mandatory/compulsory to overwrite this function in the derived class and give
its implementation so that when called it can be executed. This mechanism of
abstracting/hiding the function of the base class and then re-declaring it in the
derived class is called as Abstraction.

E.g.
#include <iostream>
using namespace std;

class Actor // This is the abstract class


{
protected:
int Films, Awards;
float Networth;
bool Married;

public:
Actor(int films, int awards, float networth, bool married)
{
Films = films;
Awards = awards;
Networth = networth;
Married = married;
}

virtual void display() = 0; // Pure Virtual Function;


};

class SRK : public Actor


{
protected:
string Name = "Shahrukh khan", Tag = "King Khan";
int age;

public:
SRK(int age, int films, int awards, float networth, bool married) :
Actor(films, awards, networth, married)
{
this->age = age;
}

void display()
{
cout << "\n"
<< Name << " is a " << age << " years old Actor and he had done
over " << Films << " films and won " << Awards << " awards. He is known as \""
<< Tag << "\" and his networth is around $" << Networth << " million.";

if (Married)
cout << " He is a married person." << endl;
else
cout << " He is not married and he's happy." << endl;
}
};

class SLK : public Actor


{
protected:
string Name = "Salman khan", Tag = "Bhai";
int age;

public:
SLK(int age, int films, int awards, float networth, bool married) :
Actor(films, awards, networth, married)
{
this->age = age;
}
void display()
{
cout << "\n"
<< Name << " is a " << age << " years old Actor and he had done
over " << Films << " films and won " << Awards << " awards. He is known as \""
<< Tag << "\" and his networth is around $" << Networth << " million.";

if (Married)
cout << " He is a married person." << endl;
else
cout << " He is not married and he's happy." << endl;
}
};

int main()
{
SRK srk(52, 125, 75, 655.75, true);
SLK slk(54, 115, 65, 545.35, false);

Actor *ptr[2];

ptr[0] = &srk;
ptr[1] = &slk;

ptr[0]->display();
ptr[1]->display();

return 0;
}

File I/O in C++

Files are the storage area for the data of various kinds. The files can be of
different types like text files, image files, audio files etc. In the file each
character or block is equivalent to some ASCII value or UNICODE value which is
then converted to the binary and therefore the file is stored on to the disk in
the format of binary.

FILE DATA ASCII / UNICODE BINARY


A stream is a flow of data in either way. There are two types of streams; Input
stream and Output Stream. The stream from which the input is provided from
the file or input devices to the program is called as the input stream and the
stream from which the output is provided from the program to the file or
output devices is called as the output stream.

Reading and Writing in Files in C++

To read and write into the files we need to include the header file “fstream”
i.e. file stream. The useful classes for working with files in cpp are:

1) fstreambase( File Stream Base Class )


2) ifstream (Input File Stream  Derived from fstreambase)
3) ofstream (Output File Stream  Derived from fstreambase)

In order to work with files we need to open the file. Primarily there are two
ways to open the file:

1)Using the Constructor of class “ofstream” or “ifstream”.

2)Using the member function open() of the class “ofstream” or “ifstream”.


Reading content from the File -

Syntax:

Ifstream_obj>>string_variable;  Doesn’t read special characters and spaces.

getline(ifstream_object, string variable);  Reads the complete line.

Writing content to the File -

Syntax:

Ofstream_object << string_variable;

Ofstream_object<<”Text to insert in the file”;

After performing the desired operations on the opened file, the file must be
closed in order to release or free up its all the resources. We use the close
method to close the opened file.

Syntax:

File_Object.close();

End of File -

The “eof()” defines the end of file. It can used with the while loop to read all
the content of the file.

NOTE: For the purpose of reading a complete line from the file we use the
getline() function. This function is present in the “string” header file and so we
need to include “string” for using the function.

E.g. 1. Writing and Reading from file using constructor of class.


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

//fstream --> fstreambase --> ifstream & ofstream;

int main()
{
ofstream fout("FileProgram.txt"); //fout is now an output file stream
just similar to cout.

string str;
cout<<"\nEnter Your Name : ";
cin>>str;

fout<<str<<" is my name!";
fout.close();

ifstream fin("FileProgram.txt"); //fin is now an input file stream just


similar to cin.

cout<<"\nContent of the file : "<<str;


fin.close();

return 0;
}

E.g. 2. Writing and Reading from file using open function.


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ofstream fout;
fout.open("FileProgram.txt");

string str;
cout << "\nEnter Your Name : ";
cin >> str;

fout << "This is " << str << " and this is my second file program";

fout.close();

ifstream fin;
fin.open("FileProgram.txt");
while (fin.eof() == 0)
{
getline(fin, str);
cout << "\nThe Content of File is : " << str;
}

fin.close();

return 0;
}

Templates in C++

Class is a blue-print or a structure for the objects. Similarly we can say that
templates are the blue-print or structure for the classes. We can create a
template and then use it for different datatypes as required. Templates are
also called as the parameterized classes. We provide datatype as a parameter
to the template.

We prefer the use of template to follow the “DRY” principle i.e. “Don’t Repeat
Yourself” principle. Templates allows us to do Generic Programing (Generic 
Templates can be used for various datatypes ).

Syntax for creating Template : ‘T’ is the Datatype that we pass as parameter.

template < class T >

class class_name {

T variable; //One of many variables of the class.

T *pointer; //One of many pointers of the class.

};

int main() {

class_name < datatype > object_name;

}
E.g. Dot Product of Vectors
#include <iostream>
using namespace std;

template <class T>


class Vector
{
public:
T *arr = new T[3];

T dotProduct(Vector &v)
{
T sum = 0;

for (int i = 0; i < 3; i++)


{
sum += this->arr[i] * v.arr[i];
}

return sum;
}
};

int main()
{
Vector<float> v1;
v1.arr[0] = 4.2;
v1.arr[1] = 2.9;
v1.arr[2] = 3.7;

Vector<float> v2;
v2.arr[0] = 1.0;
v2.arr[1] = 2.54;
v2.arr[2] = 3.213;

cout << "\nSum of Vectors is : " << v1.dotProduct(v2) << endl;

return 0;
}

Templates with Multiple Parameters in C++

We can create templates with multiple parameters to specify multiple


datatypes in the class. Syntax for the same is given below:
template < class T1, classT2,… class TN >

class class_name {

T1 variable; //One of many variables of the class.

T2 *pointer; //One of many pointers of the class.

};

int main() {

class_name < datatype1, datatype2,..datatypeN > object_name;

E.g.
#include <iostream>
using namespace std;

template <class T1, class T2>


class addition
{
T1 data1;
T2 data2;

public:
addition(T1 data1, T2 data2)
{
this->data1 = data1;
this->data2 = data2;
}

void result()
{
cout << "\nResult = " << data1 + data2;
}
};

int main()
{
addition<int, float> obj(45, 457.56);

obj.result();
return 0;
}
Templates with Default Parameters in C++

We can write templates with default parameters, i.e. we can provide the
default datatypes to the template parameter. If no datatypes are specified at
the time of creating the object of the class then those default parameter
datatypes are been used.

Syntax:

template < class T1 = int, classT2 = float >

class class_name {

T1 variable; //One of many variables of the class.

T2 *pointer; //One of many pointers of the class.

};

int main() {

class_name < datatype1, datatype2 > object_name;

E.g.
#include <iostream>
using namespace std;

template <class T1 = float, class T2 = float>


class addition
{
public:
addition(T1 data1, T2 data2)
{
cout << "\nResult = " << data1 + data2;
}
};

int main()
{
addition obj1(45.98, 78.24);
addition<int, float> obj2(85, 54.45);
addition<int, int> obj3(95, 108);
return 0; }
Function Template and Function Template with Parameters in C++

Function Template is similar to the template of the class. We create function


template for using the same function for various datatypes as per our
convenience and need.

Syntax:

template <class T1, class T2>

datatype function_name (T1 a, T2 b, ….TN n)

Body of Function…;

E.g.
#include <iostream>

using namespace std;

template <class T1, class T2>

float avg(T1 a, T2 b)
{
float result = (a + b) / 2.0;

return result;
}

int main()
{
int a = 19, b = 24;

float result1, result2;

result1 = avg(a, b);


result2 = avg(54.87, 98.15);

printf("\nThe First Result is = %.3f", result1);


printf("\nThe Second Result is = %.3f", result2);

return 0;
}
Member Function Templates & Overloading Template Functions in C++

Member function templates are useful when we write the member function of
the class outside the class. We need to write the template for the function and
declare it outside the class and then write its implementation.

E.g.
#include <iostream>

using namespace std;

template <class T>

class Test
{
T data;

public:

Test(T value)
{
data = value;
}

void display();
};

template <class T>

void Test<T>::display()
{
cout << "\nThe Data value is = " << data;
}

int main()
{
Test<int> o1(42);
Test<char> o2('S');
Test<float> o3(93.65);

o1.display();
o2.display();
o3.display();

return 0;
}
We can also overload the template functions. The function with exact match of
the datatype when called has the first preference.

E.g.
#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "\nThe result of Integer Addition is = " << (a + b);
}

template <class T>


void add(T a, T b)
{
cout << "\nThe result of Addition is = " << (a + b);
}

int main()
{
add(45, 85); //Exact match so the first function is called.
add(78.5, 95.25);
return 0;
}

Standard Template Library (STL) in C++

Standard Template Library is a library or collection of generic classes and


functions. We can reuse these classes and functions which are well tested to
perform various operations and tasks. Using STL saves a lot of time and effort
to write codes for different operations.

There are 3 components of STL  Containers, Algorithms and Iterators.

Containers are objects that stores data & uses template classes (e.g. Vector )

Algorithms are procedures that processes data & it uses template functions
(e.g. Sorting, Searching, Merging etc. )

Iterators are objects which points to an element in a container. It is handled


just like pointers. It connects algorithms with containers.
Containers in STL in C++

Containers in STL are divided into three categories:

1) Sequence Containers = Stores Data in Linear Fashion ( Vector, List,


Deque ).

2) Associative Containers = Elements are associated with each other to


provide faster/direct access to them. ( Tree, Set, Multi-Set, Map, Multi-
Map )

3) Derived Containers = These containers can be derived from sequence


containers and associative containers. It provides Real World Modeling
facilities. ( Stack, Queue, Priority Queue, Circular Queue )

Sequence Containers :

1) Vector = Random access is fast as compared to array and insertion &


deletion in middle is relatively slow. However, insertion and deletion at
the end is fast.
2) List = Random access is slow as compared to array. Insertion and
deletion in middle & end is faster as compared to array.

Associative Containers : All operations are fast except random access.

Derived Containers : The speed of the operations depends on the used data
structure as per our requirement.

Vector in STL in C++

Vector is similar to array. Size of the vector can be dynamically changed as per
required but it is not possible in the case of array. There are several methods
and variables with respect to the vector. Refer the “methods of vector”
document on “cplusplus.com” for such methods and variables.
Syntax:

vector <datatype> object_name;

OR

vector <datatype> object_name(vector_size);

OR

vector <datatype> object_name(vector_object);

OR

vector <datatype> object_name(size, value);

E.g.1.
#include <iostream>
#include <vector>

using namespace std;

void display(vector<int> &v)


{
cout << "\nValues in Vector are :\n"
<< endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
// cout<<v.at(i)<<endl; //Does the same thing as above line;
}
}

int main()
{
vector<int> vec1;
int value, size;

cout << "\nEnter the size of Vector : ";


cin >> size;

for (int i = 0; i < size; i++)


{
cout << "\nEnter value " << (i + 1) << " : ";
cin >> value;
vec1.push_back(value); // Push the value in the vector from back;
}

vec1.pop_back(); // Pop's the last value from the vector.


display(vec1);

vector<int>::iterator iter; // Creating Iterator pointer for iterating


vector;
iter = vec1.begin(); // Assigning iterator pointer to the first
position of the vector;
iter = iter + 1; // Iterator pointing to the second position;

vec1.insert(iter, 25);
display(vec1);

vec1.insert(iter + 1, 4, 30); // Inserting value 30 at 3rd position for 4


times;
display(vec1);

return 0;
}

E.g.2.
#include <iostream>
#include <vector>
using namespace std;

template <class T>


void display(vector<T> &v)
{
cout << "\n\nValues in the Vector are : \n"
<< endl;

for (int i = 0; i < v.size(); i++)


{
cout << v.at(i) << " ";
}
}

int main()
{
vector<char> vec1(4); // 4 Element Character Vector;
vector<char> vec2(vec1); // Vector vec2 has the size of vec1;
vector<int> vec3(6, 5); // Adds value 5 in the vector for 6 times.

vec1.push_back('S');
display(vec1);

vec2.push_back('P');
vec2.push_back('N');
vec2.push_back('H');
vec2.push_back('S');
display(vec2);

display(vec3);
return 0;
}

List in STL in C++

List is also a container and is used to store data in it. It is bidirectional linear list
which provides efficient insertion, deletion and many more operations. It is
different from an array. Array stores elements with contiguous memory
allocation whereas list is the STL implementation of “Linked List” data structure
where the elements are not stored in contiguous blocks of memory. In STL
there are several methods and variables which can be used in respect to List.
Refer “cppreference.com” for such methods and varaibles.

Syntax:

list <datatype> list_object;

OR

list <datatype> list_object(size_of_list);

E.g.
#include <iostream>
#include <list>

using namespace std;

void display(list<int> &l)


{
list<int>::iterator iter;
cout << "\n\nElements in the list are :\n\n";
for (iter = l.begin(); iter != l.end(); iter++)
{
cout << (*iter) << endl;
}
}

int main()
{
list<int> list1;
list<int> list2(2);

list1.push_back(42);
list1.push_back(20);
list1.push_front(25);
list1.push_back(43);
list1.push_front(95);

list<int>::iterator iter;
iter = list2.begin();
*iter = 40;
++iter;
*iter = 45;

display(list1);
display(list2);

list1.pop_back();
list1.remove(25);
list1.pop_front();

list1.sort();
list1.reverse();

list1.merge(list2);
display(list1);
return 0;
}

Map in STL in C++

Map is similar to dictionary datatype. Map stores data values which


corresponds to a key value. Therefore map stores data in the form of key
values pairs. We insert the data values of any datatype with a key attached
with it. The key-value pairs are stored in alphabetical order of keys.
Syntax:

map <string, datatype> object_name;

E.g.
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
map<string, int> marks;

marks["Suraj"] = 42;
marks["Piyush"] = 40;
marks["Tanmay"] = 53;
marks["Aditya"] = 24;

marks.insert({{"Sayali", 20}, {"Divya", 02}, {"Ketaki", 25}});

map<string, int>::iterator iter;

for (iter = marks.begin(); iter != marks.end(); iter++)


{
cout << "\n\n" << (*iter).first << " = " << (*iter).second;
//.first gives us the key and .second gives us the value;
}

return 0;
}

Function Objects (Functors) in C++

Function objects are functions wrapped in a class so that it is available like an


object. There are many function objects available in cpp which are present in
the “functional” header file. Several methods are available as algorithms for
various operations in the “algorithm” header file.
Syntax:

Function_name <datatype> ();

E.g.
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;

void display(int arr[])


{
cout << endl
<< endl;
for (int i = 0; i < 6; i++)
{
cout << arr[i] << " ";
}
}

int main()
{
int arr[] = {45, 98, 30, 14, 75, 21};

// sort method is present in "algorithm" header file.


sort(arr, arr + 5); // sorting only first 5 elements in the arr;
display(arr);

sort(arr, arr + 6, greater<int>()); // greater<int>() is a function object


to sort in reverse;
display(arr);

return 0;
}

You might also like