CPP Exam

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

What is C++?

C++ is a general-purpose, object-oriented programming language. It was created by


BjarneStroustrup at Bell Labs circa 1980. C++ is very similar to C (invented by Dennis
Ritchie in the early 1970s). C++ is so compatible with C that it will probably compile over
99% of C programs without changing a line of source code. Though C++ is a lot of well-
structured and safer language than C as it OOPs based.

Some computer languages are written for a specific purpose. Like, Java was initially
devised to control toasters and some other electronics. C was developed for
programming OS. Pascal was conceptualized to teach proper programming techniques.
But C++ is a general-purpose language. It well deserves the widely acknowledged
nickname “Swiss Pocket Knife of Languages.”

Manipulator
A manipulator in C++ is a special type of function that can be used to modify the output
stream. Manipulators are used to change the format of the output, such as setting the
precision of a floating-point value or specifying the field width when printing data.
Here is an example of using manipulators in C++:
#include <iostream>
#include <iomanip> // Needed to use manipulators
using namespace std;
int main()
{
// Set the floating-point precision to 2 decimal places
cout << setprecision(2);
// Declare some variables
double x = 1.23456;
int y = 78;
// Print the variables using manipulators
cout << x << "\n"; // Output: 1.23
cout << setw(4) << y << "\n"; // Output: 78
return 0;
}

In the example, the setprecision manipulator is used to set the floating-point precision
to 2 decimal places, and the setw manipulator is used to set the field width when
printing the y variable. This causes the number to be padded with spaces so that it
occupies a field of width 4.
Data Type
In C++, a data type is a classification of types of data that determines the possible
values for that type, the operations that can be performed on it, and the way it can be
stored in memory. C++ supports a wide range of built-in data types, including integer,
floating-point, character, and boolean types.
Here is an example of some common data types in C++:
int a = 5; // integer type
double b = 3.14; // floating-point type
char c = 'A'; // character type
bool d = true; // boolean type
In this example, the int data type is used to store an integer value, the double data type
is used to store a floating-point value, the char data type is used to store a character
value, and the bool data type is used to store a boolean value (true or false).
C++ also allows users to define their own custom data types using user-defined types
such as enumerations, classes, and structures. These types can be used to create
more complex data structures and to organize data in a way that is meaningful for the
specific application.
Scope resolution
The scope resolution operator in C++ is "::" and it is used to specify the scope in which
a particular identifier exists. For example, if you have a class with a member variable
and a local variable with the same name, you can use the scope resolution operator to
specify which one you want to use. Here is an example:
class MyClass
{
public:
int x = 10;
};

int main()
{
MyClass obj;
int x = 20;

// Use the class's member variable x


std::cout << obj.x << std::endl;

// Use the local variable x


std::cout << x << std::endl;

// Use the class's member variable x again


std::cout << obj::x << std::endl;

return 0;
}
In this code, the first cout statement will print the value of the x member variable from
the MyClass object obj, which is 10. The second cout statement will print the value of
the local variable x, which is 20. The third cout statement uses the scope resolution
operator to explicitly specify that we want to use the x member variable from the obj
object, so it will also print 10.
Constructors
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. 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. Constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object which is why it is known as
constructors.

Constructor does not have a return value, hence they do not have a return type.
Example
// defining the constructor outside the class
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
int main()
{
student s;
s.display();
return 0;
}
Output:
Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
Types of Constructors
In C++, there are several types of constructors that can be used in a class:
1. Default constructor: This constructor is called when an object is created with no
arguments. It typically initializes the member variables of the object with default
values. For example:
class MyClass {
public:
MyClass() {
// Initialize member variables with default values
x = 0;
y = 0;
}
// Other class members
private:
int x;
int y;
};
int main() {
MyClass obj; // Default constructor is called
return 0;
}
2. Parameterized constructor: This constructor is called when an object is created
with some arguments. It typically initializes the member variables of the object
with the given values. For example:
class MyClass {
public:
MyClass(int a, int b) {
// Initialize member variables with given values
x = a;
y = b;
}
// Other class members
private:
int x;
int y;
};

