0% found this document useful (0 votes)
24 views48 pages

C++ Booster

The document provides an overview of Object-Oriented Programming (OOP) in C++, detailing its key principles such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It explains how classes serve as blueprints for objects, encapsulating data and functions, while inheritance allows for code reuse and hierarchical classification. Additionally, it discusses polymorphism as the ability for functions to operate in multiple forms, enhancing flexibility and readability in code.

Uploaded by

Ritx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views48 pages

C++ Booster

The document provides an overview of Object-Oriented Programming (OOP) in C++, detailing its key principles such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It explains how classes serve as blueprints for objects, encapsulating data and functions, while inheritance allows for code reuse and hierarchical classification. Additionally, it discusses polymorphism as the ability for functions to operate in multiple forms, enhancing flexibility and readability in code.

Uploaded by

Ritx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

OOP ***:

As the name suggests uses objects in programming. Object-oriented programming aims to


implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The
main aim of OOP is to bind together the data and the functions that operate on them so that no
other part of the code can access this data except that function.

The key principles of OOP in C++ are Encapsulation, Abstraction, Inheritance,


and Polymorphism.,calss, object.

1.class : Collection of objects is called class.A class is like a blueprint for an object.
It 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 behavior of the
objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc and member functions
can apply brakes, increase speed, etc.
 Class has a semicolan in the end(;).

E.g. class Car {

public:

// class data

string brand, model;

int mileage = 0;

// class function

void drive(int distance) {

mileage += distance;

};

In the above code, we have used the class keyword to create a class named Car . Here,

 brand and model are class attributes used to store data


 drive() is a class function used to perform some operation
The public keyword represents an access modifier. And by default it will set to private.

2. object : An object is an instance of a class. When you create an object, you are allocating
memory to store its attributes and methods.
For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
the basic syntax for creating objects is:

Class_Name object_name;

E.g. Car suv;

Car sedan;

Class and object in c++ :

#include <iostream>
using namespace std;

class Car {
public:

// class data
string brand, model;
int mileage = 0;

// class function to drive the car


void drive(int distance) {
mileage += distance;
}

// class function to print variables


void show_data() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Distance driven: " << mileage << " miles" << endl;
}
};

int main() {

// create an object of Car class


Car my_car;

// initialize variables of my_car


my_car.brand = "Honda";
my_car.model = "Accord";
my_car.drive(50);

// display object variables


my_car.show_data();

return 0;
}
OutPut :
Brand: Honda

Model: Accord

Distance driven: 50 miles

3. C++ Encapsulation
In C++, object-oriented programming allows us to bundle together data members (such as
variables, arrays, etc.) and its related functions into a single entity. This programming feature is
known as encapsulation.

#include <iostream>
using namespace std;
Encapsulation also leads to data abstraction class temp{
or data hiding. Using encapsulation also hides int a;
int b;
the data public:
int solve(int input){
Encapsulation ensures that only member functions of a=input;
b=a/2;
a class can access its data, which results in data return b;
}
hiding. };

