Unit 3 - Bce
Unit 3 - Bce
A class is a user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class.
For Example: Consider the Class of Cars. There may be many cars with different names and brands
but all of them will share some common properties like all of them will have 4 wheels, Speed
Limit, Mileage range, etc. So here, the Car is the class, and wheels, speed limits, and mileage are their
properties.
• A Class is a user-defined data type that has data members and member functions.
• Data members are the data variables and member functions are the functions used to manipulate
these variables together, these data members and member functions define the properties and
behaviour of the objects in a Class.
• A C++ class is like a blueprint for an object.
• But we cannot use the class as it is. We first have to create an object of the class to use its features.
An Object is an instance of a Class.
• In the above example of class Car, the data member will be speed limit, mileage, etc, and member
functions can be applying brakes, increasing speed, etc.
A class is defined in C++ using the keyword class followed by the name of the class.
The following is the syntax:
class ClassName
{
access_specifier:
// Body of the class
};
Here, the access specifier defines the level of access to the class’s data members.
Example
class ThisClass
{
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};
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 to Create an Object
We can create an object of the given class in the same way we declare the variables of any other inbuilt
data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is created.
The data members and member functions of the class can be accessed using the dot(‘.’) operator with the
object. For example, if the name of the object is obj and you want to access the member function with the
name printName() then you will have to write:
obj.printName()
Multiple Objects
Example:
#include <iostream.h>
#include <conio.h>
class Student
{
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
};
int main()
{
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Kapil";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
OUTPUT:
201
Kapil
Example2:
#include <iostream.h>
#include <conio.h>
class Student
{
public:
int x, y; //data member (also instance variable)
void input()
{
Cout<<”Enter first number”;
Cin>>x;
Cout<<”Enter Second nimber”
Cin>>y;
}
Void output()
{
cout<<”The numbers are”<<x<<y;
}
};
int main()
{
Student s1; //creating an object of Student
S1.input();
s1.output();
getch()l
return 0;
}
OUTPUT:
Enter First number:5
Enter Second Number; 4
The numbers are: 5 , 4
Access modifiers are used to implement an important aspect of Object-Oriented Programming known
as Data Hiding.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members,
i.e., they set some restrictions on the class members so that they can’t be directly accessed by the outside
functions.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected
Note: If we do not specify any access modifiers for the members inside the class, then by default the
access modifier for the members will be Private
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/ friend class are allowed to access the private data members
of the class.
3. Protected: The protected access modifier is similar to the private access modifier in the sense that it
can’t be accessed outside of its class unless with the help of a 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.
Example:
class cs
{
Private:
int x;
public:
void input()
{
cout"Enter x";
cin>>x;
}
void output()
{
cout<<x;
}
};
int main()
{
cs obj;
obj.input();
obj.output();
return 0;
}
OUTPUT:
Enter x: 5
5
The scope resolution operator is used to reference the global variable or member function that is out of
scope. Therefore, we use the scope resolution operator to access the hidden variable or function of a
program.
The operator is represented as the double colon (::) symbol.
Example: Program to access the hidden value using the scope resolution (::) operator
#include <iostream.h>
#include <conio.h>
Example 2: Program to define the member function outside of the class using the scope resolution (::)
operator
class cs
{
Private:
int x;
public:
void input()
{
cout"Enter x";
cin>>x;
}
void output();
};
void cs : : output()
{
cout<<”The value of x is ”<<x;
}
int main()
{
cs obj;
obj.input();
obj.output();
return 0;
}
OUTPUT:
Enter x: 5
5
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is
created. It is used to initialize the data members of new objects generally. The constructor in C++ has the
same name as the class or structure. It constructs the values i.e. provides data for the object which is why
it is known as a constructor.
class ClassName
{
public:
ClassName(); // Constructor declaration
};
class ClassName
{
public:
ClassName()
{
ClassName::ClassName()
{
// Constructor definition outside the class
}
int main()
{
cs obj;
obj.output();
return 0;
}
class ClassName {
public:
ClassName(); // Default constructor declaration
};
class ClassName {
public:
ClassName(parameter1, parameter2, ...); // Parameterized constructor declaration
};
Example:
class cs
{
Private:
int a,b;
public:
cs()
{
a=0;
b=0
}
cs( int x, int y)
{
a=x;
b=y
}
void output()
{
cout<<”The value of a and b are ”<<a<<b;
}
};
int main()
{
cs obj;
cs obj1(10, 20);
obj.output();
obj1.output();
return 0;
}
OUTPUT:
The value of x and y are: 0, 0
The value of x and y are: 10, 20
A copy constructor is a type of constructor that initializes an object using another object of the same
class. In simple terms, a constructor which creates an object by initializing it with an object of the same
class, which has been created previously is known as a copy constructor
......
}
Example:
class cs
{
Private:
int a,b;
public:
cs( int x, int y)
{
a=x;
b=y
}
cs( cs & m)
{
a=a.m;
b=b.m
}
void output()
{
cout<<”The value of a and b are ”<<a<<b;
}
};
int main()
{
cs obj1(10, 20);
obj.output();
cs obj2(obj);
obj2.output();
return 0;
}
OUTPUT:
The value of x and y are: 10, 20
The value of x and y are: 10, 20
Destructors in C++
class cs
{
public:
cs ()
{
cout<<"Constructor Invoked"<<endl;
}
~ cs ()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
cs e1; //creating an object of cs
cs e2; //creating an object of cs
return 0;
}
OUTPUT:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be
accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword friend.
Syntax:
class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
};
NOTE:
In the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use either
the keyword friend or scope resolution operator.
Characteristics of a Friend function:
• The function is not in the scope of the class to which it has been declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name and dot membership
operator with the member name.
• It can be declared either in the private or the public part.
class cs
{
Private:
int a, b;
public:
void input()
{
cout"Enter a and b";
cin>>a>>b;
}
void output()
{
cout<<”The value of a and b are ”<<x<<y;
}
Friend void sum(cs & obj);
};
int main()
{
cs obj;
obj.input();
obj.output();
sum(obj); // calling of friend function
return 0;
}
OUTPUT:
Enter a and b: 5, 4
The value of a and b are: 5, 4
The sum of a and b is: 9
The syntax for defining the child class and parent class in all inheritance types in C++ is given below:
class parent_class
{
Syntax Description
• parent_class: Name of the base class or the parent class.
• child_class: Name of the derived class or the child class.
• visibility_mode: Type of the visibility mode (i.e., private, protected, and public) that specifies
how the data members of the child class inherit from the parent class.
Visibility modes:
• Public: When the member is declared as public, it is accessible to all the functions of the
program.
• Private: When the member is declared as private, it is accessible within the class only.
• Protected: When the member is declared as protected, it is accessible within its own class as well
as the class immediately derived from it.
Types Of Inheritance
• Single inheritance
• Multiple inheritance
• Hierarchical inheritance
• Multilevel inheritance
• Hybrid inheritance
1.Single Inheritance:
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.
Where 'A' is the base class, and 'B' is the derived class.
EXAMPLE:
class A
{
protected:
int a;
public:
void input_A()
{
cout"Enter a ";
cin>>a;
}
void output_A()
{
cout<<”The value of a is ”<<a;
}
};
class B: public A
{
private:
int b;
public:
void input_B()
{
cout"Enter b ";
cin>>b;
}
void output_B()
{
cout<<”The value of b is ”<<b;
}
};
int main()
{
B obj;
obj.input_A();
obj.output_A();
obj.input_B();
obj.output_B();
return 0;
}
OUTPUT:
Enter the value of a: 5
The value of a is : 5
Enter the value of b: 4
The value of b is : 4
2. Multilevel Inheritance:
EXAMPLE:
class A
{
protected:
int a;
public:
void input_A()
{
cout"Enter a ";
cin>>a;
}
void output_A()
{
cout<<”The value of a is ”<<a;
}
};
class B: public A
{
protected:
int b;
public:
void input_B()
{
cout"Enter b ";
cin>>b;
}
void output_B()
{
cout<<”The value of b is ”<<b;
}
};
class C: public B
{
private:
int c;
public:
void input_C()
{
cout"Enter c ";
cin>>c;
}
void output_C()
{
cout<<”The value of c is ”<<b;
}
Void add()
{
Int sum;
Sum= a+b+c;
Cout<<”The of a, b and c is ”<< sum;
};
int main()
{
C obj;
obj.input_A();
obj.output_A();
obj.input_B();
obj.output_B();
obj.input_C();
obj.output_C();
obj.sum();
return 0;
}
OUTPUT:
Enter the value of a: 5
The value of a is : 5
Enter the value of b: 4
The value of b is : 4
Enter the value of c: 3
The value of b is : 3
The sum of a, b and c is : 12
Multiple Inheritance
2. Multiple Inheritance:
Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit
properties or behaviour from multiple base classes. Therefore, we can say it is the process that enables a
derived class to acquire member functions, properties, characteristics from more than one base class.
In the above diagram, there are two-parent classes: Base Class 1 and Base Class 2, whereas there is only
one Child Class. The Child Class acquires all features from both Base class 1 and Base class 2.
Therefore, we termed the type of Inheritance as Multiple Inheritance.
class A
{
// code of class A
}
class B
{
// code of class B
}
class C: public A, public B (access modifier class_name)
{
// code of the derived class
}
EXAMPLE:
class A
{
protected:
int a;
public:
void input_A()
{
cout"Enter a ";
cin>>a;
}
void output_A()
{
cout<<”The value of a is ”<<a;
}
};
class B
{
protected:
int b;
public:
void input_B()
{
cout"Enter b ";
cin>>b;
}
void output_B()
{
cout<<”The value of b is ”<<b;
}
};
class C: public A, public B
{
private:
int c;
public:
void input_C()
{
cout"Enter c ";
cin>>c;
}
void output_C()
{
cout<<”The value of c is ”<<b;
}
Void add()
{
Int sum;
Sum= a+b+c;
Cout<<”The of a, b and c is ”<< sum;
};
int main()
{
C obj;
obj.input_A();
obj.output_A();
obj.input_B();
obj.output_B();
obj.input_C();
obj.output_C();
obj.sum();
return 0;
}
OUTPUT:
Enter the value of a: 5
The value of a is : 5
Enter the value of b: 4
The value of b is : 4
Enter the value of c: 3
The value of b is : 3
The sum of a, b and c is : 12
Hierarchical Inheritance:
As the name defines, it is the hierarchy of classes. There is a single base class and multiple derived
classes. Furthermore, the derived classes are also inherited by some other classes. Thus a tree-like
structure is formed of hierarchy.
Here class A is the base class. Class B and Class C are the derived classes of A.
Class D and Class E are derived classes of B. Class F and Class G are derived classes of C. Thus forming
the structure of hierarchical inheritance.
Syntax:
Class Parent
{
statement(s);
};
Class Derived1: public Parent
{
statement(s);
};
Class Derived2: public Parent
{
statement(s);
};
class newderived1: public Derived1
{
statement(s);
};
class newderived2: public Derived2
{
statement(s);
};
Here,
Class Parent is the base class and Derived1 and Derived2 are the class that inherit Parent class. Further,
newderived1 is the class that inherits Dervied1, and newderived2 is the class that inherits the Derived2
class. There can be any number of base classes that are inherited by n number of derived classes.
Example:
We are taking three class in our example:
Example:
class A
{
protected:
int a, b ;
public:
void input_A()
{
cout"Enter a and b ";
cin>>a>>b;
}
void output_A()
{
cout<<”The value of a and b are is ”<<a<<b;
}
};
Hybrid inheritance:
Combining various types of inheritance like multiple, simple, and hierarchical inheritance is known as
hybrid inheritance.
The diagram shows the hybrid inheritance that is a combination of single inheritance and multiple
inheritance.
Single inheritance - Class B inherits class A. Thus an example of single inheritance.
Multiple inheritance - Class D is inherited from multiple classes( B and C shown above D). Thus an
example of multiple inheritance.
Class A
{
statement(s)
}:
Class B: public A
{
statement(s);
};
Class C
{
statement(s);
};
Class D: public B, public C
{
statement(s);
};
Example:
class A
{
protected:
int a,
public:
void input_A()
{
cout"Enter a ";
cin>>a;
}
void output_A()
{
cout<<”The value of a and b are is ”<<a<<b;
}
};
};
class C :
{
protected:
int c,
public:
void input_C()
{
cout"Enter c ";
cin>>c;
}
void output_C()
{
cout<<”The value of c is ”<<c;
}
};
class D :
{
protected:
int d,
public:
void input_D()
{
cout"Enter d ";
cin>>d;
}
void output_D()
{
cout<<”The value of d is ”<<d;
}
Void sum()
{
Int sum;
Sum=a+b+c+d;
Cout<<”The sum is ”<<sum;
};
int main()
{
D obj;
obj. input_A();
obj. output_A();
obj. input_B();
obj. outputB();
obj. input_C();
obj. output_C();
obj. inputD();
obj. output_D();
obj. sum();
return 0;
}
Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom, mother
or daughter in a home and customer in a market. Here, a single person is behaving differently according
to the situations.
Types of Polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
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. In simple terms, it is a
feature of object-oriented programming providing many functions that have the same name but distinct
parameters when numerous tasks are listed under one function name.
Example:
class CS {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
int main()
{
CS obj1;
obj1.func(7);
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Explanation: In the above example, a single function named function func() acts differently in three
different situations, which is a property of polymorphism.
B. Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. 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.
Example:
#include <iostream.h>
#include <conio.h>
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator is used to add
two numbers (integers or floating point numbers), but here the operator is made to perform the addition of
two imaginary or complex numbers.
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.
B. Virtual Function:
A virtual function is a member function that is declared in the base class using the keyword virtual and is
re-defined (Overridden) in the derived class.
Example:
// C++ program for virtual function overriding
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
void show()
{ cout << "show base class" << endl;
}
};
void print()
{ cout << "print derived class" << endl;
}
void show()
{
cout << "show derived class" << endl;
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
return 0;
}
Output
print derived class
show base class
Data structures are the fundamental building blocks of computer programming. They define how data is
organized, stored, and manipulated within a program.
Understanding data structures is very important for developing efficient and effective algorithms.
Need of Data Structure:
Data structures provide an easy way of organizing, retrieving, managing, and storing data.
2. Linked Lists:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a
contiguous location; the elements are linked using pointers.
3. Stack:
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all insertion and deletion
are permitted at only one end of the list.
Stack Operations:
• push(): When this operation is performed, an element is inserted into the stack.
• pop(): When this operation is performed, an element is removed from the top of the stack and is
returned.
• top(): This operation will return the last inserted element that is at the top without removing it.
• size(): This operation will return the size of the stack i.e. the total number of elements present in
the stack.
• isEmpty(): This operation indicates whether the stack is empty or not.
4. Queue:
Like Stack, Queue is a linear structure which follows a particular order in which the operations are
performed. The order is First In First Out (FIFO). In the queue, items are inserted at one end and deleted
from the other end. A good example of the queue is any queue of consumers for a resource where the
consumer that came first is served first. The difference between stacks and queues is in removing. In a
stack we remove the item the most recently added; in a queue, we remove the item the least recently
added.
Queue Operations:
• Enqueue(): Adds (or stores) an element to the end of the queue..
• Dequeue(): Removal of elements from the queue.
• Peek() or front(): Acquires the data element available at the front node of the queue without
deleting it.
• rear(): This operation returns the element at the rear end without removing it.
• isFull(): Validates if the queue is full.
• isNull(): Checks if the queue is empty.
5. Binary Tree:
Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data
structures. A binary tree is a tree data structure in which each node has at most two children, which are
referred to as the left child and the right child. It is implemented mainly using Links.
A Binary Tree is represented by a pointer to the topmost node in the tree. If the tree is empty, then the
value of root is NULL.
7. Heap:
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps
can be of two types:
• Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys
present at all of its children. The same property must be recursively true for all sub-trees in that
Binary Tree.
• Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys
present at all of its children. The same property must be recursively true for all sub-trees in that
Binary Tree.
Hashing is an important Data Structure which is designed to use a special function called the Hash
function which is used to map a given value with a particular key for faster access of elements. The
efficiency of mapping depends on the efficiency of the hash function used.
Let a hash function H(x) maps the value x at the index x%10 in an Array. For example, if the list of
values is [11, 12, 13, 14, 15] it will be stored at positions {1, 2, 3, 4, 5} in the array or Hash table
respectively.
9. Matrix:
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to
enclose the elements of a matrix in parentheses or brackets.
A matrix with 9 elements is shown below.
Matrix
10. Tree:
Tree Data Structure is a non-linear data structure in which a collection of elements known as nodes are
connected to each other via edges such that there exists exactly one path between any two nodes.
Trie Data Structure
11. Graph:
Graph is a data structure that consists of a collection of nodes (vertices) connected by edges. Graphs are
used to represent relationships between objects and are widely used in computer science, mathematics,
and other fields. Graphs can be used to model a wide variety of real-world systems, such as social
networks, transportation networks, and computer networks.