int main() {
MyClass obj(10, 20); // Parameterized constructor is called
return 0;
}
Inheritance

In C++, inheritance is a mechanism that allows one class (i.e., a child class or derived
class) to inherit members (i.e., variables and functions) from another class (i.e., a parent
class or base class). This allows the derived class to reuse the functionality defined in
the base class, without having to reimplement it.
Inheritance is a key concept in object-oriented programming (OOP), as it enables code
reuse and polymorphism. Code reuse means that you can use the code defined in the
base class in the derived class, without having to write it again. Polymorphism means
that you can use the same code to operate on objects of different classes, without
knowing their exact type at compile time.
Example:
// Example: define member function without argument within the class

#include<iostream>
using namespace std;

class Person
{
int id;
char name[100];

public:
void set_p()
{
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
cout<<"Enter the Name:";
cin.get(name,100);
}

void display_p()
{
cout<<endl<<id<<"\t"<<name<<"\t";
}
};

class Student: private Person


{
char course[50];
int fee;

public:
void set_s()
{
set_p();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}
void display_s()
{
display_p();
cout<<course<<"\t"<<fee<<endl;
}
};

main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000

101 Dev GCS 70000


Types of inheritance:
In C++, there are several types of inheritance that allow one class to inherit members
(i.e., variables and functions) from another class. The types of inheritance in C++
include:
1. Single inheritance: In single inheritance, a derived class (also called a child
class) inherits members from a single base class (also called a parent class).
Example:
#include<iostream>
using namespace std;
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
class Car : public Vehicle {

};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle

2. Multiple inheritance: In multiple inheritance, a derived class inherits members


from multiple base classes.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};
class Car : public Vehicle, public FourWheeler {
};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel inheritance: In multilevel inheritance, a class inherits from a derived


class, which in turn inherits from a base class.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical inheritance: In hierarchical inheritance, multiple derived classes


inherit from a single base class.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
class Car : public Vehicle {
};
class Bus : public Vehicle {
};
int main()
{
Car obj1;
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) inheritance: Hybrid inheritance is a combination of two or more


types of inheritance, such as single inheritance and multiple inheritance.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};
class Car : public Vehicle {
};

class Bus : public Vehicle, public Fare {


};
int main()
{
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
Abstract class
In C++, an abstract class is a class that cannot be instantiated on its own, but can be
used as a base class for other classes that inherit from it. An abstract class defines an
interface, but does not provide an implementation for all of its methods. This means that
any class that inherits from an abstract class must provide implementations for the
abstract methods defined in the base class.
Abstract classes are typically used to define a common interface for a group of related
classes, and to provide a default implementation for some of the methods in that
interface. This allows for flexibility and code reuse, as derived classes can override the
default implementations of the abstract methods if necessary.
Here is an example of an abstract class in C++:
// Abstract base class
class Vehicle {
public:
// Pure virtual method
virtual void startEngine() = 0;

// Concrete method with default implementation


void stopEngine() {
std::cout << "Stopping engine." << std::endl;
}
};

// Derived class that inherits from Vehicle


class Car : public Vehicle {
public:
// Override startEngine() method from Vehicle
void startEngine() {
std::cout << "Starting car engine." << std::endl;
}
};

// Another derived class that inherits from Vehicle


class Motorcycle : public Vehicle {
public:
// Override startEngine() method from Vehicle
void startEngine() {
std::cout << "Starting motorcycle engine." << std::endl;
}
};
In this example, the Vehicle class is an abstract base class that defines a pure virtual
method called startEngine() and a concrete method called stopEngine() with a default
implementation. The Car and Motorcycle classes are derived from the Vehicle class
and override the startEngine() method to provide their own implementation. Because
the stopEngine() method has a default implementation in the Vehicle class, the Car
and Motorcycle classes do not need to provide their own implementation for this
method.
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.
1 CompileTime Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a feature of
object-oriented programming providing many functions to have the same name but
distinct parameters when numerous tasks are listed under one function name. There
are certain Rules of Function Overloading that should be followed while overloading a
function.
Below is the C++ program to show function overloading or compile-time polymorphism:
// C++ program to demonstrate
// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>

using namespace std;


class Geeks {
public:

// Function with 1 int parameter


void func(int x)
{
cout << "value of x is " <<
x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " <<
x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " <<
x << ", " << y << endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}
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.
To know more about this, you can refer to the article – Function Overloading in C++.
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.
Below is the C++ program to demonstrate operator overloading:
// C++ program to demonstrate
// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;

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

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

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
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.
To know more about this one, refer to the article – Operator Overloading.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
Below is the C++ program to demonstrate function overriding:
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class" <<
endl;
}

void show()
{
cout << "show base class" <<
endl;
}
};