In C++, we hide data using int main() {


int n;
the private and protected keywords. In contrast, cout<<"enter a number : ";
cin>>n;
using the public keyword for certain class members
temp half;
In Example 1, we bundled together the related variables brand , model and mileage with theint ans=half.solve(n);
function show_data() into a class named Car . cout<<ans<<endl;

}
class Car { Output : enter a number : 4
2
public:

// class data

string brand;

string model;

int mileage = 0;

// class function

void show_data() {

// code

};

4. C++ Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. 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 accelerator will increase the speed of
the car or applying brakes will stop the car but he does not know how on pressing the
accelerator the speed is actually increasing, he does not know about the inner mechanism of the
car or the implementation of an 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.

Note: Abstraction is not the same as data hiding. Abstraction is showing only the relevant information, while
data hiding is restricting access to data members (variables, arrays, structures, etc.) so that they cannot be
accessed from outside the class.

5. C++ Inheritance :
Inheritance in C++ allows us to create a new class (derived class) from an existing class (base class).The derived

class inherits features from the base class and can have additional features of its own also.

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 a sub-class is called Base Class or Superclass.
 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.

#include <iostream> A derived class inherits all base class methods with the
using namespace std; following exceptions −

// base class  Constructors, destructors and copy constructors of the


class Vehicle { base class.
public:  Overloaded operators of the base class.
 The friend functions of the base class.
string brand;
Q. Uses of inhertiance

1. Code Reusability

Inheritance allows new classes (derived classes) to


reuse the code from existing classes (base classes)
without having to rewrite it. This reduces redundancy
and makes the code more concise and easier to
maintain.

5. Improved Maintainability

Since common functionality is defined in the base


class, any changes to shared code only need to be made
in one place. This makes the system easier to maintain,
as fixing bugs or adding features in the base class
propagates to all derived classes.

7. Reduced Complexity

Inheritance helps break down complex systems into


more manageable components. By building upon
existing classes, you can create smaller, more
understandable pieces that integrate seamlessly into the
larger system.
Types of inhertitance 6. Hierarchical Classification
 Concept: Inheritance allows classes to be organized in a
hierarchical manner, which simplifies classification and
makes code more logical and intuitive.

Single Inheritance in C++:

Single inheritance is one of the simplest inheritance among other types of inheritance in C+
+, in which the child class is derived only from the single parent class.
#include <iostream>
*take diagram from above using namespace std;

// Base class
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
class parent{

};
class child : access-specifire
parent{

2 . Multiple Inheritance in C++

Multiple inheritances are another type of inheritance in c++ in which the child class
inherits its properties from more than one base class. This means the child class is
inherited from multiple parent classes, so the child class can derive the combined
features of all these classes. The child class accesses all base class data members
according to the visibility mode used.
#include <iostream>
using namespace std;

// Base class 1
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};

// Base class 2
class Vehicle {
public:
void drive() {
cout << "This vehicle can drive." << endl;
// synttax
}
class A{ };

}; // Derived class inheriting from both Animal and Vehicle


class B{ class Car : public Animal, public Vehicle {
public:
}; void honk() {
class C: visibility_mode_1 A, visibility_mode_2 B cout << "This car honks." << endl;
{ }
};
}; int main() {
OutPut :
This animal eats food.
This veicale aca drive
This car horns.

3. Multilevel Inheritance

n this type of inheritance, a derived class is created from another derived class and that derived
class can be derived from a base class or any other derived class. There can be any number of
levels.

// C++ program to implement Multilevel Inheritance


#include <iostream>
using namespace std;

// base class
class C
{ class Vehicle {
... .. ... public:
}; Vehicle() { cout << "This is a Vehicle\n"; }
class B : public C };
{
... .. ... // first sub_class derived from class vehicle
}; class fourWheeler : public Vehicle {
class A: public B public:
{
fourWheeler() { cout << "4 Wheeler Vehicles\n"; }
... ... ...
};
};

// sub class derived from the derived base class fourWheeler


class Car : public fourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

OutPut :
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car
4. 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.

#include <iostream>
class A using namespace std;
{
// base class
// body of the class A. class Vehicle {
} public:
class B : public A Vehicle() { cout << "This is a Vehicle\n"; }
{ }; OutPut :
// body of class B. // first sub class This is a Vehicle
} class Car : public Vehicle { This Vehicle is Car
class C : public A public:
{ Car() { cout << "This Vehicle is Car\n"; } This is a Vehicle
// body of class C. };
} This Vehicle is
// second sub class Bus
class D : public A class Bus : public Vehicle {
{ public:
// body of class D. Bus() { cout << "This Vehicle is Bus\n"; }
} };

// main function
int main()
{
5. Hybrid Inheritance // Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Hybrid Inheritance is implemented by combining
Bus obj2; more than one type of inheritance. For
example: Combining Hierarchical inheritance
return 0; and Multiple Inheritance will create hybrid
}
inheritance in C++
There is no particular syntax of hybrid inheritance. We can just combine two of the above
inheritance types.

class F // C++ program to illustrate the implementation of Hybrid


{ Inheritance
... .. ... #include <iostream>
}
using namespace std;
class G
{
... .. ... // base class
} class Vehicle {
class B : public F public:
{ Vehicle() { cout << "This is a Vehicle\n"; }
... .. ... };
}
class E : public F, public // base class
G class Fare { OutPut :
{ This is a Vehicle
public:
... .. ... Fare of Vehicle
} Fare() { cout << "Fare of Vehicle\n"; }
class A : public B { }; This Vehicle is a Bus with
Fare
... .. ...
} // first sub class
class C : public B { class Car : public Vehicle {
... .. ... public:
} Car() { cout << "This Vehical is a Car\n"; }
};

// second sub class


class Bus : public Vehicle, public Fare {
public:
Bus() { cout << "This Vehicle is a Bus with Fare\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
6. 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 real-life example of
polymorphism is a person who at the same time can have different characteristics. A man 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

We can implement polymorphism in C++ using the following ways:

*Compile Time Polymorphism

Compile-time polymorphism is done by overloading an operator or function. It is also known as "static" or "early binding".

Why is it called compile-time polymorphism?

Overloaded functions are called by comparing the data types and number of parameters. This type of information is
available to the compiler at the compile time. Thus, the suitable function to be called will be chosen by the C++
compiler at compilation time.

->Function Overloading

When we have two functions with the same name but different parameters, different functions are called depending on
the number and data types of parameters. This is known as function overloading

Function Overloading can be achieved through the following two cases:

 The names of the functions and return types are the same but differ in the type of arguments.
 The name of the functions and return types are the same, but they differ in the number of arguments.

Let's understand with an example :

#include <bits/stdc++.h> Advantages of function overloading are as follows:


using namespace std;
class Temp  The main advantage of function overloading is that it
{ improves code readability and allows code reusability.
private:  The use of function overloading is to save memory space,
int x = 10; consistency, and readability.
double x1 = 10.1;  It speeds up the execution of the program
public:  Code maintenance also becomes easy.
void add(int y)  Function overloading brings flexibility to code.
{  The function can perform different operations and hence
cout << "Value of x + y is: " << x + y << endl; it eliminates the use of different function names for the
} same kind of operations.
// Differ in the type of argument.
void add(double d)
{
cout << "Value of x1 + d is: " << x1 + d << endl;
}
// Differ in the number of arguments.
void add(int y, int z)
{
cout << "Value of x + y + z is: " << x + y + z << endl;
}
};
OutPyut:
Value of x + y is: 20
Value of x1 + d is: 21.2
Value of x + y + z is: 35

->Q. 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.
Below is the C++ program to demonstrate operator overloading:

#include <iostream>  Operator overloading is a compile-time polymorphism. It is


using namespace std; an idea of giving special meaning to an existing operator in
C++ without changing its original meaning
 Programmers can define custom behaviors for operators like +,
class Complex { -, or < for user-defined classes. For example, the + operator can
private: be used to add two numbers or two words when used with
int real, imag; strings

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; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}

Output : 12 Polymorphism
*Runtime + i9
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.

#include <iostream>
using namespace std;

class Parent {
public:
void GeeksforGeeks_Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void GeeksforGeeks_Print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child Child_Derived;
Child_Derived.GeeksforGeeks_Print();
return 0;
}

Output : Derived function


Advantage of OOP

 Modularity: OOP divides complex systems into smaller components, making the codebase easier to comprehend, create, and
maintain.
 Reusability: Inheritance allows code reuse, improving code quality and saving time.
 Encapsulation: Protects data integrity and privacy by restricting direct access and allowing controlled access through methods.
 Flexibility and Scalability: OOP enables easy addition and modification of features without impacting the entire codebase.
 Code Organization: OOP promotes a structured approach, enhancing collaboration and code readability.
 Code Maintenance: Changes and bug fixes can be made to specific objects or classes without affecting other parts of the
system, reducing errors and improving debugging.
 Code Reusability: OOP encourages the development of reusable code elements, saving time and improving system reliability.
 Better Problem Solving: OOP models real-world systems, allowing developers to create intuitive solutions that closely mimic
real-world circumstances.

Friend function: A friend function of a class is defined outside that class scope but it has the right to
access all private and protected members of the class. Even though the prototypes for friend functions appear in
the class definition, friends are not member functions.

A friend can be a function, function template, member function, or a class or class template, in which case the
entire class and all of its members are friends.

A friend function can access the private and protected data of a class. We declare a friend function
using the friend keyword inside the body of the class.

Characteristics of Friend function

Some characteristics / features of friend function in C++:

 A global function or a member function of another class, both can be declared as a friend function.
 A friend function in C++ should not be in the scope of the class of which it is supposed to be the friend.
This means that the function which is declared as a friend should not be a member of the same class.
 A friend function in C++ can be declared anywhere in the class, that is, in the public section or the private
section of the class.
 The friend function in C++ can be called (invoked) just like a normal function using any instance of any
class (object).
 A friend function in C++ cannot directly access the protected or private data members of the class. It is
required to use an object (instance of that class) and then use the dot operator (.) to access the data
members.
 Friend functionality in C++ is not restricted to only one class. That is, it can be a friend to many classes.

 Friend functions in C++ can use objects (instance of a class) as arguments.

Syntax : // C++ program to demonstrate the working of friend function

class className {
#include <iostream>
using namespace std;
... .. ...
class Distance {
friend returnType functionName(arguments); private:
int meter;
... .. ...

// friend function
}
friend int addFive(Distance);

public:
Features of Friend Distance() : meter(0) {}

Functions };

 A friend function does not belong to the // friend function definition


class for which it was designated as a int addFive(Distance d) {
friend.
 A friend function in C++ cannot directly //accessing private members from the friend function
access the protected or private data d.meter += 5;
members of the class; it is required to return d.meter;
make use of an object (instance of that }
class) and then use the dot operator (.) to
access the data members. int main() {
 The friend function permits a non-member
Distance D;
function of a class to share confidential
cout << "Distance: " << addFive(D);
class information.
return 0;
The friend function
Advantages enables Functions:
of Friend
additional functionality that is not usually }
OUtPut: Distnace : 5
1.Access to Private and Protected Data:

1. Friend functions can access private and protected members of the class, which would otherwise be inaccessible from
outside the class.
2. This allows them to perform operations that require more intimate knowledge of the class, such as arithmetic on data
members.

2. Implementation of Non-Member Functions:


You can use friend functions to implement operations on objects that are not necessarily member functions, allowing for
more flexibility in design. For example, you could use a friend function to define an overloaded operator that requires
access to the internal data of the class.

3. Improves Encapsulation in Certain Cases:

If you need to allow some non-member functions access to a class’s internals without exposing all the internal details (like
using getter and setter methods), a friend function can provide a controlled, secure way of doing this.

4. Overloading Operators:
Friend functions are commonly used for overloading operators like +, <<, >>, and others that require accessto private
members to implement meaningful behavior for non-member operations.

Disadvantages of Friend Functions:

1. Breaks Encapsulation:

1. Friend functions can break the principle of encapsulation because they have direct access to the private and protected
members of the class. This means that they could alter the internal state of an object in ways that the class’s public
interface does not intend or control.

2.Maintainability Issues:

1. As friend functions break the object-oriented principle of data hiding, the code can become harder to maintain. If many
functions are declared as friends, it can become more difficult to track which parts of the code can manipulate the
internal state of the class.

3 Limited Flexibility:

1. The relationship between a class and its friend functions is fixed at compile-time. You cannot easily change a friend
function once it's declared. This is less flexible compared to member functions, which are tied to the object itself.

4 Increased Complexity:

1. Friend functions add another layer of complexity to the class interface. Developers who interact with the class may not
immediately know which functions have access to its private data, making the system harder to understand and
extend.

** C++ Program to Calculate Factorial Using Friend


Function:

Q example of abstarction :

#include <iostream>

using namespace std;

class implementAbstraction {
Output a=10
B 20
private:

int a, b;

public:

// method to set values of // private members

void set(int x, int y){

a = x;

b = y;

}
void display() {

cout << "a = " << a << endl;

cout << "b = " << b << endl;

};

int main(){

implementAbstraction obj;

obj.set(10, 20);

obj.display();

return 0;

}}

Q. C++ token In C++, tokens are the smallest building block of programs that the compiler
understands(means they has speaail meaning for complier). Types of tokens :
keyword,constant,string,operator , special symbol etc.

Q.C++ Bitwise Operators


Bitwise Operators are the operators that are used to perform operations on the bit level on the
integers. While performing this operation integers are considered as sequences of binary digits.
In C++, we have various types of Bitwise Operators.
1. Bitwise AND (&)
2. Bitwise OR (|)
3. Bitwise XOR (^)
4. Bitwise NOT (~)
5. Left Shift (<<)
6. Right Shift (>>)

Q .This Pointer

In C++ programming, this is a keyword that refers to the current object of the class. There can be 3
main usage of this keyword in C++.

In C++, the “this” pointer is a special


#include <iostream> keyword that can be used inside a
member function of a class to refer to the
class MyClass {
Q.Inline function
C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the
compiler places a copy of the code of that function at each point where the function is called at compile
time.

Any change to an inline function could require all clients of the function to be recompiled because compiler
would need to replace all the code once again otherwise it will continue with old functionality.

Rules for inline function:


The compiler may not perform inlining in such circumstances as:
1. If a function contains a loop. (for, while and do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a
function body.
5. If a function contains a switch or goto statement.
Inline functions Advantages:
1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when a function is called.
3. It also saves the overhead of a return call from a function.
4. When you inline a function, you may enable the compiler to perform context-specific
optimization on the body of the function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of the calling
context and the called context.
5. An inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function called preamble and return.

Syntax:
inline return-type function-name(parameters)
{
// function code
}

#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
Q. Multiple inheritance with with example

Q. Template
The templates are one of the most powerful and widely used methods added to C++, template allowing us to write
generic programs. It allow us to define generic functions and classes. Generic programming is a technique where
generic types are used as parameters which can work any data types, means the programmer does not need to write
the same function or method for different data types.

/* a "template" is a blueprint for creating generic functions or classes that can work with different data types,
essentially allowing you to write one piece of code that can operate on integers, floats, strings, or any other type
you specify at compile time, without needing to rewrite the code for each data type separately; this is called
"generic programming" and is a powerful way to reuse code and improve maintainability */

Benefits:
 Code reuse: Write once, use with various data types
 Folow DRY principal
 Reduce code complecity
 Flexibility: Adapt to different data types without modifying the core logic
 Efficiency: Compiler optimization can often produce highly efficient code for each specific typ

Tempate are categorie : 1. Funtion tempplate 2. class tempaplet

1.Function Templates
We write a generic function that can be used for different data types. Examples of function
templates are sort(), max(), min(), printArray().

#include <iostream> Syntax of Function Template


using namespace std;
template < typename Ttype>
// One function works for all data types. This would work ret_type func_name(parameter_list)
template <typename T>
{
T myMax(T x, T y){
return (x > y) ? x : y; Output:
// body of function.
} 7 }

7
int main(){ g

// Call myMax for int


cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;

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. Can be useful for classes like LinkedList,
BinaryTree, Stack, Queue, Array, etc.

Synatx
template<class Ttype> #include <iostream>
class class_name using namespace std;
{ template<class T>
. class A {
. public:
} T num1 = 5;
T num2 = 6;
void add() {
std::cout << "Addition of num1 and num2 : " <<
num1+num2<<std::endl;
}

};

int main()
{
A<int> d;
d.add();
return 0;
}
Output :
Addition of num1 and num2 : 11

R. Oop vs pop
Struct
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.
The ‘struct’ keyword is used to create a structure.

#include <iostream>
using namespace std; Output :
X=0 , y=1
struct Point { X=0 , y =20
int x = 0; // It is Considered as Default Arguments and no Error is Raised
int y = 1;
};

int main()
{
struct Point p1;

// Accessing members of point p1


// No value is Initialized then the default value is considered. ie x=0 and y=1;
cout << "x = " << p1.x << ", y = " << p1.y<<endl;
Structures in C++ can contain two types of members:
// Initializing the value of y = 20;
 Data Member: These members are normal C++ p1.y = 20; variables. We can create a
cout << "x = " << p1.x << ", y = " << p1.y;
structure with variables of different data types in0; C++.
return
}
 Member Functions: These members are normal C++ functions. Along with
variables, we can also include functions inside a structure declaration.

*How struct are different from class in c++

Members of a class are private by default and members of a structure are public by default.
User defind data types :

User-Defined DataTypes
The data types that are defined by the user are called the derived datatype or user-defined derived data type. These types
include:

 Class
 Structure
 Union
 Enumeration
 Typedef

1. class : exaplain at up page


2. Struct : exaplain ata upnapage

3. Union : Like Structures , Union a user-defined data type. In union, all members share the same memory location. For
example in the following C program, both x and y share the same location. If we change x, we can see the changes being
reflected in y.

#include <iostream>
using namespace std;
Syntax
// Declaration of union is same as the structures
union test { Union_Name
int x, y; {
}; // Declaration of data members
}; union
int main()
{
// A union variable t
union test t;

// t.y also gets value 2 Output:


t.x = 2;
After making x = 2:
cout << "After making x = 2:" << endl
<< "x = " << t.x << ", y = " << t.y << endl; x = 2, y = 2

// t.x is also updated to 10 After making Y = 10:


t.y = 10;
x = 10, y = 10
cout << "After making Y = 10:" << endl
<< "x = " << t.x << ", y = " << t.y << endl;

4. Enumeration
return 0;
}
Enumeration (or enum) is a user-defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.

Syntax
enum nameOfEnum {
varName1 = 1, varName2 = 0
};

// Program to demonstrate working


// of enum in C++

#include <iostream>
using namespace std;

enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };

int main()
{
enum week day;

day = Wed;

cout << day;

return 0;
}
Output : 2

Q. how polymorphism achived through overlaoding in c++ ? expalin

Ans. At page 10

R. Conditonal statement in c++

Ans : theroy by own!!!!

-> switch -> ternary


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

int main()
int main()
-> If- else-if { {
-> if - else #include <bits/stdc++.h>
#include <bits/stdc++.h> using namespace std;
int x = 2; int x = 10;
using namespace std;
int main() switch (x) {
string result
{ case 1:
int main() int x = 0; = (x > 0) ? "x is
cout << "x is one";
{ if (x > 0) {
break; positive" : "x is not
int x = -10; cout << "x is positive";
if (x > 0) { } case 2: positive";
else if (x < 0) { cout << "x is two"; cout << result;
cout << "x is positive";
cout << "x is not positive"; break;
} } default:
else { else { return 0;
cout << "x is neither one nor
cout << "x is not positive"; cout << "x is not zero";
} }
two"; }
}
return 0;
return 0; Output : x is positive
} return 0;
Q. looping stament
} in c++? Output :; x is not zero }
Output: x is not positive
Output : x is two

R. Loop, the statement needs to be written only once and the loop will be executed 10 times as
shown below. In computer programming, a loop is a sequence of instructions that is repeated until a
-> If
certain condition is reached.The C++ Course includes comprehensive lessons on the different
#include <bits/stdc++.h>
types
using ofnamespace
loopsstd;available in C++, ensuring you can implement them effectively in your programs.
int main()
{

int x = 10;
For Loop- While Loop- Do-while loop
if (x > 0) { While studying for loop we have seen that the number In Do-while loops also the loop execution is
A For loop isis a
cout<<"x repetition control structure that allows
positive"; of iterations is known beforehand, i.e. the number of terminated on the basis of test conditions. The
us}to write a loop that is executed a specific number times the loop body is needed to be executed is known main difference between a do-while loop and the
of times. The loop enables us to perform n number of to us. while loops are used in situations where we do
while loop is in the do-while loop the condition is
steps together in one line. not know the exact number of iterations of the
return 0; loop beforehand. The loop execution is terminated on tested at the end of the loop body, i.e do-while loop
Syntax:
} the basis of the test conditions. is exit controlled whereas the other two loops are
Q. Virtual function :

o A C++ virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the virtual keyword.

o A 'virtual' is a keyword preceding the normal declaration of a function.


 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.

Rules of Virtual Function Syntax :
virtual return_type function_name(parameters) {
o Virtual functions must be members of some class. // function body
o Virtual functions cannot be static members. }
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes must be identical. If the
two functions with the same name but different prototypes, C++ will consider them as the overloaded
functions.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.

#include <iostream>

using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
R. Pure virtual function :
A pure virtual function in c++ is a virtual function for which we do not have an implementation.
We do not write any functionality in it.A pure virtual function is declared by assigning a zero (0) in
its declaration.

Any class containing one or more pure virtual functions can not be used to define any object. So
the classs which have pure virtual function are known as abstract classes.

Pure virtuial function are imlemented in child class.

Pure vitu;a function guiuves 100% abstarction .

Syntax
virtual <function_type> <function_name>() = 0;

Characteristics of Pure Virtual Function in C++


The following are the characteristics of a pure virtual function in c++:

 A pure virtual function does not do anything, which means it is used to resemble the template, and
the derived classes implement the function.
 It is an empty function because it does not contain any definition of the functionality of its base class
in it.
 Derived class can call a member or pure virtual function in c++.
 The user in the derived class redefines a pure virtual function.

 Any class in c++ that contains a pure virtual function does not allow the user to create the object of
that class.

// C++ program to calculate the area of a square and a circle

#include <iostream>
using namespace std;

// Abstract class
class Shape {
protected:
float dimension;

public:
void getDimension() {
cin >> dimension;
}
Enter the length of the square: 4

Area of square: 16

Enter radius of the circle: 5

Area of circle: 78.5

Q. Virtaul and pure virtual finction

<- Q mca

Exception handling

An exception is occurs during the execution of a program that disrupts the normal flow of instructions.
Exceptions are typically used to indicate an error has occurred and to transfer control to a specific location in
the code where the error can be handled.

E.g - IOexception, calssnot foundexception, divodeby zero exception.

The main benefit of using exceptions is that it allows you to separate the error handling code from the
normal code, making it more readable and maintainable. The exception-handling code can be kept
separate from the rest of the code and can be reused easily across the program.

In C++, exception handling is a mechanism to handle runtime errors. It allows the program to transfer
control to a special block of code, called an exception handler when an exceptional condition (such as a
divide-by-zero error) occurs. This allows the program to recover gracefully from the error rather than
terminating abruptly

-> C++ exception handling is built upon three keywords: try, catch, and throw.

1. try
The try block contains the code that may throw an exception. If an exception is thrown within the try block,
the control is transferred to the corresponding catch block.

2. catch
The catch block contains the code that will handle the exception. Each catch block is associated with a
specific exception type, and the catch block that corresponds to the type of exception that was thrown will
be executed. If the catch block does not have a matching exception type, the exception is passed to the next
catch block.

3 throw
The throw keyword is used to throw an exception. The expression that follows the throw keyword is used to
create the exception object. The exception object is then passed to the nearest catch block that can handle
it.

Types of exceptions
1. Standard exceptions
These exceptions are a part of the C++ Standard Library and are defined in the <exception> header. They are intended to
provide a standard set of exception classes for use in C++ programs and are designed to represent a wide range of error
conditions that may occur during the execution of a program. The standard exceptions include std::logic_error, which
represents errors resulting from an application’s logic (e.g., an invalid argument passed to a function), and
std::runtime_error, which represents errors that occur due to external factors (e.g., a file not found).

2. Derived exceptions
These exceptions are derived from standard exceptions. They provide a more specific indication of the type of error. For
example, std::out_of_range is derived from std::logic_error and is used to indicate that an index or a value is out of the
acceptable range for a container or an algorithm.

3. User-defined exceptions
The user in the application code defines these exceptions. They can be derived from standard exceptions or a user-defined
base class. User-defined exceptions allow the programmer to indicate errors specific to the application rather than relying on
standard exceptions.

Exapple :

#include <iostream>
using namespace std;

int main() {
try {
std::cout<<"Please enter the age"<<std::endl;
int age=0;
std::cin>>age;
if (age<0 || age>100){
throw (age);
}
}
catch (int e) {
cout << "Access denied - You must enter a valid age.\n";
}
return 0;
}

Output:
Please enter the age
122
Access denied- You must not enter a valid value.
* program to divide by zero exception handling

#include <iostream>
#include <stdexcept>
using namespace std;//handling divide by zero

float Division(float num, float den){


if (den == 0) {
throw runtime_error("Math error: Attempted to divide by Zero\n");
}
return (num / den);
}
int main(){
float numerator, denominator, result;
numerator = 12.5;
denominator = 0;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
}
catch (runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}}

Output :
Exception occurred
Math error: Attempted to divide by Zero

Type conversion :(exaplin type acasting ?(mca/bca))


Type conversion is essential for managing different data types in C++. A type cast is basically a
conversion from one type to another. There are two types of type conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.

 All the data types of the variables are upgraded to the data type of the variable with largest
data type
// An example of implicit conversion
x = 107
#include <iostream>
y = a
using namespace std;
z = 108
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


2. Explicit Type Conversion : This process is also called type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type. In C++, it can be
done by two ways:
 Converting by assignment: This is done by explicitly defining the required type in front of
the expression in parenthesis. This can be also considered as forceful casting.

Syntax: (type) expression

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to


int
int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Outpuy : sum = 2

Ternary operator :
n C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional
statements. It can be used as an inline conditional statement in place of if-else to execute some
conditional code.

Syntax of Ternary Operator ( ? : )


The syntax of the ternary (or conditional) operator is:
expression ? statement_1 : statement_2;

 expression: Condition to be evaluated.


 statement_1: Statement that will be executed if the expression evaluates to true.
 statement_2: Code to be executed if the expression evaluates to false.
#include <iostream>
using namespace std; Outputr
int main() {
Num - Test = 10
// creating a variable
int num, test = 40;

// assigning the value of num based on the value of test


// variable
num = test < 10 ? 10 : test + 10;

printf("Num - Test = %d", num - test);

return 0;
}
Member function

A Member function is a function that is declared as a member of a class.

Member functions are the functions, which have their declaration inside the class
definition and works on the data members of the class. The definition of member
functions can be inside or outside the definition of class.

If the member function is defined inside the class definition it can be defined directly,
but if its defined outside the class, then we have to use the scope
resolution :: operator along with class name alng with function name.

It operates on any object of the class of which it is a member, and has access to all the members of a class
for that object.

Exapmle

lass Cube{

class Cube{
public:

public:
int side;

int side; int getVolume();

int getVolume(){ }

return side*side*side; // member function defined outside class definition


//returns volume of cube
int Cube :: getVolume(){
}};
return side*side*side;

Data member a data member is a variable that is declared within a class or struct. It represents the
attributes or properties of the objects created from that class.
int main()
{
Cube C1;
Expression : C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
}
Expression is the combination of the constants, variables, and operators, which are arranged
according to the syntax of C++ language and, after computation, return some values that may be
a boolean, an integer, or any other data type of C++ Outpur : volume of cune c1 is : 16

A logical expression is a statement that can be either true or false. For example, "a < b" is a
logical expression that can be true or false depending on the values of a and b

In C++ programming languages, logical operators are symbols that allow you to combine or
modify conditions to make logical evaluations. They are used to perform logical operations on
boolean values (true or false).
In C++, there are three logical operators:
1. Logical AND ( && ) Operator
2. Logical OR ( || ) Operator
3. Logical NOT ( ! ) Operator

1. Logical AND Operator ( && )


The C++ logical AND operator (&&) is a binary operator that returns true if both of its
operands are true. Otherwise, it returns false. Here’s the truth table for the AND operator:
// C++ Program to illustrate the logical AND Operator
#include <iostream>
using namespace std;

int main() {
// initialize variables
int age = 25;
bool isStudent = true;

// Using AND operator in if condition


if (age > 18 && isStudent) {
cout << "You are eligible for a student discount."
<< endl;
}
else {
cout << "You are not eligible for a student "
"discount."
<< endl;
return 0;
}
}
2. Logical OR Operator ( || )
The C++ logical OR operator ( || ) is a binary operator that returns true if at least one of its
operands is true. It returns false only when both operands are false. Here’s the truth table for
the OR operator:
#include <iostream>
using namespace std;

int main() {

int num = 7;

// using logical or for conditional statement


if (num <= 0 || num >= 10) {
cout
<< "The number is outside the range of 0 to 10."
<< endl;
}
else {
cout << "The number is between 0 to 10." << endl;
}

return 0;
}

3. Logical NOT Operator ( ! )


The C++ logical NOT operator ( ! ) is a unary operator that is used to negate the value of a
condition. It returns true if the condition is false, and false if the condition is true. Here’s the
truth table for the NOT operator:
// C++ program to illustrate the logical not operator
#include <iostream>
using namespace std;

int main() {

bool isLoggedIn = false;

// using logical not operator


if (!isLoggedIn) {
cout << "Please log in to access this feature."
<< endl;
}
else {
cout << "Welcome to GeeksforGeeks!" << endl;
}

return 0;
}

Access specifires :
Access specifiers define how the members (attributes and methods) of a class can be accessed.

In C++, there are three access specifiers:


 public - members are accessible from outside the class
 private - members cannot be accessed (or viewed) from outside the class
 protected - members cannot be accessed from outside the class, however, they can be accessed in
inherited classes. You will learn more about Inheritance later.

**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.

class MyClass {
public: // Public access
specifier
int x; // Public attribute
private: // Private access
specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed
(public)
myObj.y = 50; // Not allowed
(private)
return 0;
}

Output : error: y is private

Jump Statements :
Jump statements are used to manipulate the flow of the program if some conditions are met. It is
used to terminate or continue the loop inside a program or to stop the execution of a function.

Types of Jump Statements in C++


In C++, there is four jump statement
1. break
2. continue
3. goto
4. return
continue in C++
The C++ continue statement is used to execute other parts of the loop while skipping some
parts declared inside the condition, rather than terminating the loop, it continues to execute the
next iteration of the same loop. It is used with a decision-making statement which must be
present inside the loop.
This statement can be used inside for loop or while or do-while loop.

Syntax of continue

continue;

break in C++
The C++ break statement is used to terminate the whole loop if the condition is met. Unlike the
continue statement after the condition is met, it breaks the loop and the remaining part of the
loop is not executed.
The break statement is used with decision-making statements such as if, if-else,
or switch statement which is inside the for loop which can be for loop, while loop, or do-while
loop. It forces the loop to stop the execution of the further iteration.
Syntax

break;

return in C++
The return statement takes control out of the function itself. It is stronger than a break. It is used
to terminate the entire function after the execution of the function or after some condition.
Every function has a return statement with some returning value except the void() function.
Although void() function can also have the return statement to end the execution of the function.

Goto statement in C++


The C++ goto statement is used to jump directly to that part of the program to which it is being
called. Every goto statement is associated with the label which takes them to part of the
program for which they are called. The label statements can be written anywhere in the program
it is not necessary to use them before or after the goto statement.

Syntax

goto label_name;
.
.
.
label_name:

Example:
// return statement // goto statement
// continue statement // break statement #include <iostream>
#include <iostream>
#include <iostream> #include <iostream> using namespace std;
using namespace std;
using namespace std; using namespace std;
int main() // Driver Code
// Driver code // Driver Code int main()
{
int main() int main() {
out << "Begin ";
{ { int n = 4;
for (int i = 1; i < 10; i++) { for (int i = 1; i < 10; i++) { for (int i = 0; i < 10; i++) {
// Breaking Condition if (n % 2 == 0)
if (i == 5) if (i == 5) goto label1;
// Termination
continue; break; else
condition
cout << i << " "; cout << i << " "; goto label2;
if (i == 5)
} } return 0;
return 0; return 0; label1:
cout << i << " ";
} } cout << "Even" << endl;
}
cout << "end"; return 0;

return 0; label2:
} cout << "Odd" << endl;
}
Keyword:

a keyword is a reserved word that has a predefined meaning in the language. These words cannot be used as
identifiers (e.g., variable names, function names) because they have special significance to the compiler.

Examples of C++ keywords:


 int: Used to declare integer variables.
 if: Used for conditional statements.
 while: Used for loops.
 class: Used to define classes.
 public: Used to define access specifiers in classes.
 return: Used to return values from functions.

Important points about keywords:


 They are case-sensitive, so int is different from INT.

R. what is class and object?descrinbe object and calss concept in deatil?how to cresate
xalss and object?

Pointer :

Pointers are variable that stores the address of another variable.

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a
value.
#include <iostream>

Syntax using namespace std;


int main()
datatype *var_name; {
int *ptr; // ptr can point to an address which holds int data int number=30;
int ∗ p;
Declaring a pointer p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<
The pointer in C++ language can be declared using ∗ (asterisk symbol).
<endl;
cout<<"Address of p variable is:"<<p<<endl;
. int ∗ a; //pointer to int
cout<<"Value of p variable is:"<<*p<<endl;
. char ∗ c; //pointer to char
return 0;
}
Advantage of pointer Output:
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with
Value of p variable is:30
arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Virtual base class in C+ + (mca)


Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of
a given class appearing in an inheritance hierarchy when using multiple inheritances.

Need for Virtual Base Classes: Consider the situation where we have one class A . This
class A is inherited by two other classes B and C. Both these class are inherited into another in a
new class D as shown in figure below.As we can see from the figure that data members/function of
class A are inherited twice to class D. One through class B and second through class C. When any
data / function member of class A is accessed by an object of class D, ambiguity arises as to which
data/function member would be called? One inherited through B or the other inherited through C.
This confuses compiler and it displays error.

#include <iostream> #include <iostream>


using namespace std; using namespace std;

class A { class A {
public: public:
void show() int a;
{ A() // constructor
cout << "Hello from A \n"; {
} a = 10;
}; }
};
class B : public A {
}; class B : public virtual A {
};
class C : public A {
}; class C : public virtual A {
};
class D : public B, public C {
}; class D : public B, public C {
};
int main()
{ int main()
D object; {
object.show(); : D object; // object creation of class d
Explanation
} The class A has just one data member a whichcout << "a = " << object.a << endl;
is public. This class is virtually inherited in
class B and class C. Now class B and class C use the virtual base class A and no duplication of
return 0;
//error due toaambigunity
data member is done; Classes B and C share
} a single copy of the members in the virtual base
class A.
Output : a = 10

Operator :

An operator is a symbol that operates on a value to perform specific mathematical or logical


computations. They form the foundation of any programming language. In C++, we have built-in
operators to provide the required functionality.
An operator operates the operands. For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

* expalin each by own.

Constructor :

A constructor is a special member function that is called automatically when an object is created.

Constructors are functions of a class that are executed when new objects of the class are created. The constructors
have the same name as the class and no return type, not even void. They are primarily useful for providing initial
values for variables of the class.

The two main types of constructors are default constructors and parameterized constructors.

Characteristics of Constructors in C++


 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class though they can be
declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.

Rules to define constructor :


The constructor must have the same name as the class.

Constructors do not have a return type, not even void.


Constructors can have any access specifier (public, protected, or private), but they are typically declared
as public.
Constructors can take parameters, just like any other function. These parameters are used to initialize the object's data
members.
Syntax of Constructors in C++
The prototype of the constructor looks like this:
<class-name> (){
...
}
Types of Constructors in C++
Constructors can be classified based on in which situations they are being used. There are 4
types of constructors in C++:

1. Default Constructor

A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is
also called a zero-argument constructor.
Syntax of Default Constructor
className() {
// body_of_constructor
}
The compiler automatically creates an implicit default constructor if the programmer does not
define one.

2. Parameterized Constructor

Parameterized constructors make it possible to pass arguments to constructors. Typically, these


arguments help initialize an object when it is created. To create a parameterized constructor,
simply add parameters to it the way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
Syntax of Parameterized Constructor
className (parameters...) {
// body
}
If we want to initialize the data members, we can also use the initializer list as shown:
MyClass::MyClass(int val) : memberVar(val) {};

3. Copy Constructor

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.
The process of initializing members of an object through a copy constructor is known as copy
initialization. It is also called member-wise initialization because the copy constructor
initializes one object with the existing object, both belonging to the same class on a member-by-
member copy basis.

Syntax of Copy Constructor in C++


Copy constructor takes a reference to an object of the same class as an argument:
className (ClassName &obj)
{ class A {
member1 = obj.member1; public:
// for dynamic resources
int x;
..
// parameterized constructor.
}
A(int a) {

x=a;

// copy constructor

A(A &i) {

x = i.x;

};

int main() {

A a1(20); // Calling the parameterized constructor.


Destructor:

destructor is an instance member function that 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.

Syntax to Define Destructor


The syntax for defining the destructor within the class:
~ <class-name>() {
// some instructions
}

Characteristics of a Destructor
 A destructor is also a special member function like a constructor. Destructor destroys the
class objects created by the 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 created by the constructor. Hence,
destructor cannot be overloaded.
 It cannot be declared static or const.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

// C++ program to demonstrate the execution of constructor


// and destructor

#include <iostream>
using namespace std;

class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }

// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;

return 0;
}why do we need preprocessor direvtive #include<iostream> in c++ ?

Output :
nConstructor
C++, the preprocessor
executed directive #include <iostream> is necessary to access the standard input/output
library, allowing you to use functions like cout and cin to interact with the user by displaying output on the
Destructor executed
console and reading input from the user, respectively; essentially, it enables basic input and output operations
within your program
Actual and formal parameter :

Actual Parameters:
 These are the values or expressions passed to a function when it is called.
 They are also known as arguments.
 Actual parameters are matched with the corresponding formal parameters based on their position and data type.

Formal Parameters:
 These are the variables declared in the function definition that receive values when the function is called.
 They act as placeholders for the values that will be passed during the function call.
 Formal parameters are specified within the parentheses of the function declaration, along with their data types.

#include <iostream>

int add(int a, int b) { // a and b are formal parameters


return a + b;
}

int main() {
int x = 5, y = 10;
int result = add(x, y); // x and y are actual parameters
std::cout << "Result: " << result << std::endl;
return 0;
}

Data type :

**Defined each by own with syntax :

Break and continue :


Binary files:

A binary file in C++ is like a special container that stores data in a way that computers can understand directly,
without needing to translate it.

These files store information as raw data, like a series of 0s and 1s. This format is perfect for computers to read and
process quickly, but it's not directly readable by humans.

Why use binary files?


Efficiency: Binary files are often smaller and faster to read and write than text files, especially for large amounts of
data.
Flexibility: They can store any type of data, including images, videos, and programs

Q.write a fuction template to swap two values?


#include <iostream>
using namespace std;
s
template <class T>
int swap_numbers(T& x, T& y) {
T t;
t = x;
x = y;
y = t;
return 0;
}
int main() {
int a, b;
a = 10, b = 20;

// Invoking the swap()


swap_numbers(a, b);
cout <<a << " " << b << endl;
return 0;
}
File
Output : 20 10
In C++, a file is a collection of data that is stored on a storage device, such as a hard drive. You can use files to
store and retrieve data persistently, even after your program terminates.

File Handling in C++:


We can access various file handling methods in C++ by importing the <fstream> class.. This library contains
several classes that enable you to perform various file operations:
 ofstream: this class Used for creating and writing to files.it contains open() function with default input mode.
 ifstream: Used for reading data from files .it contains open() function with default input mode.
 fstream: Used for both reading from and writing to files.

Q.what arre the stpes involved in using a file in a c++ program

For achieving file handling we need to follow the following steps:-


STEP 1-Naming a file
STEP 2-Opening a file,Before performing any operation on a file, it must be opened. In C++, we
use the open() method.

ofstream outfile;
outfile.open("example.txt");

STEP 3-Writing data into the file

 Writing: outfile << "Writing to file." << endl;

STEP 4-Reading data from the file

 Reading: infile >> variable;

STEP 5-Closing a file., After completing operations on the file, it's essential to close it using
the close() method. Closing the file releases the resources that were allocated for that file during
the operation.

outfile.close();

File modes in c++

In C++, file mode refers to the settings used when opening a file to specify how the file will
be accessed (e.g., for reading, writing, or appending). File modes are typically used with file
streams provided by the <fstream> library, such as std::ifstream, std::ofstream, and
std::fstream

Common File Modes:

Here’s a list of file modes and what they do:

1. ios::in

 Opens a file for reading.


 The file must already exist; otherwise, the operation fails.

2. ios::out

 Opens a file for writing.


 If the file already exists, its contents are overwritten.
 If the file doesn’t exist, it is created.

3.ios::app

 Opens a file for appending.


 Data is added to the end of the file without modifying its existing content.

4.ios::binary

 Opens the file in binary mode (instead of text mode).


 Useful for reading or writing non-text data, like images or compiled files.

5.ios::ate

 Opens the file and moves the file pointer directly to the end.
 You can still modify data at any position in the file.

6.ios::trunc

 Opens the file and clears its contents if it already exists.


 Used by default with ios::out.

Combining File Modes:

You can combine modes using the bitwise OR operator ( |). For example:

 ios::out | ios::app: Opens a file for writing and appends to it.


 ios::in | ios::binary: Opens a file for reading in binary mode.

Example Code:
#include <fstream>
#include <iostream>
using namespace std;

int main() {
fstream file;

// Open the file in both read and write mode


file.open("example.txt", ios::in | ios::out | ios::app);

if (file.is_open()) {
// Write to the file
file << "Hello, File Modes!" << endl;

// Go to the beginning of the file and read its contents


file.seekg(0, ios::beg);
string line;
while (getline(file, line)) {
cout << line << endl;
}

file.close();
} else {
cout << "Failed to open the file!" << endl;
}

return 0;
}

Key Points:
 Default Mode: ios::out with ofstream and ios::in with ifstream.
 Binary Mode: Used for files with data other than plain text.
 Append vs Truncate: Use ios::app to keep existing data and add more, while ios::trunc clears it.

Q. Syntax and exapmle of openung and closing a file ?

R. done at up page

//opning and closing a file

#include <iostream>#include <fstream>

using namespace std;

int main() {

// opening a text file for writing


ofstream my_file("example.txt");

// close the file


my_file.close();

return 0;
Q. diff. b/w sequental file and random file
}

Order of invocation of constructor and destructor :

In C++ multiple inheritance, when a class inherits from multiple base classes, the
order of constructor and destructor calls follows specific rules. Here's a breakdown:

Order of Constructor Invocation:

1.Base Class Constructors:

 Constructors of base classes are called first, in the order in which they are listed in the
inheritance list.
 This happens before the constructor of the derived class.

2.Derived Class Constructor:

 After all base class constructors have been called, the constructor of the derived class is executed.

Order of Destructor Invocation:

1.Derived Class Destructor:

 The destructor of the derived class is called first.

2.Base Class Destructors:

 After the derived class destructor finishes, destructors of base classes are called in the reverse
order of inheritance.

Example:
#include <iostream>
using namespace std;

// Base classes
class A {
public:
A() { cout << "Constructor of A\n"; }
~A() { cout << "Destructor of A\n"; }
};

class B {
public:
B() { cout << "Constructor of B\n"; }
~B() { cout << "Destructor of B\n"; }
};

// Derived class
class C : public A, public B {
public:
C() { cout << "Constructor of C\n"; }
~C() { cout << "Destructor of C\n"; }
};

int main() {
C obj; // Create an object of derived class
return 0;
}

Output:
Constructor of A
Constructor of B
Constructor of C
Destructor of C
Destructor of B
Destructor of A
Explanation:

1.The constructor call order is determined by the inheritance list:

 A is constructed first (since it's listed first in class C : public A, public B).
 Then B is constructed.
 Finally, the constructor of C (the derived class) is called.

2.The destructor call order is the reverse of the constructor call order:

 First, the destructor of C is called.


 Then, the destructor of B is called.
 Finally, the destructor of A is called.

Key Points:

 The order of constructor calls depends on the inheritance list order, not the order in which the base
classes are defined.
 The order of destructor calls is the reverse of the constructor calls.
 You can use initializer lists in the derived class constructor to explicitly initialize the base classes.

Stream

The word Streams means continuous flow of data or instructions

a stream refers to a sequence of characters that are transferred between the program and input/output
(I/O) devices. Stream classes in C++ facilitate input and output operations on files and other I/O devices.

To use streams in C++, you need to include the appropriate header file. For instance, to use input/output
streams, you would include the iostream header file. This library provides the necessary functions and
classes to work with streams, enabling you to read and write data to and from files and other I/O devices.

essential C++ stream classes:


1. istream
2. ostream
3. ifstream
4. ofstream

Data oriented approach


A "data-oriented approach" in C++ means designing software by prioritizing the organization
and manipulation of data as the central focus, often by separating data structures from
their associated functions, with the goal of optimizing performance by efficiently
accessing and processing data in memory

Static Member Function in C++


Static Member Function in a class is the function that is declared as static because of which
function attains certain properties as defined below:
 A static member function is independent of any object of the class.
 A static member function can be called even if no objects of the class exist.
 A static member function can also be accessed using the class name through the scope
resolution operator.
 A static member function can access static data members and static member functions inside
or outside of the class.
 Static member functions have a scope inside the class and cannot access the current object
pointer.
 You can also use a static member function to determine how many objects of the class have
been created.
The reason we need Static member function:
 Static members are frequently used to store information that is shared by all objects in a
class.
 For instance, you may keep track of the quantity of newly generated objects of a specific class
type using a static data member as a counter. This static data member can be increased each
time an object is generated to keep track of the overall number of objects.

// C++ Program to demonstrate


// Static member in a class
#include <iostream>
using namespace std;

class Student {
public:
// static member
static int total;

// Constructor called
Student() { total += 1; }
};

int Student::total = 0;

int main(){
// Student 1 declared
Student s1;
cout << "Number of students:" << s1.total << endl;

// Student 2 declared
Student s2;
cout << "Number of students:" << s2.total << endl;

// Student 3 declared
Student s3;
cout << "Number of students:" << s3.total << endl;
return 0;
}
Outout
Number of students:1
Number of students:2
Number of students:3
Function prototype

In C++, a function prototype is a declaration of a function that specifies the function's name,
return type, and parameters, but omits the function body. It acts as a blueprint for the compiler,
informing it about the function's interface before its actual definition

Can constructor and desrtror overlaod if yes then how ?


Constructors:
Yes, they can be overloaded. You can have multiple constructors in a class, each taking different
parameters. This allows you to create objects in different ways.

Destructors:
No, they cannot be overloaded. A class can only have one destructor, which takes no parameters.

// C++ program to illustrate


// Constructor overloading
#include <iostream>
using namespace std;

class construct
{

public:
Why we need manipulator
anipulators are used to format the input and output streams. They provide a convenient way to
control the appearance of data without having to write complex formatting code. They are defined
inside the <iostream> and <iomanip>

Example : endl- for new line,

Readability and Maintainability: , Control over Formatting: , Flexibility:

Static vs late binding

You might also like