C++ Notes
C++ Notes
There are certain rules that should be followed while naming c++ identifiers:
3. Constants: Constants are also like normal variables. But, the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals.
Constants may belong to any of the data type
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “MSR Degree College”
4. Strings: Strings are nothing but an array of characters ended with a null character (‘\
0’). This null character indicates the end of the string. Strings are always enclosed in
double-quotes. Whereas, a character is enclosed in single quotes in C and C++.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5. Special Symbols: The following special symbols are used in C++ having some special
meaning and thus, cannot be used for some other purpose. [] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
Assignment operator(=): It is used to assign values and for the logical operation
validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that trigger an action when applied to C++
variables and other objects. The data items on which operators act upon are called
operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators. For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
Ternary Operator: The operator that require three operands to act upon are called
ternary operator. Conditional Operator(?) is also called ternary operator.
Syntax: (Expression1)? expression2: expression3;
DATA TYPES:
A data type tells a variable the kind and size of data it can store. When we declare a
variable, the compiler allocates memory for it on the basis of its data type.
In C++, there are three broad categories of data types namely,
For Example:
int age = 18;
For Example:
float area = 34.65;
For Example:
double volume = 127.4935;
double value = 25E11; //Exponential 25E9 = 25 * 10^11
For Example:
bool condition = true;
Syntax:
typedef type newname;
Example of typedef
#include <iostream>
typedef int integer; //we can use integer in place of int
int main()
{
integer total = 100;
cout<<total;
return 0;
}
Output
100
OPERATORS:
An operator is a symbol used for performing operations on operands. An operator
operates operands. The operations can be mathematical or logical. There are different
types of operators in C++ for performing different operations.
Consider the following operation:
a = x + y;
In the above statement, x and y are the operands while + is an addition operator. When
the C++ compiler encounters the above statement, it will add x and y and store the result
in variable a.
There are mainly 6 different types of operators in C++
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators: Operators that operate or work with a single operand are unary
operators. For example: Increment(++) and Decrement(– –) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two operands are binary
operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/)
operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, an operand is greater than
the other operand or not, etc. Some of the relational operators are (==, >= , <= )
int a = 3;
int b = 5;
a < b; // operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combining two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C or C++ returns true
when both the conditions under consideration are satisfied. Otherwise, it returns false.
Therefore, a && b returns true when both a and b are true
4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. The mathematical operations such as addition, subtraction, multiplication,
etc. can be performed at bit-level for faster processing. For example, the bitwise
AND represented as & operator in C or C++ takes two numbers as operands and does
AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
(See this article for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators:
Assignment operators are used to assigning value to a variable. The left side operand of
the assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
a. “=”: This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
For example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and then
assigns the result to the variable on the left.
For example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
For example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
For example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C or C++
used to perform some specific tasks. Some of them are discussed here:
a. sizeof operator:
1. sizeof is much used in the C/C++ programming language.
2. It is a compile-time unary operator which can be used to compute the size of its
operand.
3. The result of sizeof is of the unsigned integral type which is usually denoted by
size_t.
4. Basically, the sizeof the operator is used to compute the size of the variable
b. Conditional Operator:
1. The conditional operator is of the form Expression1? Expression2: Expression3.
2. Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
3. We may replace the use of if..else statements with conditional operators.
(See this article for reference)
Expression:
An expression is a combination of operators, constants and variables. An expression
may consist of one or more operands, and zero or more operators to produce a value.
Every expression produces some value which is assigned to the variable with the help of
an assignment operator.
Examples of C++ expression:
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
Types of Expressions:
Expressions may be of the following types:
o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
Ex1:-
// Array declaration by specifying size and initializing elements
int arr[6] = { 10, 20, 30, 40 }
Ex2:-
// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows −
type arrayName [ x ][ y ];
A two-dimensional array can be think as a table, which will have x number of rows and
y number of columns. A 2-dimensional array a, which contains three rows and four
columns can be shown as below −
C++ Strings:
String is a collection of characters. There are two types of strings commonly used in C++
programming language:
Strings that are objects of string class (The Standard C++ Library string class)
C-strings (C-style Strings)
C-strings
In C programming, the collection of characters is stored in the form of arrays. This is also
supported in C++ programming. Hence it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).
Output
Enter a string: Programming is fun.
You entered: Programming is fun.
In this program, a string str is declared. Then the string is asked from the user.
Instead of using cin>> or cin.get() function, you can get the entered line of text
using getline().
getline() function takes the input stream as the first parameter which is cin and str as the
location of the line to be stored.
Pointers:-
The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.
Usage of pointer
There are many usage of pointers in C++ language.
int ∗ p;
int number=30;
∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
getch();
}
Bubble Sort
Bubble sort is the simplest technique in which we compare every element with its
adjacent element and swap the elements if they are not in order. This way at the end of
every iteration (called a pass), the heaviest element gets bubbled up at the end of the list.
Functions in C++:-
A function is a group of statements that together perform a task. Every C++ program has
at least one function, which is main().
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Syntax:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all
the parts of a function −
Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
Function Body − The function body contains a collection of statements that
define what the function does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
Syntax:
return_type function_name( parameter list );
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when
its function-ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
Default Values for Parameters
When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is
called, the default given value is used, but if a value is specified, this default value is
ignored and the passed value is used instead.
Ex:-
#include <iostream>
int sum(int,int); // function prototype
int main ()
{
int a = 100; // local variable declaration:
int b = 200;
int result;
Syntax
returnType functionName(dataType arrayName[arraySize])
{
// code
}
Let's see an example,
int total(int marks[5])
{
// code
}
Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
void display(int m[5]) // declare function to display marks take a 1d array as parameter
{
cout << "Displaying marks: " << endl;
for (int i = 0; i < 5; ++i) // display array elements
{
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}
int main() {
int marks[5] = {88, 76, 90, 61, 69}; // declare and initialize an array
// call display function pass array as argument
display(marks);
getch();
}
Object
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
An object contains data and methods or functions that operate on that data. Objects take
up space in memory.
It simplifies the software development and maintenance by providing some concepts:
Class
A class, on the other hand, is a blueprint of the object. Conversely, an object can be
defined as an instance of a class. A class contains a skeleton of the object and does not
take any space in the memory.It is a logical entity.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program
without presenting the details.
For example, a database system hides certain details of how data is stored and created
and maintained. Similar way, C++ classes provides different methods to the outside
world without giving internal detail about those methods and data.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
Encapsulation is placing the data and the functions that work on that data in the same
place. While working with procedural languages, it is not always clear which functions
work on which variables but object-oriented programming provides you framework to
place the data and the relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As
the name suggests Inheritance is the process of forming a new class from an existing
class that is from the existing class called as base class, new class is formed called as
derived class.
This is a very important concept of object-oriented programming since this feature helps
to reduce the code size.
Polymorphism
Polymorphism means many forms.Polymorphism is an important feature of OOP and is
usually implemented as operator overloading or function overloading. Operator
overloading is a process in which an operator behaves differently in different situations.
Similarly, in function overloading, the same function behaves differently in different
situations.
Class in C++:
A class is a user-defined data type representing a group of similar objects, which holds
member functions and variables together. We can define classes using the keyword
‘class’ followed by the name of the class. The body of class is defined inside the curly
brackets and terminated by a semicolon at the end.
Declaring Objects:
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need
to create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot(‘.’) operator with the object. For
example if the name of object is obj and you want to access the member function with
the name printName() then you will have to write obj.printName() .
Access modifiers:
These are the specifiers which provide or grant access for the members.
They are of three types:
Private: Only members of the same class have access to private members.
Public: You can access the public members from within, as well as from outside of the
class.
Protected: You can access the protected members from the same class members and
members of the derived class. It is also accessible from outside the class but with the help
of the friend function.
Syntax:
inline return_type function_name(parameters)
{
// function code?
}
Ex:
#include<iostream.h>
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}
Note:
We cannot provide the inlining to the functions in the following circumstances:
o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.
C++ Constructor
1. Constructor in C++ is a special method that is invoked automatically at the time of
object creation.
2. It is used to initialize the data members of new objects generally.
3. The constructor in C++ has the same name as the class or structure.
4. Constructor is invoked at the time of object creation.
5. Constructor does not have a return value, hence they do not have a return type.
6. Constructors can be defined inside or outside the class declaration.
Default Constructors:
Default constructor is the constructor which doesn’t take any argument. It has no
parameters. It is also called a zero-argument constructor.
// Cpp program to illustrate the concept of Constructors
#include <iostream.h>
class construct
{
public:
int a, b;
Parameterized Constructors:
A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.
#include <iostream>
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main()
{
Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is used
to −
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
Syntax:
classname (const classname &obj)
{
// body of constructor
}
Ex:
#include<iostream>
class Number
{
int a;
public:
Number()
{
a = 0;
}
Number(int num)
{
a = num;
}
// When no copy constructor is found, compiler supplies its own copy constructor
Number(Number &obj)
{
cout<<"Copy constructor called!!!"<<endl;
a = obj.a;
}
void display()
{
cout<<"The number for this object is "<< a <<endl;
}
};
int main()
{
Number x, y, z(45), z2;
x.display();
y.display();
z.display();
Number z1(z); // Copy constructor invoked
z1.display();
getch();
}
Constructor Overloading
In C++, We can have more than one constructor in a class with same name, as long as
each has a different list of arguments. This concept is known as Constructor Overloading
and is quite similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class)
and different by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
Ex:
#include <iostream>
class Complex
{
int a, b;
public:
Complex()
{
a = 0;
b =0;
}
Complex(int x, int y)
{
a = x;
b = y;
}
Complex(int x)
{
a = x;
b = 0;
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
int main()
{
Complex c1(4, 6);
c1.printNumber();
Complex c2(5);
c2.printNumber();
Complex c3;
c3.printNumber();
return 0;
}
Destructor:
Destructor is an instance member function which is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going
to be called before an object is destroyed.
Destructor is also a special member function like constructor. Destructor destroys the
class objects created by constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object create by constructor. Hence
destructor can-not be overloaded.
Destructor neither requires any argument nor returns any value.
It is automatically called when object goes out of scope.
Destructor release memory space occupied by the objects created by constructor.
Syntax:
Syntax for defining the destructor within the class
~ <class-name>()
{
}
Syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>()
{
}
Ex:
#include<iostream>
class Test
{
public:
Test()
{
cout<<"\n Constructor executed";
}
~Test()
{
cout<<"\n Destructor executed";
}
};
void main()
{
Test t;
return 0;
}
Static data members:
Static data members are class members that are declared using static keywords. A static
member has certain special characteristics. These are:
Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
It is initialized before any object of this class is being created, even before main
starts.
It is visible only within the class, but its lifetime is the entire program
#include <iostream>
class Example
{
static int x;
public:
void function1()
{
x++;
}
void function2()
{
cout<<"x = "<<x<<"\n";
}
};
int Example :: x=0;
int main()
{
Example obj1, obj2, obj3;
cout<<"Initial value of x" <<"\n";
obj1.function2();
obj2.function2();
obj3.function2();
obj1.function1();
obj2.function1();
obj3.function1();
getch();
}
C++ Inheritance
1. Inheritance is one of the most important features of Object-Oriented Programming.
2. In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically.
3. Inheritance is a feature or a process in which, new classes are created from the
existing classes.
4. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be
inherited from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single Inheritance:
In single inheritance, a class is allowed to inherit from only one class. i.e. one
subclass is inherited by one base class only.
Syntax:
class A
{ ... .. ...
};
class B: public A
{... .. ...
};
Ex:
#include<iostream>
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
{
int b,p;
public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}
void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}
};
main()
{
B _b;
_b.set_B();
_b.cal_product();
return 0;
}
Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than
one class. i.e one subclass is inherited from more than one base class.
Syntax:
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access
mode for every base class must be specified.
Ex:
#include<iostream.h>
#include<conio.h>
class Father
{
public:
void fatherMethod()
{
cout<<"from father method"<<endl;
}
};
class Mother
{
public:
void motherMethod()
{
cout<<"from mother method"<<endl;
}
};
class Ch1:public Father,public Mother
{
public:
void child1()
{
cout<<"from child1"<<endl;
}
};
void main()
{
clrscr();
Ch1 obj1;
obj1.fatherMethod();
obj1.motherMethod();
obj1.child1();
getch();
}
Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class.
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Ex:
#include<iostream>
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
{
protected:
int b;
public:
void set_B()
{
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
cout<<endl<<"Value of B="<<b;
}
};
class C: public B
{
int c,p;
public:
void set_C()
{
cout<<"Enter the Value of C=";
cin>>c;
}
void disp_C()
{
cout<<endl<<"Value of C="<<c;
}
void cal_product()
{
p=a*b*c;
cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;
}
};
main()
{
C obj;
obj.set_A();
obj.set_B();
obj.set_C();
obj.disp_A();
obj.disp_B();
obj.disp_C();
obj.cal_product();
return 0;
}
Hierarchical Inheritance: In this type of inheritance, more than one subclass is
inherited from a single base class. i.e. more than one derived class is created from a
single base class.
Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Ex:
#include<iostream.h>
#include<conio.h>
class Parent
{
public:
void parentMethod()
{
cout<<"from parent"<<endl;
}
};
class Ch1:public Parent
{
public:
void child1()
{
cout<<"from child1"<<endl;
}
};
class Ch2:public Parent
{
public:
void child2()
{
cout<<"from child2"<<endl;
}
};
void main()
{
clrscr();
Ch1 obj1;
obj1.parentMethod();
obj1.child1();
Ch2 obj2;
obj2.parent();
obj2.child2();
getch();
}
Access Specifiers in a class decide the accessibility of the class members, like variables
or methods in other classes. That is, it will decide whether the class members or methods
will get directly accessed by the blocks present outside the class or not, depending on the
type of Access Specifier.
In a program, we need to create methods or variables that can be accessed by the object
of the same class or accessible in the entire program. And Access Modifiers help us to
specify that.
Syntax:
class ClassName
{
private:
// Declare private members/methods here.
public:
// Declare public members/methods here.
protected:
// Declare protected members/methods here.
};
There are three types of access modifiers in C++:
1. Public
2. Private
3. Protected
The public members of a class can be accessed from anywhere in the program using
the (.) with the object of that class.
Ex:
// C++ program to demonstrate public access modifier
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
void main()
{
clrscr();
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.compute_area();
getch();
}
2. Private Access Specifiers
The private keyword is used to create private variables or private functions. The private
members can only be accessed from within the class. Only the member functions or the
friend functions are allowed to access the private data of a class or the methods of a class.
Note -
Protected and Private data members or class methods can be accessed using a function
only if that function is declared as the friend function.
We can use the keyword friend to ensure the compiler understands and make the data
accessible to that function.
Ex:
// C++ program to demonstrate private access modifier
#include<iostream.h>
#include<conio.h>
class Circle
{
private: // private data member
double radius;
public: // public member function
void compute_area(double r)
{
radius = r; // member function can access private data member radius
double area = 3.14*radius*radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
void main()
{
Circle obj; // creating object of the class
// trying to access private data member directly outside the class like obj.radius=1.5
obj.compute_area(1.5);
getch();
}
The protected keyword is used to create protected variables or protected functions. The protected
members can be accessed within and from the derived/child class.
Note - A class created or derived from another existing class(base class) is known as a derived
class. The base class is also known as a superclass. It is created and derived through the process
of inheritance.
Ex:
// C++ program to demonstrate protected access modifier
#include<iostream.h>
#include<conio.h>
class A
{
protected:
int a;
public:
void method1(int x)
{
a=x;
cout<<"a value:"<<a<<endl;
}
};
void main()
{
clrscr();
A obj;
//obj.a=100;
obj.method1(100);
getch();
}
Streams:
A C++ stream is a flow of data into or out
of a program, such as the data written to cout or read from cin.
Stream classes in C++ are used to input and output operations on files and io devices.
These classes have specific features and to handle input and output of the program.
All these classes are defined in the file iostream.h.
C++ Polymorphism:
The term "Polymorphism" is the combination of
"poly" + "morphs" which means many forms. It is a
greek word. A real-life example of polymorphism is a
person at the same time is a father, a husband, and an
employee. So the same person exhibits different
behavior in different situations. This is called
polymorphism. Polymorphism is considered one of
the important features of Object-Oriented
Programming.
Types of Polymorphism
Compile-time Polymorphism.
Runtime Polymorphism.
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and changing
the type of arguments.
Ex:
// C++ program to demonstrate function overloading or Compile-time Polymorphism
#include <iostream.h>
class Polymorphism
{
public:
void func(int x) // Function with 1 int parameter
{
cout << "value of x is " <<x << endl;
}
void func(double x) // Function with same name but 1 double parameter
{
cout << "value of x is " <<x << endl;
}
void func(int x, int y) // Function with same name and 2 int parameters
{
cout << "value of x and y is " <<x << ", " << y << endl;
}
};
int main()
{
Polymorphism obj1;
obj1.func(7); // Function being called depends on the parameters
obj1.func(9.132); // func() is called with double value
obj1.func(85, 64); // func() is called with 2 int values
return 0;
}
B. Operator Overloading
Using operator overloading in C++, you can specify more than one meaning for an
operator in one scope. The purpose of operator overloading is to provide a special
meaning of an operator for a user-defined data type. You can also use operator
overloading to perform different operations using one operator.
For example, we can make use of the addition operator (+) for string class to
concatenate two strings. We know that the task of this operator is to add two operands.
So a single operator ‘+’, when placed between integer operands, adds them and when
placed between string operands, concatenates them.
Syntax:
To overload a C++ operator, you should define a special function inside the Class as
follows:
class class_name
{
... .. ...
public
return_type operator symbol (argument(s))
{
... .. ...
}
... .. ...
};
Ex:
#include <iostream.h>
class OverLoad
{
private:
int a,b;
public:
OverLoad()
{
a=0; b=0;
}
void in()
{
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter the second number : ";
cin >> b;
}
// Overload the prefix decrement operator
void operator-- ()
{
a= a+10;
b= b+10;
}
void out()
{
cout<<"The decremented elements of the object are: "<<endl<< a<<" and
" <<b;
}
};
int main()
{
OverLoad obj;
obj.in();
--obj;
obj.out();
return 0;
}
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
Ex:
// C++ Program to demonstrate the Virtual Function
#include <iostream>
class Base // Declaring a Base class
{
public:
virtual void display() // virtual function
{
cout << "Called virtual Base Class function" <<"\n\n";
}
void print()
{
cout << "Called Base print function" <<"\n\n";
}
};
class Child : public Base // Declaring a Child Class
{
public:
void display()
{
cout << "Called Child Display Function" <<"\n\n";
}
void print()
{
cout << "Called Child print Function" <<"\n\n";
}
};
int main() // Driver code
{
Base* base; // Create a reference of class GFG_Base
Child child;
base = &child;
base->Base::display(); // This will call the virtual function
base->print(); // this will call the non-virtual function
}
Run Time Errors - They are also known as exceptions. An exception caught during run
time creates serious issues.
Errors restrict the normal execution of program. Exception handling is the process of
handling errors and exceptions in such a way that they do not hinder normal execution of
the system. For example, User divides a number by zero, this will compile successfully
but an exception or run time error will occur due to which our applications will be
crashed. In order to avoid this we'll introduce exception handling techniques in our code.
try
catch
throw
Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
try block:
The code which can throw any exception is kept inside(or enclosed in) a try block. Then,
when the code will lead to any error, that error/exception will get caught inside
the catch block.
catch block:
catch block is intended to catch the error and handle the exception condition. We can
have multiple catch blocks to handle different types of exception and perform different
actions when the exceptions occur. For example, we can display descriptive messages to
explain why any particular exception occurred.
Syntax:
try {
// protected code
}
catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
throw statement:
throw statement is used when we explicitly want an exception to occur, then we can
use throw statement to throw or generate that exception.
Syntax:
try
{
throw 'a';
}
catch (int x)
{
cout << "Caught " << x;
}
Ex:
#include <iostream.h>
#include<conio.h>
void main()
{
int a=10, b=0, c;
try // try block activates exception handling
{
if(b == 0)
{
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
getch();
}
Re-throwing an Exception:
In C++, we can re-throw an exception that was caught in a try-catch block by using the
throw keyword without any argument.
Ex:
#include <iostream.h>
#include<conio.h>
int main()
{
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}
Multiple Exceptions:
In C++, you can handle multiple exceptions using a try-catch block with multiple catch
statements. Each catch statement can handle a specific type of exception, allowing you to
perform different actions based on the type of exception that is thrown.
Syntax:
try {
// protected code
}
catch( ExceptionName1 e1 )
{
// code to handle ExceptionName exception
}
catch(ExceptionName2 e2)
{
//code to handle ExceptionName exception
}
Ex:
#include <iostream.h>
#include<conio.h>
void main()
{
int numerator, denominator, res,arr[4] = {10, 20, 30, 40};
int index;
cout << "Enter array index: ";
cin >> index;
try
{
if (index >= 4) // throw exception if array out of bounds
{ // not executed if array is out of bounds
throw "Error: Array out of bounds!";
}
else
{
cout<<”Array value:”<<arr[index]<<endl;
}
cout << "Enter numerator: ";
cin >> numerator;
Templates can be used to define functions, classes and other constructs that can operate
on a variety of data types without having to rewrite the code for each type.
C++ adds two new keywords to support
templates: ‘template’ and ‘type name’.
The second keyword can always be
replaced by the keyword ‘class’.
o Function templates
o Class templates
Function Template:
Function templates are special functions that can operate with generic types. This allows
us to create a function template whose functionality can be adapted to more than one type
or class without repeating the entire code for each type.
In C++ this can be achieved using template parameters. A template parameter is a special
kind of parameter that can be used to pass a type as argument: just like regular function
parameters can be used to pass values to a function, template parameters allow to pass
also types to a function. These function templates can use these parameters as if they
were any other regular type.
Syntax:
template <typename T>
T functionName(T parameter1, T parameter2, ...)
{
// code
}
Ex:
#include<iostream.h>
#include<conio.h>
template <class t>
t sum(t a,t b)
{
cout<<"Total:"<<(a+b)<<endl;
}
void main()
{
clrscr();
sum(10,20);
}
Syntax:
template<class T1, class T2,…..>
return_type function_name (arguments of type T1, T2….)
{
//body of function.
}
Ex:
#include<iostream.h>
#include<conio.h>
template <class t1,class t2,class t3>
void show(t1 a,t2 b,t3 c)
{
cout<<"a value:"<<a<<endl;
cout<<"b value:"<<b<<endl;
cout<<"c value:"<<c<<endl;
}
void main()
{
clrscr();
show(10,20.34,'c');
getch();
}
Template Function Overloading:
The name of the function templates are the same but called with different arguments
is known as function template overloading.
If the function template is with the ordinary template, the name of the function
remains the same but the number of parameters differs.
When a function template is overloaded with a non-template function, the function
name remains the same but the function’s arguments are unlike.
Ex:
// C++ program to illustrate overloading of template function using an explicit function
#include<iostream.h>
#include<conio.h>
template <class T>
void display(T t1) //Template overloading of function
{
cout << "Displaying Template: "<< t1 << "\n";
}
void display(int t1) //Template overloading of function
{
cout << "Explicitly display: "<< t1 << "\n";
}
int main()
{
// Function Call with a different arguments
display(200);
display(12.40);
display('G');
return 0;
}
Class Templates
Class templates like function templates, class templates are useful when a class defines
something that is independent of the data type.
Syntax of Class Template
template<class Ttype>
class class_name
{
//class body;
}
Here Type is a placeholder type name, which will be specified when a class instantiated.
The Type can be used inside the body of the class.
Ex:
#include<iostream.h>
#include<conio.h>
template <class t>
class Demo
{
private:
t num1,num2;
public:
Demo(t n1,t n2)
{
num1=n1;
num2=n2;
}
void check()
{
if(num1>num2)
{
cout<<num1<<" is the largest value"<<endl;
}
else
{
cout<<num2<<" is the largest value"<<endl;
}
}
};
void main()
{
clrscr();
Demo <int>obj1(5,3);
Demo <float>obj2(10.23,20.35);
obj1.check();
obj2.check();
getch();
}
STL in C++:
In C++, the C++ STL is a very powerful feature and it is a set of C++ template classes.
With the help of STL, you can make use of general-purpose classes and functions with
templates. And these implement many popular and most used algorithms and data
structures like vectors, lists, queues and stacks.
The C++ Standard Template Library (STL) is a collection of algorithms, data structures,
and other components that can be used to simplify the development of C++ programs.
The STL provides a range of containers, such as vectors, lists, and maps, as well as
algorithms for searching, sorting and manipulating data.
One of the key benefits of the STL is that it provides a way to write generic, reusable
code that can be applied to different data types. This means that you can write an
algorithm once, and then use it with different types of data without having to write
separate code for each type.
Algorithms
Containers
Function objects
Iterators