class derived : public base {


public:

// print () is already virtual function in


// derived class, we could also declared as
// virtual void print () explicitly
void print()
{
cout << "print derived class" <<
endl;
}

void show()
{
cout << "show derived class" <<
endl;
}
};

// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at


// runtime (Runtime polymorphism)
bptr->print();

// Non-virtual function, binded


// at compile time
bptr->show();

return 0;
}
Output:
print derived class
show base class
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.
Some Key Points About Virtual Functions:
 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
 A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
// C++ Program to demonstrate
// the Virtual Function
#include <iostream>
using namespace std;
// Declaring a Base class
class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function" <<
"\n\n";
}

void print()
{
cout << "Called GFG_Base print function" <<
"\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

public:
void display()
{
cout << "Called GFG_Child Display Function" <<
"\n\n";
}
void print()
{
cout << "Called GFG_Child print Function" <<
"\n\n";
}
};

// Driver code
int main()
{
// Create a reference of class bird
GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}
Output:
Called virtual Base Class function

Called GFG_Base print function


Exception Handling
Exception handling is a mechanism for dealing with errors or exceptional situations that
may occur in a program. In C++, exception handling is implemented using the try, catch,
and throw keywords.
The try keyword is used to enclose a block of code that may throw an exception. If an
exception is thrown in a try block, the code execution will immediately jump to the
corresponding catch block, which is used to handle the exception. If no exception is
thrown, the code in the catch block will not be executed.
The throw keyword is used to throw an exception. The throw keyword is typically used
inside a try block to indicate that an error or exceptional situation has occurred, and the
exception should be handled by a catch block.
Here is an example of exception handling in C++ using the try, catch, and throw
keywords:
#include <iostream>
#include <string>

int main() {
// Prompt the user to enter a number
std::cout << "Enter a number: ";
int x;
std::cin >> x;

try {
// Check if the number is negative
if (x < 0) {
// Throw an exception if the number is negative
throw std::string("Negative number");
}

// Print the square of the number if it is non-negative


std::cout << "The square of the number is " << x * x << std::endl;
} catch (std::string& ex) {
// Handle the exception if the number is negative
std::cout << "Error: " << ex << std::endl;
}

return 0;
}
In this example, the code prompts the user to enter a number and reads the number
from the standard input. The code then checks if the number is negative. If the number
is negative, an exception is thrown using the throw keyword. The exception is caught in
the catch block, which prints an error message and handles the exception. If the
number is non-negative, the code prints the square of the number.
In this example, the try block encloses the code that may throw an exception, and the
catch block handles the exception if it is thrown. The throw keyword is used to throw
an exception if the number is negative, and the exception is caught and handled in the
catch block. This is an example of exception handling in C++.
Inline Function
In C++, an inline function is a function that is expanded in line when it is called, rather
than being called like a normal function. This means that the code for the function is
inserted at the call site, which can improve performance by reducing function call
overhead.
Here is an example of an inline function in C++:
#include <iostream>

inline int max(int a, int b) {


return (a > b) ? a : b;
}

