C - C++ Notes
C - C++ Notes
C - C++ Notes
C Programming Language
• Who is the main contributor in designing the C language after Dennis Ritchie?
Brain Kernighan.
- Portable: C is called a mid-level programming language because it binds the low level and high
-level programming language.
- Mid Level: C is a mid-level programming language as it combines the low- level language with
the features of the high-level language.
- Fast Speed: C language is very fast as it uses a powerful set of data types and operators.
- Memory Management: C provides an inbuilt memory function that saves the memory and
improves the efficiency of our program.
- Pointer: C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
• How does a program execute in C ? - Program execution in C by GFG
Variable in C by JAVATPOINT
• Scope of variable
Scope of the variable can be defined as the part of the code area where the variables declared
in the program can be accessed directly. In C, all identifiers are lexically (or statically) scoped.
Scoping is generally divided into two classes, lets understand with an example :-
int x = 10;
int f() {
return x; }
int g() {
int x = 20;
return f(); }
main() {
printf(g()); }
1. Static Scoping :- In static scoping the compiler first searches in the current block, then in
global variables, then in successively smaller scopes. C, C++ and Java, variables are always
statically (or lexically) scoped.
2. Dynamic Scoping :- in dynamic scoping the compiler first searches the current block and then
successively all the calling functions. Dynamic scoping is very uncommon in the familiar
languages but Perl supports both dynamic and static scoping.
Output for the above program :- 20
Static scoping also makes it much easier to make a modular code as programmer can figure out
the scope just by looking at the code. In contrast, dynamic scope requires the programmer to
anticipate all possible dynamic contexts.
• What is a C Token?
Keywords, Constants, Special Symbols, Strings, Operators, Identifiers used in C program are
referred to as C Tokens.
Identifier refers to name given to entities such as variables, functions, structures etc. Identifiers
must be unique.
• Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Note :- Structure, Union & Enum are also called as user-defined data types.
Also known as ‘automatic type conversion’.Done by the compiler on its own, without any
external trigger from the user.Generally takes place when in an expression more than one data
type is present. In such condition type conversion (type promotion) takes place to avoid loss of
data.
int x = 10;
char y = 'a';
x = x + y;
float z = x + 1.0;
This process is also called type casting and it is user defined. Here the user can type cast the
result to make it of a particular data type.
double x = 1.2;
Output: sum = 2
#include<stdio.h>
int main()
day = Wed;
printf("%d",day);
return 0;
Note :- & (ampersand) means the address-of, mainly used to pass by reference. *(asterisk)
means the dereference of a pointer variable, meaning to get the value of that pointer variable.
Without an asterisk, an initialized pointer holds a memory address not its value.
• Structure in C
A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.
Structure members cannot be initialized with declaration. The reason for above error is simple,
when a datatype is declared, no memory is allocated for it. Memory is allocated only when
variables are created. Structure members can be initialized using curly braces ‘{}’. For example,
following is a valid initialization.
• Union in C
refer to this - Union in C by GFG
- If there is a situation where only 5 elements are needed to be entered in this array. In this
case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 9 to 5.
- Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But
there is a need to enter 3 more elements in this array. In this case 3 indices more are required.
So the length (size) of the array needs to be changed from 9 to 12.
So, Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate
dynamic memory allocation in C programming. They are :-
1. malloc() & calloc() :- “memory allocation" & “contiguous allocation” both method are used
to dynamically allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form.
If space is insufficient, allocation fails and returns a NULL pointer.
Note :- The only difference between them is that malloc() initializes each block with default
garbage value while Calloc() initializes each block with a default value ‘0’.
2. free() :- “free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it. Syntax: free(ptr);
To store a negative integer, Calculate the two’s complement of the same positive integer.
follow the following steps :- Let's Say we want to store -10.
Step-2 − Calculate the One’s complement( the zeroes would be changed to one and one to
zeroes) of 5: 0101
Step-3 − Add 1 to above to ge the two's complement , giving 0110, which is -10
To store char, For example, if we want to store char ‘A’ in computer, the corresponding ASCII
value will be stored in computer.ASCII value for capital A is 65.To store character value,
computer will allocate 1 byte (8 bit) memory.65 will converted into binary form which is
(1000001) 2. Because computer knows only binary number system.Then 1000001 will be stored
in 8-bit memory.
Note :- We can also store char value in int variable( will be stored in binary of the ascii code of
the char ) & int value in char variable. Consider the below link for the example. How integers
are stored in char variable ?
1. Winding phase: In Winding phase, the recursive function keeps calling itself. This phase ends
when the base condition is reached.
2. Unwinding phase: When the base condition is reached, unwinding phase starts and control
returns back to the original call.
#include<stdio.h>
void rec();
int main(){
rec(1);
return 0; }
void rec(int n) {
if(n<3) {
rec(n+1); }
%d: It is a datatype format specifier used to print and scan an integer value.
%c: It is a datatype format specifier used to display and scan a character value.
%f: It is a datatype format specifier used to display and scan a float value.
#include<stdio.h>
int main()
char a[20];
int n=sprintf(a,"javaToint");
printf("value of n is %d",n);
return 0;}
Output:
value of n is 9
• What is /0 character ?
The Symbol mentioned is called a Null Character. It is considered as the terminating character
used in strings to notify the end of the string to the compiler.
Note :- getch() or getche() does not hold the screen, rather it wait for user to hit any character
from keyboard. The next statement after getch(); will only execute when there will be any
generation of character by user from keyboard. getch() is library function define in conio. It is
used to get a single character from the console.
to be used in the program. Include the file in the ‘#include’ section in its name.
#include<stdio.h>
void start() {
printf("Hello");
void main()
{
if(printf("hello world")){}
Output:
hello world
• Write a program to swap two numbers without using the third variable.
"conio.h" stands for Console Input & Output header & isn't used anymore. It was used in old
Turbo C compiler which are 16-bit . It includes functions like clrscr() (Clears the Screen), getch()
(it holds the screen until and input from keyboard is received).
"iostream" - standard C++ input and output, contains objects like cout, cin and cerr. works with
C++ streams, which are objects that manages IO.It is the default IO choice for C++ projects.
- Algorithms
- Containers
- Functions
- Iterators
Vectors are 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 there may be a
need of extending the array. Removing the last element takes only constant time because no resizing
happens. Inserting and erasing at the beginning or in the middle is linear in time.
For example-
int x=10;
1) Once a reference is created, it cannot be later made to reference another object; it cannot
be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers
Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc
Nonetheless, a compiler with a good optimizer is able to inline recursive calls until some depth
is fixed at compile-time and insert non-recursive calls at compile time for the cases when the
actual depth exceeds run time.
Oops :-
Object-oriented programming – As the name suggests uses objects in programming. The object-
oriented approach views a problem in terms of objects involved rather than procedure for
doing it. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming.
• Object
Any real world entity is termed as an object. An Object is an instance of a Class. For ex, table,
chair, tv etc.
• Class
A Class is a user-defined data-type which has data members and member functions. A class is
like a blueprint for an object.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions define the
properties and behaviour of the objects in a Class.
In the example of class person, the data member will be name, id and member functions will be
get details.
• What is shallow copy & Also differentiate between shallow & deep copy.
Shallow Copy:
In shallow copy, an object is created by simply copying the data of all variables of the original
object. This works well if none of the variables of the object are defined in the heap section of
memory. If some variables are dynamically allocated memory from heap section, then copied
object variable will also reference then same memory location.
This will create ambiguity and run-time errors dangling pointer. Since both objects will
reference to the same memory location, then change made by one will reflect those change in
another object as well. Since we wanted to create a replica of the object, this purpose will not
be filled by Shallow copy.
Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in
order to perform shallow copy at compile time.
• What are destructors in C++?
A constructor is automatically called when an object is first created. Similarly when an object is
destroyed a function called destructor automatically gets called. A destructor has the same
name as the constructor (which is the same as the class name) but is preceded by a tilde.
• Static Keyword in C++
Static elements are allocated storage only once in a program lifetime in static storage area. And
they have a scope till the program lifetime. Static Keyword can be used with following,
Static variables when used inside function are initialized only once, and then they hold there
value even through function calls.
These static variables are stored on static storage area , not in stack.
Example :-
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular
month. In this case, he is not allowed to directly access the data of the sales section. He will first
have to contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name “sales section”. so
this wrapping of data in a section( class ) so that only person(member function or methods)
from that section can manipulate data( data member or variables ) is called encapsulation.
In the above program the variable a is made private. This variable can be accessed and
manipulated only using the functions get() and set() which are present inside the class. Thus we
can say that here, the variable a and the functions get() and set() are binded together which is
nothing but encapsulation.
Note :- Encapsulation also known as data hiding because using encapsulation also hides the
data. In the above example, the data of any of the section like sales, finance or accounts are
hidden from any other section.
As we have seen in above example, access specifiers plays an important role in implementing
encapsulation in C++. The process of implementing encapsulation can be sub-divided into two
steps:
1. The data members should be labeled as private using the private access specifiers
2. The member function which manipulates the data members should be labeled as public using
the public access specifier
• Access modifiers/specifiers
There are 3 types of access modifiers available in C++:
1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed by
other classes and functions too. The public members of a class can be accessed from anywhere
in the program using the direct member access operator (.) with the object of that class.
2. Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of a class.
3. Protected: Protected access modifier is similar to private access modifier in the sense that it
can’t be accessed outside of it’s class unless with the help of friend class, the difference is that
the class members declared as Protected can be accessed by any subclass(derived class) of that
class as well.
• Friend class & function in C++ .
Friend Class A friend class can access private and protected members of other class in which it
is declared as friend. It is sometimes useful to allow a particular class to access private
members of other class. For example, a LinkedList class may be allowed to access private
members of Node.
Friend Function Like friend class, a friend function can be given a special grant to access private
and protected members. A friend function can be:
b) A global function
• Abstraction
Abstraction means displaying only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car but he does
not know about how on pressing accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the
car. This is what abstraction is.
- Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps
us to group data members and member functions using available access specifiers. A Class can
decide which data member will be visible to the outside world and which is not.
- Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
In the this example, we can see that abstraction has achieved by using class. The class
'Summation' holds the private members a, b and c, which are only accessible by the member
functions of that class.
Note :- Here Both screen(class or interface) & covering(access modifiers) over circuit are hiding
something but in a differenr aspect. In abstraction, problems are solved at the design or
interface level. While in encapsulation, problems are solved at the implementation level. So,
Abstraction is used also for hiding something but in a higher degree(class, interface).
Abstraction is done using abstract class or interfaces while encapsulation is done by using
access modifiers. In abstraction, implementation complexities are hidden using abstract
classes and interfaces. While in encapsulation, the data is hidden using methods of getters
and setters.
• Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behaviour in different
situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour depends
upon the types of data used in the operation.
- Function Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.
- Operator Overloading: C++ also provide option to overload operators. For example, we can
make the operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string operands,
concatenates them.
2. Runtime polymorphism:
Suppose, the same function is defined in both the derived class and the based class. Now if we
call this function using the object of the derived class, the function of the derived class is
executed.
This is known as function overriding in C++. The function in derived class overrides the function
in base class.
- Virtual functions should be accessed using pointer or reference of base class type to achieve
run time polymorphism.
- The prototype of virtual functions should be the same in the base as well as derived class.
- They are always defined in the base class and overridden in a derived class. It is not mandatory
for the derived class to override (or re-define the virtual function), in that case, the base class
version of the function is used.
- A class may have virtual destructor but it cannot have a virtual constructor.
For code or ex :- Virtual function by C++ by GFG Do read the "concept of VTABLE and VPTR"
given at the end of the link.
• What is the difference between virtual functions and pure virtual functions?
A virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the virtual keyword.
Example-
class base{
public:
};
A pure virtual function is a function that has no implementation and is declared by assigning 0.
It has no body.
Example-
class base{
public:
};
Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything.
It is used to simply tell the compiler that a function will be pure and it will not have anybody.
• Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
- Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
- Super Class: The class whose properties are inherited by sub class is called Base Class or Super
class.
- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Modes of Inheritance
- Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
- Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
- Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed.
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e.
one sub class is inherited by one base class only.
Syntax:
//body of subclass
};
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one classes. i.e one sub class is inherited from more than one base classes.
Syntax:
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every
base class must be specified.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited
from a single base class. i.e. more than one derived class is created from a single base class.
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one
type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
6. A special case of hybrid inheritance : Multipath inheritance: Diamond Problem
A derived class with two base classes and these two base classes have one common base class
is called multipath inheritance. An ambiguity can arrise in this type of inheritance.
• What is the ‘diamond problem’ that occurs with multiple inheritance in C++?
Explain using an example.
The diamond problem occurs when two superclasses of a class have a common base class. For
example, in the following diagram, the TA class gets two copies of all attributes of Person class,
this causes ambiguities ( inexactness ).
The solution to this problem is ‘virtual’ keyword. We make the classes ‘Faculty’ and ‘Student’ as
virtual base classes to avoid two copies of ‘Person’ in ‘TA’ class.
For Code :- Diamond Problem by GFG.
- Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the
kind of object at runtime then matches the call with the right function definition (Refer this for
details). This can be achieved by declaring a virtual function.
• Message Passing
Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function and the information to be sent.
The End