CPP Sunbeam Notes 2024
CPP Sunbeam Notes 2024
in
Explore More
Agenda
Language Fundamentals
Introduction to CPP
OOP Concepts
Hello World
Data types
Structure in C++
Inline Functions
Classfication of languages:
1. Machine level languages Binary language( 1, 0 )
2. Low level languages Assembly
3. High level languages C, C++, java
Chracteristics of Language
1. It has own syntax
2. It has its own rule(semantics)
3. It contain tokens:
1. Identifier
2. Keyword
3. Constant/literal
4. Operator
5. Seperator / punctuators
4. It contains built in features.
5. We use language to develop application( CUI, GUI, Library )
6. If we want to implement business logic then we should use language.
ANSI
Histroy of C++
Inventor of C++ is Bjarne Stroustrup.
C++ is derived from C and simula.
Its initial name was "C With Classes".
It was developed in "AT&T Bell Lab" in 1979.
It was developed on Unix Operating System.
Standardizing C++ is a job of ANSI.
In 1983 ANSI renamed "C With Classes" to C++.
C++ is objet orieted programming language.
In C++ we can develop code using Procedure as well as object orieneted fashion. Hence it is also called
Hybrid programming language.
C++ Standards
In 1985, the first edition of The C++ Programming Language was released.
In 1989, C++ 2.0 was released. New features in 2.0 included multiple inheritance, abstract classes, static
member functions, const member functions, and protected members.Later feature additions included
templates, exceptions, namespaces, new casts, and a Boolean type.
In 1998, C++98 was released, standardizing the language, and a minor update (C++03) was released in
2003.
After C++98, C++ evolved relatively slowly until, in 2011, the C++11 standard was released, adding
numerous new features,enlarging the standard library further, and providing more facilities to C++
programmers.
A minor C++14 update was released in December 2014.
A major revision where various new additions were introduced in C++17.
Year and version of cpp
1. 1998 : C++98
2. 2003 : C++03
3. 2011 : C++11
4. 2014 : C++14
5. 2017 : C++17
6. 2020 : C++20
The errors generated and hidden errors may reach an astonishing degree, this is not something that
can be solved in the programming stage.
Need to standardize the entire software development process and clarify the software
The tasks of each stage in the development process, while ensuring the correctness of the work of the
previous stage, proceed to the next stage work.
This is the problem that software engineering needs to study and solve.
Object-oriented software development and engineering include the following parts:
Object-oriented programming
OOPS is not a syntax. It is a process / programming methodology which is used to solve real world
problems.
It is invented by Dr. Alan Kay. He is inventor of Simula too.
Unified Modelling Language( UML ) is invented by Grady Booch. If we want to do OOA and OOD then
we can use UML.
According Grady Booch there are 4 main/major and 3 minor elements/parts/pillars of OOPS
1. Abstraction
2. Encapsulation
3. Modularity
4. Hierarchy
1. Typing
2. Concurrency
3. Persistence
Here, word major means, language without any one of the above feature will not be Object orieneted.
Here word minor means, above features are useful but not essential to classify language object
oriented.
Abstraction
Getting only essential things and hiding unnecessary details is called as abstraction.
Abstraction always describe outer behavior of object.
In console application when we give call to function in to the main function , it represents the
abstraction
Encapsulation
Binding of data and code together is called as encapsulation.
Implementation of abstraction is called encapsulation.
Encapsulation always describe inner behavior of object
Function call is abstraction
Function definition is encapsulation.
Modularity
Dividing programs into small modules for the purpose of simplicity is called modularity.
Hirerachy
Level / order / ranking of abstraction is called hireracy.
Its main purpose is to achive reusability.
Advantages of reusability:
Types of Hierarcy:
1. Has-a/Part-of Association/Containment
2. Is-a/Kind-of Inheritance/Generalization
3. Use-a Dependancy
4. Creates-a Instantiation
Typing/Polyorphism
polymorphism = poly(many) + morphism(forms)
An ability of object to take multiple forms is called polymorphism.
Main purpose of polymorphism is to reduce maintenance of system.
Types of polymoprhism:
Concurrency
In context of OS it is called multitasking
Process of executing multiple task simultaneously is called concurrency.
If we want to utilize hardware resources efficiently then we should use concurrency.
Using multithreading, we can achive concurrency.
Persistance
It is the process of maintaing state of object on secondry storage(HDD).
We can achive it using file handling and database programming.
Installation
To install the gcc/g++ compiler use the below link
https://sourceforge.net/projects/tdm-gcc/
https://code.visualstudio.com/download
Hello World
// header file
#include <iostream>
g++ demo01.cpp
a.exe
1. Preprocessor
This is the first stage of any C/C++ program execution process; in this stage Preprocessor
processes the program before compilation. Preprocessor include header files, expand the
Macros.
2. Compiler
This is the second stage of any C/C++ program execution process, in this stage generated
output file after preprocessing ( with source code) will be passed to the compiler for compilation.
Complier will compile the program, checks the errors and generates the object file (this object
file contains assembly code).
3. Linker
It will link the multiple files
4. Loader
It will load the executable for the execution
We can view the intermediate files like preprocesssed (.i),assembly (.asm) file for out .cpp using below
commands
we can view the .i and .asm files but we cannot view the object .o and executable .exe files
1. Array
2. Function
3. Pointer
4. Reference
5. Union
6. Structure
7. Class
Type Modifiers
C++ allows the char, int, and double data types to have modifiers preceding them.
A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of
various situations.
The data type modifiers are
1. short
2. long
3. signed
4. unsigned
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition,
signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example,
unsigned long int.
Prepared By : Rohan Paramane 7/8
Day01_Help.MD Sunbeam Infotech 2024-09-09
Type Qualifiers
The type qualifiers provide additional information about the variables they precede.
their are two qualifiers
1. const
2. volatile
Bool Datatype
it can take true or false value.
It takes one byte in memory.
by default the value is false
wchar_t Datatype
wchar_t stands for Wide Character.
This should be avoided because its size is implementation defined and not reliable.
It is similar to char data type, except that it take up twice the space and can take on much larger values.
As char can take 256 values which corresponds to entries in the ASCII table. On the other hand, wide
char can take on 65536 values which corresponds to UNICODE values which is a recent international
standard which allows for the encoding of characters for virtually all languages and commonly used
symbols.
The type for character constants is char, the type for wide character is wchar_t. This data type occupies
2 or 4 bytes depending on the compiler being used. Mostly the wchar_t datatype is used when
international languages like Japanese are used. This data type occupies 2 or 4 bytes depending on the
compiler being used. L is the prefix for wide character literals and wide-character string literals which
tells the compiler that that the char or string is of type wide-char.
Agenda
Structure in C++
Inline Functions
Class
Object
Console I/O
this pointer
Namespace
Menu Driven Code
Function Overloading
Default Argument Function
Types of Member Functions
Structure in CPP
In Cpp we can define the functions within the structure
to access the members of structure we have to create the variable of the structure and access the
members using .operator.
struct Time
{
int hrs;
int min;
void acceptTime()
{
printf("Enter hrs and mins - ");
scanf("%d%d", &hrs, &min);
}
void printTime()
{
printf("Time - %d : %d \n", hrs, min);
}
};
int main()
{
struct Time t1;
t1.acceptTime();
t1.printTime();
return 0;
}
By default all members in structure are accessible everywhere in the program by dot(.) or arrow( )
operators.
But such access can be restricted by applying access specifiers
private: Accessible only within the struct
public: Accessible within & outside struct
Inline Function
Managing function activation record is a job of compiler.
If we give call to the function then compiler need to create Stack Frame and push it into stack. Upon
returning control back to the calling function it needs to destroy stackframe from stack. In other words
giving call the function is overhead to the compiler.
If we want to reduce compilers overhead then we should use inline function.
C++ provides a keyword inline that makes the function as inline function.
If we declare function inline then compiler do not call function rather it replaces function call by
function body.
As Inline functions get replaced by compiler at its call statement. It ensures faster execution of function
just like macros.
Inline is request to the compiler.
In following cases, function is not considered as inline:
1. If we use loop( for/while) inside function
2. If we implement function using recursion
3. If we use jump statement inside function
In case of modular approach, we can use inline keyword in either declaration, definition or both places.
We can not declare main function static, constant, virtual or inline.
Advantage of inline functions over macros: inline functions are type-safe.
If we define member function inside class then function are by default considered as inline.
If we want to make member function inline whose definition is global then we must explicitly use inline
keyword.
We can not divide inline function code in multiple files.
Naming Convention
The naming convention used for software development are
In this case, except word, first Character of each word must be in upper case.
main()
parseInt()
showInputDialog
addNumberOfDays( int days )
Data member
Member function
Function Parameter
Local and global variable
In this case, including first word, first character of each word must be in upper case.
System
StringBuilder
NullPointerException
IndexOutOfBoundsException
Union Name
Structure Name
Class Name
Enum Name
#define NULL 0
#define EOF -1
#define SIZE 5
enum ShapeType
{
EXIT, LINE, RECT, OVAL
};
namespace collection
{
class Stack
{
};
}
Class
Prepared By : Rohan Paramane 3/8
Day02_Help.MD Sunbeam Infotech 2024-09-10
Object
It is physical entity.
Object is a variable/instance of a class.
An entity, which get space inside memory is called object.
With the help of instantiation we achive abstraction.
Example: Nokia 1100, MacBook Pro, Maruti 800
Characteristics of object
Object defines 3 things
1. State
2. Behavior
3. Identity
Value of any data member, which is used to identify object uniquly is called its identity.
If state of object is same the its address can be considered as its identity.
Object Size
If we create object of the class then only non static data members get space inside object.
Hence size of object is depends on size of all the non static data members declared inside class.
Member function do not get space inside object.
Data members get space once per object according to the order of data member declaration.
Member function do not get space per object rather it gets space on code segment and all the objects
of same class share single copy of it.
Object of an empty class is 1 byte.
Access Specifiers
If we want to control visibility of members of structure/class then we should use access specifier.
Access specifiers in C++
1. private( - )
In C++, structure members are by default considered as public and class members are by default
considered as private
Namespace
If we want to access value of global variable then we should use scope resolution operator( :: )
1. Variable
2. Function
3. Types[ structure/union/class]
4. Enum
5. Nested Namespace
Namespaces are used to organize code into logical groups and to prevent name collisions that can
occur especially when your code base includes multiple libraries.s
We can not instantiate namespace.
If we want to define namespace then we should use namespace keyword.
namespaces can only be defined in global or namespace scope. In other words, we can not define
namespace inside function/class.
If we want to access members of namespace then we should use namespace name and scope
resolution operator.
If name of the namespaces are diffrent then we can give same/diffrent name to the members of
namespace.
If name of the namespaces are same then name of members must be different.
We can define namespace inside another namespace. It is called nested namespace.
If we define member without namespace then it is considered as member of global namespace.
If we want to access members of namespace frequently then we should use using directive.
namespace na
{
int num1 = 10;
}
1. cout
2. cin
Function Overloading
Functions with same name and different signature are called as overloaded functions.
Return type is not considered for function overloading.
Function call is resolved according to types of arguments passed.
Function overloading is possible due to name mangling done by the C++ compiler (Name mangling
process , mangled name)
Differ in number of input arguments
Differ in data type of input arguments
Prepared By : Rohan Paramane 6/8
Day02_Help.MD Sunbeam Infotech 2024-09-10
this pointer
If we call member function on object then compiler implicitly pass address of that object as a argument
to the function implicitly.
To store address of object compiler implitly declare one pointer as a parameter inside member function.
Such parameter is called this pointer.
this is a keyword. "this" pointer is a constant pointer.
General type of this pointer is:
Classname * const this;
Member Functions
The functions declared inside the class are called as Member Functions.
The member functions according to their behaviour are classified into following types
1. constructor
2. destructor
3. Mutator
4. Inspector
5. Facilitator
Mutator
A member function of a class, which is used to modify state of the object is called mutator function.
It is also called as modifier function or setter function
e.g setHrs() and setMins()
Inspector
A member function of class, which is used to read state of the object is called inspector function.
It is also called selector function of getter function.
e.g getHrs() and getMins()
Facilitator
Agenda
Types of Member Functions
constructor and their types
Constant
Dynamic Memory Allocation
Reference
Constructor
It is a member function of a class which is used to initialize object.
Due to following reasons, constructor is considered as special function of the class:
1. Its name is same as class name
2. It doesn't have any return type.
3. It is designed to call implicitly.
4. In the life time of the object is gets called only once.
We can not call constructor on object, pointer or reference explicitly. It is designed to call implicitly.
constructor does not get called if we create pointer or reference.
We can use any access specifier on constructor.
If ctor is public then we can create object of the class inside member function as well as non member
function but if constructor is private then we can create object of the class inside member function only.
We can not declare constructor static, constant, volatile or virtual. We can declare constructor only
inline.
constructor can contain return statement,it cannot return any value from constructor as return
statement is used only to return controll to the calling function.
Types of Constructor
1. Parameterless Constructor
class Point
{
int x;
int y;
public:
Point()
{
x = 1;
y = 1;
}
}
int main(){
Point pt1;
Point pt2;
//Point::Point( )
//Point::Point( )
}
2. Parameterized Constructor
Point pt1(10,20);
//Point::Point(int,int)
Point pt2; //Point::Point( )
3. Default constructor
If we do not define constructor inside class then compiler generates default constructor for the
class.
Compiler do not provide default parameterized constructor. Compiler generated default
constructor is parameterless.
If we want to create object by passing argument then its programmers responsibility to write
parameterized constructor inside class.
Default constructor do not initialize data members declared by programmer. It is used to
initialize data members declared by compiler(e.g v-ptr).
If compiler do not declare any data member implicitly then it doesnt generate default
constructor.
We can write multiple constructor's inside class. It is called constructor overloading.
Point()
{
cout << "Inside Parameterless Ctor" << endl;
x = 1;
y = 1;
}
// constructor overloading
Point(int value)
{
x = value;
y = value;
Prepared By : Rohan Paramane 2/7
Day03_Help.MD Sunbeam Infotech 2024-09-11
}
// constructor overloading
Point(int x, int y)
{
cout << "Inside Parameterized Ctor" << endl;
this->x = x;
this->y = y;
}
Point() : Point(1, 1)
{
cout << "Inside Parameterless Ctor" << endl;
}
Point(int x, int y)
{
cout << "Inside Parameterized Ctor" << endl;
this->x = x;
this->y = y;
}
class Point
{
int x;
int y;
const int num;
public:
// ctor members initializer list initialize data member according to order of
data member declaration in class
// here x will get initialized first then y and then num
Point(int value) : y(value), x(++value), num(value) // x= 3, y = 3, num = 3
{
}
// Point(int value)
// {
// this->y = value; // y = 2
// this->x = ++value; // x = 3
// this->num = value; // NOT OK
// }
}
Destructor
It is a member function of a class which is used to release the resources.
Due to following reasons, it is considered as special function of the class
1. Its name is same as class name and always preceds with tild operator( ~ )
2. It doesnt have return type or doesn't take parameter.
3. It is designed to call implicitly.
We can declare destructor as a inline and virtual only.
Destructor calling sequence is exactly opposite of constructor calling sequence.
We can not call constructor on object, pointer or reference explicitly. It is designed to call implicitly.
Destructor is designed to call implicitly but we can call it explicitly.
If we do not define destructor inside class then compiler generates default destructor for the class.
Default destructor do not deallocate resources allocated by the programmer. If we want to deallocate it
then we should define destructor inside class.
Constant
const is type qualifier.
If we dont want modify value of the variable then we should use const keyword.
constant variable is also called as read only variable.
In C++, Initializing constant variable is mandatory.
- Once initialized, if we dont want to modify state of the data member inside any
member function of the class including constructor body then we should declare
data member constant.
- If we declare data member constant then it is mandatory to initialize it using
constructors member initializer list.
```CPP
class Test
{
private:
const int num1;
public:
Test( void ) : num1( 10 ) //OK
{
//this->num1 = 10; //Not OK
}
};
```
- We can not declare global function constant but we can declare member function
constant.
- If we dont want to modify state of current object inside member function then we
should declare member function constant.
- Non constant member function get this pointer like: `ClassName *const this`
- Constant member function get this pointer like: `const ClassName *const this;`
- We can not delclare following function constant:
1. Global Function
2. Static Member Function
3. Constructor
4. Destructor
3. Object as Constant
- If we dont want to modify state of the object then instead of declaring data
member constant, we should declare object constant.
- On non constant object, we can call constant as well as non constant member
function.
- On Constant object, we can call only constant member function of the class.
int main()
{
int *ptr = new int;
*ptr = 20;
cout << "Address of dynamic Memory - " << ptr << endl;
cout << "Value on dynamic memory - " << *ptr << endl;
delete ptr;
ptr = NULL;
return 0;
}
Type:
malloc(): malloc() is a function. Declared in <stdlib.h>.
new: new is an operator. No separate header file needed.
Initialization:
malloc(): Memory allocation only. Doesn't call constructors for objects.
new: Memory allocation and initialization. Calls constructors for objects.
Usage with Arrays:
malloc(): No special handling for arrays.
new: Supports array allocation. new[] is used for arrays, which can later be deallocated with
delete[].
Return Type:
Type:
free(): free() is a function. Declared in <stdlib.h>.
delete: delete is an operator. No separate header file needed.
Type of Memory:
free(): Used to deallocate memory allocated with malloc() or calloc().
delete: Used to deallocate memory allocated with new.
De-Initialization:
free(): Only deallocates memory. Doesn't call destructors for objects.
delete: Deallocates memory and calls destructors for objects.
Usage with Arrays:
free(): No special handling for arrays.
delete: Used with delete[] to deallocate memory allocated for arrays.
Overloading:
delete: Supports overloading to customize memory deallocation behavior.
free(): free() is not meant to be overloaded.
Usage in C++:
free(): Not used in C++. Deallocating memory allocated with malloc() or calloc() using free() in
C++ can lead to undefined behavior if
the object has non-trivial constructors or destructors.
delete: Preferred in C++ for deallocating memory allocated with new because it properly calls
destructors for objects.
https://drmemory.org/page_download.html
Agenda
Reference
Static (Data Member & Member Functions),
simple and dynamic Array(1D)
simple and dynamic Array(2D)
enum
multiple files
typedef
It is C language feature which is used to create alias for exsiting data type.
Using typedef, we can not define new data type rather we can give short name / meaningful name to
the exisiting data type.
e.g
1. typedef unsigned short wchar_t;
2. typdef unsgined int size_t;
3. typedef basic_istream istream;
4. typedef basic_ostream ostream;
5. typedef basic_string string;
Reference
Reference is derived data type.
It alias or another name given to the exisiting memory location / object.
Static
All the static and global variables get space only once during program loading
Static variable is also called as shared variable.
If we declare function static then local variables are not considered as static.
If we dont want to access any global function inside different file then we should declare global
function static.
In C/C++, we can not declare main function static.
In C++ we can declare
1. Data member as static
2. Member function as static
If we want to declare data member static then we must provide global definition for it otherwise linker
generates error.
Instance variable get space inside instance hence we should initialize it using constructor.
Class level variable do not get space inside instance hence we should not initialize it inside constructor.
We must initialize it in global definition.
We can declare constant data member static.
Array
Array is a data structure that is used to store the elements of same type in contagious memory
locations.
the elements stored in the array can be accessed using their index number;
Types of array
1. Single Dimension Array
2. Multi Dimension Array
we can create array for fundamental data types as well as derived data types
// ...
Agenda
2D Array
enum
multiple files
Hierarchy and its type.
Association
Inheritance
Type of Inheritance
Diamond problem
Virtual base class
Mode of Inheritance
enum
Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values.
These values are defined by the programmer at the time of declaring the enumerated type.
Enums provide a way to define symbolic names for sets of integers, making the code more readable
and maintainable.
#include <iostream>
int main() {
// Declare a variable of type Color
Color myColor = GREEN;
If we include header file in angular bracket (e.g #include<filename.h>) then preprocessor try to locate
and load header file from standard directory only(/usr/include).
If we include header file in double quotes (e.g #include“filename.h") then preprocessor try to locateand
load header file first from current project directory if not found then it try to locate and load from
standard directory.
// Header Guard
#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
//TODO : Type declaration here
#endif
Hierarchy
It is a major pillar of oops.
Level / order / ranking of abstraction is called hierarcy.
Its main purpose is to achive reusability.
Advantages of reusability:
1. To reduce develoers efforts.
2. To reduce development time and development cost.
Types of Hierarcy:
1. Has-a/Part-of Association/Containment
2. Is-a/Kind-of Inheritance/Generalization
3. Use-a Dependancy
This hierarchy represents how classes depend on each other.
Dependencies occur when one class relies on another class but does not own or control its
lifetime.
For example, if Class A uses Class B as a method parameter or local variable, there's a
dependency between A and B.
4. Creates-a Instantiation
This can often be seen in factory design patterns or in scenarios where one class encapsulates
the creation logic of another class.
Association
If has-a relationship exist between two types then we should use association.
Example:
1. Room has-a wall
2. Room has-a chair
3. Car has-a engine
4. Car has-a music player
5. Department has-a faculty
6. Human has-a heart
If object is part-of / component of another object then it is called association.
class Engine{
};
class Car{
private:
Engine e; //Association
};
int main( void ){
Car car;
return 0;
}
1. Composition
If dependancy object do not exist without Dependant object then it represents composition.
Composition represents tight coupling.
If we create object of dependency class as data member inside the dependent class it represents
composition.
2. Aggegration
Agenda
Inheritance
Type of Inheritance
Diamond problem
Virtual base class
Mode of Inheritance
Runtime Polymorphism
Virtual Functions
vptr and vtable
RTTI
Inheritance
If "is-a" relationship exist between two types then we should use inheritance.
Inheritance is also called as "Generalization".
Consider example:
1. Employee is-a Person
2. Book is-a product
3. Car is-a Vehicle
4. Rectangle is-a Shape
5. Loan Account is-a Account
//Parent class
class Person//Base class
{
};
//Child class
class Employee:public Person//Derived class
{
};
Types of inheritance
1. Single Inheritance
class A{
};
class B : public A{
};
2. Multiple Inheritance
class A{
};
class B{
};
class C{
};
class D : public A, public B, public C{ };
3. Hierarchical Inheritance
class A{
};
class B : public A{
};
class C : public A{
};
class D : public A{
};
4. Multilevel Inheritance
class B is derived from class A, class C is derived from class B and class D is derived from class C.
If single inheritance is having multiple levels then it is called multilevel inheritance.
class A{
};
class B : public A{
};
class C : public B{
};
class D : public C{
};
Hybrid Inheritance
Combination of any two or more than two types of inheritance is called hybrid inheritance.
class A{
};
class B : public A{
};
class C : public A{
};
class D : public C{
};
Diamond Problem
It is hybrid inheritance. Its shape is like diamond hence it is also called as diamond inheritance.
class A{
};
class B : public A{
};
class C : public A{
};
class D : public B, public C{
};
Data members of indirect base class inherit into the indirect derived class multiple times.
Hence it effects on size of object of indirect derived class.
Member functions of indirect base class inherit into indirect derived class multiple times.
If we try to call member function of indirect base class on object of indirect derived class, then compiler
generates ambiguity error.
If we create object of indirect derived class, then constructor and destructor of indirect base class gets
called multiple times.
All above problems generated by hybrid inheritance is called diamond problem.
If we want to overcome diamond problem, then we should declare base class virtual i.e. we should
derive class B & C from class A virtually. It is called virtual inheritance. In this case, members of class A
will be inherited into B & C but it will not be inherited from B & C into class D.
class A{
};
class B : virtual public A{
};
class C : virtual public A{
};
class D : public B, public C{
};
Mode of inheritance
If we use private/protected/public keyword to control visibility of members of class then it is called
access specifier.
If we use private/protected/public keyword to extend the class then it is called mode of inheritance.
In below statement, mode of inheritance is public if we dont mention then the default mode of
inheritance is private.
In private mode of inheritance, the visibility of base class members that inherit inside the derived class
is made as private inside the derived class
In protected mode of inheritance except private members, the visibility of base class members that
inherit inside the derived class is made as protected inside the derived class
In public mode of inheritance, the visibility of base class members that inherit inside the derived class
does not change inside the derived class
In all types of mode, private members inherit into derived class but we can not access it inside member
function of derived class.
If we want to access private members inside derived class then
1. Either we should use member function(getter/setter).
2. or we should declare derived class as a friend inside base class.
If we want to create object of derived class then constructor of base class and derived must be public
RunTime Polymorphism
During inheritance, members of base class inherit into derived class hence using derived class object,
we can access members of base class as well as derived class.
Members of derived class do not inherit into the base class hence using base class object we can access
members of base class only.
Members of base class inherit into derived class hence derived class object can be considered as base
class object.
Example : Employee object is-a Person object.
Since Derived class object can be considered as Base class object, we can use it in place of Base class
object.
Base b1;
Base b2 = b1;//OK
Derived d1;
b1 = d1;//OK
If we assign derived class object to the base class object then compiler copies state of base class
portion from derived class object into base class object. It is called Object slicing.
During Object slicing, mode of inheritance must be public.
class Base{
public:
int n1,n2;
void printBase(){
cout<<num1<<","<<num2<<endl;
}
}
class Derived:public Base(){
public:
int n3;
Derived(int n1,int n2,int n3){
this->n1=n1;
this->n2=n2;
this->n3=n3;
}
}
int main( void )
{
Base base;
Derived derived( 500,600,700);
base = derived; //OK : Object Slicing
base.printRecord(); //Base::printRecord() : 500,600
return 0;
}
Prepared By : Rohan Paramane 6/9
Day06_Help.MD Sunbeam Infotech 2024-09-14
Members of derived class do not inherit into base class. Hence base class object, can not be considered
as derived class object.
Since base class object, can not be considered as derived class object, we can not use it in place of
derived class object.
Process of converting, pointer of derived class into pointer of base class is called upcasting.
Upcasting represents object slicing.
In case of upcasting, explicit type casting is optional.
Main purpose of upcasting is to reduce object dependancy in the code.
Process of converting pointer of base class into pointer of derived class is called downcasting.
In Case of downcasting, explicit typecasting is mandatory.
Note: Only in case of upcasting, we can do downcasting. Otherwise downcasting will fail.
return 0;
}
Virtual Function
In case of upcasting, if we want to call function, depending on type of object rather than type of pointer
then we should declare function in base class virtual.
If class contains, at least one virtual function then such class is called polymorphic class.
If signature of base class and derived class member function is same and if function in base class is
virtual then derived class member function is by default considered as virtual.
If base class is polymorphic then derived class is also considered as polymorphic.
Process of redefining, virtual function of base class, inside derived class, with same signature, is called
function overriding.
Rules for function overriding
1. Function must be exist inside base class and derived class(different scope)
2. Signature of base class and derived class member function must be same( including return type).
3. At least, Function in base class must be virtual.
Virtual function, redefined in derived class is called overriden function.
Prepared By : Rohan Paramane 7/9
Day06_Help.MD Sunbeam Infotech 2024-09-14
Definition 1: In case of upcasting, a member function, which gets called depending on type of object
rather than type of pointer, is called virtual function.
Definition 2: In case of upcasting, a member function of derived class which is designed to call using
pointer of base class is called virtual function.
We can call virtual function on object but it is designed to call on Base class pointer or reference.
We can instantiate concrete class but we can not instantiate abstract class and interface.
We can not instantiate abstract class but we can create pointer/reference of it.
If we extend abstract class then it is mandatory to override pure virtual function in derived class
otherwise derived class can be considered as abstract.
Abstract class can contain, constructor as well as destructor.
An ability of different types of object to use same interface to perfrom different operation is called
Runtime Polymorphism.
Agenda
RTTI
Virtual Destructor
Advanced Casting Operators
Exception Handling
Friend Function and class
Manipulators
Template
Shallow Copy and Deep Copy
Copy Constructor
#include<iostream>
#include<string>
#include<typeinfo>
using namespace std;
int main( void )
{
float number = 10;
const type_info &type = typeid( number );
string typeName = type.name();
cout<<"Type Name : "<<typeName<<endl;
return 0;
}
In case of upcasting, if we want to find out type of object then we should use RTTI.
In case of upcasting, if we want to find out true type of object then base class must be polymorphic.
Using NULL pointer, if we try to find out true type of object then typeid throws std::bad_typeid
exception.
Virtual Destructor
A destructor is implicitly invoked when an object of a class goes out of scope or the object's scope ends
to free up the memory occupied by that object.
Due to early binding, when the object pointer of the Base class is deleted, which was pointing to the
object of the Derived class then, only the destructor of the base class is invoked
Prepared By : Rohan Paramane 1/6
Day07_Help.MD Sunbeam Infotech 2024-09-16
It does not invoke the destructor of the derived class, which leads to the problem of memory leak in
our program and hence can result in undefined behavior.
To correct this situation, the base class should be defined with a virtual destructor.
Making base class destructor virtual guarantees that the object of derived class is destructed properly,
i.e., both base class and derived class destructors are called.
to make a virtual destrictor use virtual keyword preceded by a tilde(~) sign and destructor name inside
the parent class.
It ensures that first the child class's destructor should be invoked and then the destructor of the parent
class is called.
Note: There is no concept of virtual constructors in C++.
1. dynamic_cast operator
In case of polymorphic type, if we want to do downcasting then we should use dynamic_cast operator.
dynamic_cast operator check type conversion as well as inheritance relationship between type of source
and destination at runtime.
In case of pointer if, dynamic_cast operator fail to do downcasting then it returns NULL.
In case of reference, if dynamic_cast operator fail to do downcasting then it throws std::bad_cast
exception.
2. static_cast operator
If we want to do type conversion between compatible types then we should use static_cast operator.
In case of non polymorphic type, if we want to do downcasting then we should use static_cast operator.
In case of upcasting, if we want to access non overriden members of Derived class then we should do
downcasting.
static_cast operator do not check whether type conversion is valid or invalid. It only checks inheritance
between type of source and destination at compile time.
Risky conversion not be used, should only be used in performance-critical code when you are certain it
will work correctly.
The static_cast operator can be used for operations such as converting a pointer to a base class to a
pointer to a derived class. Such conversions are not always safe.
3. const_cast operator
4. reinterpret_cast operator.
If we want to convert pointer of any type into pointer of any other type then we should use
reinterpret_cast operator.
The reinterpret_cast operator can be used for conversions such as char* to int*,
or One_class* to Unrelated_class*, which are inherently unsafe.
Exception Handling
Following are the operating system resources that we can use in application development
1. Memory
2. File
3. Thread
4. Socket
5. Network connection
6. IO Devices etc.
Since OS resources are limited, we should use it carefully.
If we make syntactical mistake in a program then compiler generates error.
Without definition, if we try to access any member then linker generates error.
Logical error / syntacticaly valid but logicaly invalid statements represents bug.
If we give wrong input to the application then it generates runtime error/exception.
Exception is an object, which is used to send notification to the end user of the system if any
exceptional situation occurs in the program.
If we want to manage OS resources carefully then we should use exception handling mechanism.
Need of exception Handling:
1. To avoid resource leakage.
2. To handle all the runtime errors(exeption) centrally.
If we want to handle exception then we should use 3 keywords:
1. try
2. catch
3. throw
1. try:
2. throw:
3. catch:
try
{
}
catch(...)
{
}
class ArithmeticException{
private:
string message;
public:
Stack Unwinding
During execution of function if any exception occurs then process of destroying FAR and returning
control back to the calling function is called stack unwinding.
During stack unwinding, destructor gets called on local objects( not on dynamic objects ).
Manipulator
It is a function which is used to format the output.
Manipulators are of two types
1. Without arguments
2. With arguments
1. endl
2. setw
3. fixed
4. scientific
5. setprecision
6. hex
7. dex
8. oct
9. left
10. right
Agenda
Templates
Shallow Copy and Deep Copy
Copy Constructor
STL
Document Link
https://en.cppreference.com/w/
Template
If we want to write generic program in C++ then we should use template.
Using template we can not reduce code size or execution time but we can reduce developers effort.
It is designed for implementing generic data structure and algorithms
Types of template:
1. Function Template
2. Class Template
1. Function Template
Type inference : It is ability of compiler to detect type of argument at compile time and passing it as a
argument to the function.
2. Class Template
In C++, by passing data type as a argument, we can write generic code hence parameterized type is
called template.
template<class T>
class Array // Parameterized type
{
private:
int size;
T *arr;
public:
Array( void ) : size( 0 ), arr( NULL )
{
}
Array( int size )
{
this->size = size;
this->arr = new T[ this->size ];
}
void acceptRecord( void ){
}
void printRecord( void ){
}
~Array( void ){ }
};
int main( void )
{
Array<char> a1( 3 );
a1.acceptRecord();
a1.printRecord();
return 0;
}
Operator overloading
Conversion Function
Copy Constructor
Copy constructor is a parametered constructor of the class which take single parameter of same type
but using reference.
Copy constructor gets called in following conditions:
class ClassName
{
public:
//this : Address of dest object
//other : Reference of src object
ClassName( const ClassName &other )
{
//TODO : Shallow/Deep Copy
}
};
If we do not define copy constructor inside class then compiler generate copy constructor for the class.
It is called, default copy constructor. By default it creates shallow copy.
Job of constructor is to initialize object. Job of destructor is to release the resources. Job of copy
constructor is to initialize newly created object from existing object.
Note : Creating copy of object is expesive task hence we should avoid object copy operation. To avoid
the copy, we should use reference.
During initialization of object, if there is need to create deep copy then we should define user defined
copy constructor inside class.
STL
We can not divide template code into multiple files.
Standard Template Library( STL) is a collection of readymade template data structure classes and
algorithms.
The Standard Template Library (STL) is a set of C++ template classes to provide common programming
data structures and functions such as lists, stacks, arrays, etc.
1. Containers
2. Algorithms
3. Function Objects
4. Iterators
1. Container
1. Sequence containers
2. Associative containers
3. Unordered associative containers
4. Sequence container adapters
STL
│
├── Containers
├── Sequence Containers
│ ├── vector
│ ├── deque
│ ├── list
│ └── forward_list
├── Associative Containers
│ ├── set
│ ├── multiset
│ ├── map
│ └── multimap
├── Unordered Associative Containers
│ ├── unordered_set
│ ├── unordered_multiset
│ ├── unordered_map
│ └── unordered_multimap
└── Container Adapters
├── stack
├── queue
└── priority_queue
2. Algorithm
They act on containers and provide means for various operations for the contents of the containers.
Sorting
Searching
3. Functions
The STL includes classes that overload the function call operator.
Instances of such classes are called function objects or functors.
Functors allow the working of the associated function to be customized with the help of parameters to
be passed.
4. Iterators
As the name suggests, iterators are used for working upon a sequence of values.
They are the major feature that allows generality in STL.
Iterators are used to point at the memory addresses of STL containers.
They are primarily used in sequences of numbers, characters etc.
They reduce the complexity and execution time of the program.
Sequence Containers
Sequence containers are used for data structures that store objects of the same type in a linear manner.
vector: A dynamic array that can grow and shrink in size. It provides fast random access to elements
and efficient insertion and deletion at the end.
deque: A double-ended queue that supports efficient insertion and deletion at both ends. It provides
similar functionality to vector but may have better performance for inserting and deleting elements at
the beginning.
list: A doubly-linked list that allows for efficient insertion and deletion of elements at any position. It
does not provide random access to elements and has slower traversal compared to vector and deque.
forward_list: A singly-linked list that provides similar functionality to list but with reduced memory
overhead. It allows for efficient insertion and deletion at the beginning and after an element.
Associative Containers
Associative containers implement sorted data structures that can be quickly searched.
set : collection of unique keys, sorted by keys
map : collection of key-value pairs, sorted by keys, keys are unique
multiset : collection of keys, sorted by keys
multimap : collection of key-value pairs, sorted by keys
Container adaptors
Container adaptors provide a different interface for sequential containers.
Prepared By : Rohan Paramane 5/6
Day08_Help.MD Sunbeam Infotech 2024-09-18
Vector
Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is
inserted or deleted, with their storage being handled automatically by the container.
Vector elements are placed in contiguous storage so that they can be accessed and traversed using
iterators.
In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes the
array may need to be extended. Removing the last element takes only constant time because no
resizing happens.
When the vector needs to grow beyond its current capacity, it typically doubles its capacity.
Inserting and erasing at the beginning or in the middle is linear in time.
the iterator in the vector is a Random Access Iterator that Supports all iterator operations including
arithmetic (e.g., +, -), comparison (<, >, etc.), and dereferencing (*, []).
Agenda
STL
File IO
map
map is a sorted associative container that contains key-value pairs with unique keys.
Keys are sorted by using the comparison function Compare.
Search, removal, and insertion operations have logarithmic complexity.
Maps are usually implemented as Red–black trees
Iterators of map iterate in ascending order of keys, where ascending is defined by the comparison that
was used for construction.
Iterator of map are bidirectional iterator that supports dereferencing (*, ->) and bidirectional movement
(++, --).
iterator
An iterator in C++ is an object that enables traversal over the elements of a container (such as
std::vector, std::list, std::map, etc.) and provides access to these elements.
Iterators are a fundamental part of the Standard Template Library (STL) and are designed to abstract the
concept of element traversal, making it possible to work with different containers in a consistent
manner.
1. Traversal: Iterators allow you to move through the elements of a container, one element at a time.
2. Access: Iterators provide access to the element they point to, typically through the dereference
operator (*).
3. Type-Specific: Iterators are strongly typed, meaning that an iterator for an std::vector will be different
from an iterator for an std::list.
Types of Iterators:
1. Input Iterators:
Can read elements from a container. Only allow single-pass access (i.e., you can only move forward
through the container).
2. Output Iterators:
3. Forward Iterators:
4. Bidirectional Iterators:
Stream
We give input to the executing program and the execution program gives back the output.
The sequence of bytes given as input to the executing program and the sequence of bytes that comes
as output from the executing program are called stream.
In other words, streams are nothing but the flow of data in a sequence.
The input and output operation between the executing program and the devices like keyboard and
monitor are known as “console I/O operation”.
The input and output operation between the executing program and files are known as “disk I/O
operation”.
The I/O system of C++ contains a set of classes which define the file handling methods
These include ifstream, ofstream and fstream classes. These classes are derived from fstream and from
the corresponding iostream class.
These classes are designed to manage the disk files, are declared in fstream and therefore we must
include this file in any program that uses files.
Standard Stream Objects of C++ associated with console:
1. cin -> Associated with Keyboard
2. cout -> Associated with Monitor
3. cerr -> Error Stream
4. clog -> Logger Stream
ifstearm is a derived class of istream class which is declared in std namespace. It is used to read record
from file.
ofstearm is a derived class of ostream class which is declared in std namespace. It is used to write
record inside file.
fstream is derived class of iostream class which is declared in std namespace. It is used to read/write
record to/from file.
stream hirerachy
Prepared By : Rohan Paramane 2/5
Day09_Help.MD Sunbeam Infotech 2024-09-19
istream :
ostream :
ifstream :
ofstream :
fstream :
This class provides support for simultaneous input and output operations.
Inherits all the functions from istream and ostream classes through iostream.
File Handling
A variable is a temporary container, which is used to store record in RAM.
A file is permanent container which is used to store record on secondry storage.
File is operating system resource.
Types of file:
1. Text File
2. Binary File
1. Text File
2. Binary File
ios_base::out:
ios_base::out | ios_base::trunc
"r" mode
ios_base::in
"a" mode
ios_base::out | ios_base::app
ios_base::app
"r+" mode
ios_base::in | ios_base::out
"w+" mode
"a+" mode
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream
headerfile.
Agenda
Operator Overloading
Function Object
Conversion Function
Operator Overloading
operator is token in C/C++.
It is used to generate expression.
operator is keyword in C++.
Types of operator:
1. Unary operator
2. Binary Operator
3. Ternary operator
Unary Operator:
If operator require only one operand then it is called unary operator.
example : Unary(+,-,*) , &, !, ~, ++, --, sizeof, typeid etc.
Binary Operator:
If operator require two operands then it is called binary operator.
Example:
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Bitwise operator
5. Assignment operator
Ternary operator:
If operator require three operands then it is called ternary operator.
Example:
Conditional operator( ? : )
In C/C++, we can use operator with objects of fundamental type directly.( No need to write extra code
).
In C++, also we can not use operator with objects of user defined type directly.
If we want to use operator with objects of user defined type then we should overload operator.
class Point
{
int x;
int y;
};
If we want to use operator with objects of user defined type then we should overload operator.
To overload operator, we should define operator function.
We can define operator function using 2 ways
1. Using member function
2. Using non member function.
By defining operator function, it is possible to use operator with objects of user defined type. This
process of giving extension to the meaning of operator is called operator overloading.
Using operator overloading we can not define user defined operators rather we can increase capability
of existing operators.
1. Assignment operator( = )
2. Subscript / Index operator( [] )
3. Function Call operator[ () ]
4. Arrow / Dereferencing operator( -> )
Using operator overloading, we can not change number of parameters passed to the operator function.
If we want to overload, binary operator using member function then operator function should take only
one parameter.
Using operator overloading, we can not change, precedance and associativity of the operator.
If we want to overload unary operator using member function then operator function should not take
any parameter.
c2 = ++ c1; //c2=operator++( c1 );
1. cout<<c1; //cout.operator<<( c1 );
2. cout<<c1; //operator<<(cout, c1 );
According to first statement, to print state of c1 on console, we should define operator<<( ) function
inside ostream class. But ostream class is library defined class hence we should not modify its
implementation.
According to second statement, to print state of c1 on console, we should define operator<<() function
globally. Which possible for us. Hence we should overload operator<<( ) using non member function.
class ClassName
{
friend ostream& operator<<( ostream &cout, ClassName &other );
};
If we want to accept state of object ( of structure/class ) from console( keyboard ) then we should
overload extraction operator.
1. cin>>c1; //cin.operator>>( c1 )
2. cin>>c1;//operator>>( cin, c1 );
According to first statement, to accept state of c1 from console, we should define operator>>( )
function inside istream class. But istream class is library defined class hence we should not modify its
implementation.
According to second statement, to accept state of c1 from console, we should define operator>>( )
function globally. Which possible for us. Hence we should overload operator>>( ) using non member
function.
class ClassName
{
friend istream& operator>>( istream &cin, ClassName &other );
};
istream& operator>>( istream &cin, ClassName &other )
{
//TODO : accept state of object using other
return cin;
}
//If we use subscript operator with object at RHS of assignment operator then
expression must return value from array.
Array a1;
cin>>a1; //operator>>( cin, a1 );
cout<<a1; //opeator<<( cout, a1 );
int element = a1[ 2 ]; //int element = a1.operator[]( 1 );
// If we want to use sub script operator with object at LHS of assignment operator
then expression should not return a value rather it should return either address /
reference of memory location.
Array a1;
cin>>a1; //operator>>( cin, a1 );
a1[ 1 ] = 200; //a1.operator[]( 1 ) = 200;
cout<<a1; //opeator<<( cout, a1 );
Complex c1(10,20);
Complex c2 = c1; //On c2 copy ctor will call
Prepared By : Rohan Paramane 5/8
Day10_Help.MD Sunbeam Infotech 2024-09-20
Complex c1(10,20);
Complex c2;
c2 = c1; //c2.operator=( c1 )
class ClassName
{
public:
ClassName& operator=( const ClassName &other )
{
//TODO : Shallow/Deep Copy
return *this;
}
};
If we do not define assignment operator function inside class then compiler generates default
assignment operator function for the class. By default it creates shallow Copy.
During assignment, if there is need to create deep copy then we should overload assignment operator
function.
class Complex
{
private:
int real;
int imag;
public:
Complex(int real = 0, int imag = 0)
{
this->real = real;
this->imag = imag;
}
void operator()(int real, int imag)
{
this->real = real;
this->imag = imag;
}
void printRecord(void)
{
cout << "Real Number :" << this->real << endl;
cout << "Imag Number :" << this->imag << endl;
}
};
int main(void)
{
Prepared By : Rohan Paramane 6/8
Day10_Help.MD Sunbeam Infotech 2024-09-20
Complex c1;
c1(10, 20); // c1.operator()( 10, 20 );
c1.printRecord();
return 0;
}
If we use any object as a function then such object is called function object or functor.
In above code, c1 is function object.
Conversion Function
It is a member function of a class which is used to convert state of object of fundamental type into user
defined type or vice versa. Following are conversion functions in C++
In above code, single parameter constructor is responsible for converting state of number into c1
object. Hence single parameter constructor is called conversion function.
In above code, assignment operator function is responsible for converting state of number into c1
object hence it is considered as converion function.
If we want to put restriction on automatic instantiation then we should declare single parameter
constructor explicit.
"explicit" is a keyword in C++.
We can use it with any constructor but it is designed to use with single parameter constructor.
In above code, type conversion operator function is responsible for converting state of c1 into integer
variable(real). Hence it is considered as conversion function.
Explore More