int main() {
int x = 5, y = 10;
std::cout << "Max: " << max(x, y) << std::endl;
return 0;
}
In this example, the max() function is an inline function that takes two int values and
returns the maximum of the two. In the main() function, the max() function is called, and
the code for the function is inserted inline at that point, rather than calling the function
and jumping to the function's code. This can improve performance by reducing function
call overhead.
Friend Function
In C++, a friend function is a function that is declared as a friend of a class. This means
that the friend function has access to the private and protected members of the class.
Friend functions are often used to implement operators or other functionality that needs
access to the internals of a class.
Here is an example of a friend function in C++:
#include <iostream>

class Rectangle {
private:
int width, height;

public:
Rectangle(int w, int h) : width(w), height(h) {}

friend int area(const Rectangle& r);


};

int area(const Rectangle& r) {


return r.width * r.height;
}

int main() {
Rectangle rect(5, 10);
std::cout << "Area: " << area(rect) << std::endl;
return 0;
}
In this example, the area() function is declared as a friend of the Rectangle class. This
means that the area() function has access to the private members of the Rectangle
class, and can be used to calculate the area of a Rectangle object. In the main()
function, an instance of the Rectangle class is created, and the area() function is called
to calculate its area. Because area() is a friend function, it is able to access the private
members of the Rectangle object and calculate its area correctly.
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.
Some Key Points About Virtual Functions:
 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
 A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
// C++ Program to demonstrate
// the Virtual Function
#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function" <<
"\n\n";
}

void print()
{
cout << "Called GFG_Base print function" <<
"\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

public:
void display()
{
cout << "Called GFG_Child Display Function" <<
"\n\n";
}

void print()
{
cout << "Called GFG_Child print Function" <<
"\n\n";
}
};

// Driver code
int main()
{
// Create a reference of class bird
GFG_Base* base;

GFG_Child child;
base = &child;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}
Output:
Called virtual Base Class function

Called GFG_Base print function


Feature and Advantages of OOP
Object-oriented programming (OOP) is a programming paradigm that is based on the
concept of "objects", which can contain data and code that manipulates that data. OOP
languages, such as C++ and Java, provide features that support OOP principles, such
as inheritance, polymorphism, and encapsulation.
Some of the main features of OOP are:
 Inheritance: This allows a class to inherit properties and behavior from a parent
class, making it possible to create hierarchies of classes that can share common
functionality. This allows for code reuse and makes it easier to manage and
maintain large and complex programs.
 Polymorphism: This allows objects of different classes to be treated the same
way, even if they have different properties and behavior. This is often achieved
through the use of virtual functions and interfaces. Polymorphism allows for more
flexible and reusable code.
 Encapsulation: This allows the implementation details of a class to be hidden
from the outside world, so that users of the class only need to know its public
interface. Encapsulation allows for cleaner and more modular code, and it makes
it easier to maintain and evolve a program over time.
Some of the advantages of OOP are:
 Modularity: OOP allows code to be organized into self-contained modules,
called classes, which can be easily reused in different parts of a program. This
makes it easier to develop and maintain large and complex programs.
 Extensibility: New functionality can be added to a program by creating new
classes that inherit from existing classes, without having to modify the existing
code. This makes it easier to evolve a program over time to support new features
and requirements.
 Maintainability: OOP code is typically easier to maintain because changes to a
class do not affect other parts of the program, and because the code is organized
into logical units. This makes it easier to fix bugs and add new features to a
program.
 Scalability: OOP programs can be easily scaled up to support larger and more
complex functionality, because new functionality can be added through the
creation of new classes. This makes it easier to grow and evolve a program over
time.
 Reusability: OOP allows classes to be easily reused in different programs,
which can save time and effort when developing new software.
 Abstraction: OOP allows for the creation of abstract classes that define common
interfaces for related classes, without providing a concrete implementation. This
makes it possible to create flexible and reusable code that can be easily
extended and adapted to new requirements.
Overall, the main advantage of OOP is that it makes it possible to develop large and
complex programs in a modular and reusable way, which makes the code easier to
understand, maintain, and evolve over time.
Dynamic Memory Allocation
Dynamic memory allocation in C++ refers to the process of allocating memory for
variables at runtime, rather than during compile time. This is done using the new and
delete operators in C++.
Here is an example of dynamic memory allocation in C++:
#include <iostream>

int main() {
// Allocate memory for an int variable and store the address in a pointer
int* ptr = new int;

// Use the pointer to store a value in the dynamically allocated memory


*ptr = 5;

// Print the value stored at the dynamically allocated memory location


std::cout << *ptr << std::endl;
// Deallocate the dynamically allocated memory
delete ptr;

return 0;
}
In this example, we use the new operator to dynamically allocate memory for an int
variable. This returns a pointer to the memory location where the int is stored. We can
then use the pointer to store a value in the dynamically allocated memory, and print it
using the * operator to dereference the pointer.
To free the dynamically allocated memory, we use the delete operator and pass it the
pointer to the memory location. This deallocates the memory and makes it available for
other parts of the program to use.
It's important to note that dynamically allocated memory will not be automatically
deallocated when a program ends. This means that it's the responsibility of the
programmer to manually deallocate any dynamically allocated memory when it's no
longer needed. Failing to do so can result in memory leaks, which can cause a program
to run out of memory and crash.
Function Overloading
Function overloading in C++ is a feature that allows a class or function to have multiple
definitions with the same name but different parameter lists. This allows the same
function to be called with different types of arguments and perform different actions
depending on the arguments provided.
Here is an example of function overloading in C++
#include <iostream>

// Define a function called "max" that takes two arguments of type int
int max(int a, int b) {
// Return the greater of the two arguments
return (a > b) ? a : b;
}

// Define another function called "max" that takes three arguments of type int
int max(int a, int b, int c) {
// Return the greater of the three arguments
return (a > b && a > c) ? a : ((b > a && b > c) ? b : c);
}

int main() {
// Call the "max" function with two int arguments
int m1 = max(5, 10);
std::cout << "Max of 5 and 10 is: " << m1 << std::endl;

// Call the "max" function with three int arguments


int m2 = max(5, 10, 15);
std::cout << "Max of 5, 10, and 15 is: " << m2 << std::endl;

return 0;
}
In this example, we define two functions called max, both of which take integer
arguments and return the greater of the arguments provided. The first max function
takes two int arguments, while the second max function takes three int arguments.
When we call the max function in the main function, the correct version of the function
is called based on the number of arguments provided. When we call max(5, 10), the
first max function is called because it takes two arguments. When we call max(5, 10,
15), the second max function is called because it takes three arguments.
Function overloading is a useful feature in C++ because it allows a single function to be
called with different types of arguments and perform different actions depending on the
arguments provided. This can make code more concise and easier to read.
Template
In C++, templates are a powerful feature that allows the programmer to write code that
can be used with multiple data types without having to write separate functions for each
data type. This is achieved by using placeholder types in the code, which are replaced
with specific types at compile time.
To create a template in C++, the template keyword is used followed by angle brackets
<> that contain the placeholder type(s). The placeholder type(s) are specified using the
typename keyword and can be used anywhere in the template function or class to refer
to the actual type that will be used when the template is instantiated.
Here is an example of a template function in C++:
#include <iostream>
// Define a template function called "max" that takes two arguments of a generic type
template <typename T>
T max(T a, T b) {
// Return the greater of the two arguments
return (a > b) ? a : b;
}

int main() {
// Call the "max" function with two int arguments
int m1 = max(5, 10);
std::cout << "Max of 5 and 10 is: " << m1 << std::endl;

// Call the "max" function with two double arguments


double m2 = max(5.5, 10.5);
std::cout << "Max of 5.5 and 10.5 is: " << m2 << std::endl;

return 0;
}
In this example, we define a template function called max that takes two arguments of a
generic type T. The T type is specified using the typename keyword and is used as a
placeholder for the actual type that will be used when the max function is called.
In the main function, we call the max function twice, once with two int arguments and
once with two double arguments. When the max function is called, the placeholder T
type is replaced with the specific type of the arguments provided, so the first max call
uses T = int, and the second max call uses T = double.
Templates are a powerful and versatile feature in C++ that allows the programmer to
write generic code that can be used with multiple data types. This can make code more
modular and reusable, and can help to avoid code duplication.

You might also like