0% found this document useful (0 votes)
12 views43 pages

C++ Own Answer

C++ is a general-purpose, object-oriented programming language that enhances C with features like dynamic memory allocation, multi-threading, and a rich set of libraries. It emphasizes the four pillars of Object-Oriented Programming: abstraction, encapsulation, inheritance, and polymorphism, which promote modularity, reusability, and maintainability in software development. The document also covers the concepts of classes, objects, access specifiers, and constructors, detailing their roles and functionalities in C++.

Uploaded by

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

C++ Own Answer

C++ is a general-purpose, object-oriented programming language that enhances C with features like dynamic memory allocation, multi-threading, and a rich set of libraries. It emphasizes the four pillars of Object-Oriented Programming: abstraction, encapsulation, inheritance, and polymorphism, which promote modularity, reusability, and maintainability in software development. The document also covers the concepts of classes, objects, access specifiers, and constructors, detailing their roles and functionalities in C++.

Uploaded by

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

1. What is C++? Explain multiple features of it.

C++ is a general-purpose programming language that was developed as an


enhancement of the C language to include an object-oriented paradigm. It is an
imperative and compiled language. C++ has a number of features, including:
• Object-Oriented Programming
• Machine Independent
• Simple
• High-Level Language
• Popular
• Case-sensitive
• Compiler Based
• Dynamic Memory Allocation
• Memory Management
• Multi-threading
1. Object-Oriented Programming
C++ is an Object-Oriented Programming Language, unlike C which is a procedural
programming language. This is the most important feature of C++. It can
create/destroy objects while programming. Also, It can create blueprints with which
objects can be created. We have discussed the Object-Orient Programming Concepts
in C++ in this article.
Concepts of Object-oriented programming Language:
• Class
• Objects
• Encapsulation
• Polymorphism
• Inheritance
• Abstraction
2. Machine Independent
A C++ executable is not platform-independent (compiled programs on Linux won’t
run on Windows), however, they are machine-independent. Let us understand this
feature of C++ with the help of an example. Suppose you have written a piece of
code that can run on Linux/Windows/Mac OSx which makes the C++ Machine
Independent but the executable file of the C++ cannot run on different operating
systems.
3. Simple
It is a simple language in the sense that programs can be broken down into logical
units and parts, has rich library support and has a variety of data types. Also, the
Auto Keyword of C++ makes life easier.
Auto Keyword
The idea of the auto keyword was to form the C++ compiler to deduce the data type
while compiling instead of making you declare the data type every freaking time. Do
keep in mind that you cannot declare something without an initializer. There must
be some way for the compiler to deduce your type.
Example:
• C++

// C++ program to demonstrate


// working of auto keyword

#include <bits/stdc++.h>
using namespace std;

// Driver Code
int main()
{
// Variables
auto an_int = 26;
auto a_bool = false;
auto a_float = 26.24;
auto ptr = &a_float;

// Print typeid
cout << typeid(a_bool).name() << "\n";
cout << typeid(an_int).name() << "\n";
return 0;
}

Output:
b
i

4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language.
It makes life easier to work in C++ as it is a high-level language it is closely associated
with the human-comprehensible English language.
5. Popular
C++ can be the base language for many other programming languages that supports
the feature of object-oriented programming. Bjarne Stroustrup found Simula 67, the
first object-oriented language ever, lacking simulations, and decided to develop C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For example, cin is used
to take input from the input stream. But if the “Cin” won’t work. Other languages
like HTML and MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to be
compiled and their executable file is used to run them. C++ is a relatively faster
language than Java and Python.
8. Dynamic Memory Allocation
When the program executes in C++ then the variables are allocated the dynamical
heap space. Inside the functions, the variables are allocated in the stack space. Many
times, We are not aware in advance how much memory is needed to store particular
information in a defined variable and the size of required memory can be
determined at run time.
9. Memory Management
• C++ allows us to allocate the memory of a variable or an array in run time. This is
known as Dynamic Memory Allocation.
• In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is not the
case in C++.
• In C++, the memory must be de-allocated dynamically allocated memory
manually after it is of no use.
• The allocation and deallocation of the memory can be done using the new and
delete operators respectively.
10. Multi-threading
• Multithreading is a specialized form of multitasking and multitasking is a feature
that allows your system to execute two or more programs concurrently. In
general, there are two sorts of multitasking: process-based and thread-based.
• Process-based multitasking handles the concurrent execution of programs.
Thread-based multitasking deals with the multiprogramming of pieces of an
equivalent program.
• A multithreaded program contains two or more parts that will run concurrently.
Each part of such a program is named a thread, and every thread defines a
separate path of execution.
• C++ doesn’t contain any built-in support for multithreaded applications. Instead,
it relies entirely upon the OS to supply this feature.

2.Explain four pillars of OOPs.


Object-Oriented Programming (OOP) is a software development paradigm
emphasizing efficient and well-organized code. OOP is founded on four essential
principles, the Four Pillars: abstraction, encapsulation, inheritance, and polymorphism.
Abstraction allows us to concentrate on the fundamental characteristics of an object
while concealing superfluous complications. Encapsulation emphasizes the concept of
data concealing and data bundling with useful functions or procedures. Inheritance
allows developers to create new classes based on existing ones by establishing
hierarchical links between them. Polymorphism is the belief that different types of
objects can be treated interchangeably, providing flexibility and adaptability in
program design.

Introduction to OOP

Object-Oriented Programming (OOP) has emerged as a powerful paradigm in the ever-


changing world of software development, revolutionizing how we design and build
programs. With its emphasis on objects, encapsulation, and reusability, OOP offers a
systematic approach to software development that encourages modularity, flexibility,
and ease of maintenance. In this section, we will look at the underlying notions of
OOP and why it has become such an important part of modern software development.

Benefits of OOP:

Developers can gain various benefits by using OOP principles, including:

• Modularity: OOP fosters the division of complicated systems into smaller,


manageable modules, which improves code organization and understanding.

• Reusability: OOP allows developers to reuse classes and objects across projects,
saving time and effort.

• Maintenance: The modularity and encapsulation of OOP make it easier to


maintain and update code, reducing the impact of changes.
• Scalability: Because of OOP's hierarchical structure and inheritance, developers
can extend and modify code without affecting the entire system.

The Four Pillars of OOPs

Object-Oriented Programming (OOP) has developed as a powerful paradigm in


programming, facilitating the construction of resilient and scalable software systems.
OOP enables developers to organize code logically and efficiently, improving code
reuse, maintainability, and overall software quality. At the heart of OOP are the Four
Pillars, which serve as the framework for developing well-structured, modular
programs. This section will examine the Four Pillars of OOP and their significance in
real-world situations.

1. Abstraction

Abstraction is breaking down complex systems into manageable and reusable


components to simplify them. It enables us to construct classes and objects that
accurately replicate real-world entities while disregarding superfluous features. We
can create more efficient and maintainable software by focusing on the essentials.
Abstraction in OOP is accomplished through the usage of abstract classes and
interfaces. Consider the following scenario: We have an abstract base class
called Shape, which declares a pure virtual function calculateArea(), used to calculate
the area of various forms. Rectangle and Circle are derived classes that inherit from
the Shape class and provide their implementations of the calculateArea() function.

2. Encapsulation

Encapsulation groups data and methods within a class to provide a protective barrier
over internal implementation details. It allows the construction of objects that
encapsulate data and reveal only the methods or interfaces required for interaction
with the outside world. This method encourages information concealment by
prohibiting direct access to an object's internal state.

3. Inheritance

Inheritance creates an "is-a" relationship between classes by allowing a derived or


child class to inherit characteristics from a parent or base class. This relationship
allows the derived class to access and utilize the base class's properties and methods,
boosting code reuse and decreasing redundancy. The Circle and Rectangle classes in
the preceding code inherit from the Shape class via the public access specifier. This
option allows derived classes to access the base class's protected members.
The Shape class defines common properties (width and height) and methods
(setDimensions and displayDimensions) that derived classes can use.

4. Polymorphism

Polymorphism, derived from the Greek words "poly" (many) and "morph" (shape),
refers to an object's ability to take on numerous forms or behaviors. Polymorphism in
the context of OOP allows objects of different kinds to be treated consistently when
they share a common superclass.

2.Class & Object (with Syntax).


C++ Classes/Objects

C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class.
These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works as an
object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Example explained

• The class keyword is used to create a class called MyClass.

• The public keyword is an access specifier, which specifies that members


(attributes and methods) of the class are accessible from outside the class. You
will learn more about access specifiers later.

• Inside the class, there is an integer variable myNum and a string


variable myString. When variables are declared within a class, they are
called attributes.

• At last, end the class definition with a semicolon ;.

Create an Object

In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the
object:

Example

Create an object called "myObj" and access the attributes:

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

4. Access Specifier:
Access modifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding. Consider a real-life example:
The Research and Analysis Wing (R&AW), having 10 core members, has come into
possession of sensitive confidential information regarding national security. Now we
can correlate these core members to data members or member functions of a class,
which in turn can be correlated to the R&A Wing. These 10 members can directly
access the confidential information from their wing (the class), but anyone apart from
these 10 members can’t access this information directly, i.e., outside functions other
than those prevalent in the class itself can’t access the information (that is not entitled
to them) without having either assigned privileges (such as those possessed by a
friend class or an inherited class, as will be seen in this article ahead) or access to one
of these 10 members who is allowed direct access to the confidential information
(similar to how private members of a class can be accessed in the outside world
through public member functions of the class that have direct access to private
members). This is what data hiding is in practice.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to
the class members, i.e., they set some restrictions on the class members so that they
can’t be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
1. Public

2. Private

3. Protected

Note: If we do not specify any access modifiers for the members inside the class, then
by default the access modifier for the members will be Private. Understanding how to
use public, private, and protected access modifiers is essential.

Let us now look at each one of these access modifiers in detail:


1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be
accessed by other classes and functions too. The public members of a class can be
accessed from anywhere in the program using the direct member access operator (.)
with the object of that class.

2. Private: The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed directly by
any object or function outside the class. Only the member functions or the friend
functions/ friend class are allowed to access the private data members of the class.

The output of the above program is a compile time error because we are not
allowed to access the private data members of a class directly from outside the
class. Yet an access to obj.radius is attempted, but radius being a private data
member, we obtained the above compilation error.

However, we can access the private data members of a class indirectly using the public
member functions of the class.

3. Protected: The protected access modifier is similar to the private access modifier
in the sense that it can’t be accessed outside of its class unless with the help of a
friend class. The difference is that the class members declared as Protected can be
accessed by any subclass (derived class) of that class as well. Note: This access
through inheritance can alter the access modifier of the elements of base class in
derived class depending on the mode of Inheritance.
4.What is a Constructor? (With Types Including Copy
Constructor).
Ans= 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: No parameters. They are used to create an object with
default values.
2. Parameterized Constructor: Takes parameters. Used to create an object with
specific initial values.
3. Copy Constructor: Takes a reference to another object of the same class. Used to
create a copy of an object.
4. Move Constructor: Takes an rvalue reference to another object. Transfers
resources from a temporary object.
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. A copy constructor is a type of constructor that creates an object using another
object of the same class. 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.
Example:
1
#include <iostream>
2
using namespace std;
3

4
// Create a demo class
5
class A {
6
public:
7
int x;
8
};
9

10
int main() {
11

12
// Creating an a1 object
13
A a1;
14
a1.x = 10;
15
cout << "a1's x = " << a1.x << endl;
16

17
// Creating another object using a1
18
// Copy Constructor Calling
19
A a2(a1);
20
cout << "a2's x = " << a2.x;
21

22
return 0;
23
}

Output
a1's x = 10
a2's x = 10
Explanation: In this example, we were able to construct a2 object using already
created object a1.
But wait a minute, we haven’t defined any constructor here, so why we were able to
create an object using already existing object of same class? Actually, C++ compiler
by default create a simple copy constructor when it is not explicitly defined by the
programmer. It is called implicit copy constructor, and it will copy the bases and
members of an object in the same order that they were present in the code.
C++ also allows programmers to create their own version of copy constructor known
as user defined or explicit copy constructor.
Syntax of User Defined Copy Constructor
Copy constructor takes a reference to an object of the same class as an argument:
className (const ClassName &obj) {
// Copy logic
……
}

.
4. Move Constructor
The move constructor is a recent addition to the family of constructors in C++. It is
like a copy constructor that constructs the object from the already existing objects.,
but instead of copying the object in the new memory, it makes use of move
semantics to transfer the ownership of the already created object to the new object
without creating extra copies.
It can be seen as stealing the resources from other objects.
Syntax of Move Constructor
className (className&& obj) {
// body of the constructor
}
The move constructor takes the rvalue reference of the object of the same class and
transfers the ownership of this object to the newly created object.
Like a copy constructor, the compiler will create a move constructor for each class
that does not have any explicit move constructor.
Conclusion
In summary, constructors in C++ are special methods that initialize objects of a class.
They can be default (with no arguments), parameterized (with specific values), copy
constructors (for deep copying), or move constructors (for resource transfer).
Understanding these types and their usage is essential for effective object
initialization and management.

5.What is Inheritance? Explain different types with examples.


The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object
Oriented Programming in C++. In this article, we will learn about inheritance in C++,
its modes and types along with the information about how it affects different
properties of the class.
Syntax of Inheritance in C++
class derived_class_name : access-specifier base_class_name
{
// body ....
};
where,
• class: keyword to create a new class
• derived_class_name: name of the new class, which will inherit the base class
• access-specifier: Specifies the access mode which can be either of private, public
or protected. If neither is specified, private is taken as default.
• base-class-name: name of the base class.
Note: A derived class doesn’t inherit access to private data members. However, it
does inherit a full parent object, which contains any private members which that
class declares.
Example:
class ABC : private XYZ {...} // private derivation
class ABC : public XYZ {...} // public derivation
class ABC : protected XYZ {...} // protected derivation
class ABC: XYZ {...} // private derivation by default
To better understand inheritance and other OOP principles, enroll in our Complete
C++ Course, which breaks down inheritance, polymorphism, and encapsulation in
C++.
Examples of Inheritance in C++
The following programs demonstrate how to implement inheritance in our C++
programs.
Modes of Inheritance in C++
Mode of inheritance controls the access level of the inherited members of the base
class in the derived class. In C++, there are 3 modes of inheritance:
• Public Mode
• Protected Mode
• Private Mode
Public Inheritance Mode
If we derive a subclass from a public base class. Then the public member of the base
class will become public in the derived class and protected members of the base
class will become protected in the derived class.
Example:
class ABC : public XYZ {...} // public derivation
Protected Inheritance Mode
If we derive a subclass from a Protected base class. Then both public members and
protected members of the base class will become protected in the derived class.
Example:
class ABC : protected XYZ {...} // protected derivation
Private Inheritance Mode
If we derive a subclass from a Private base class. Then both public members and
protected members of the base class will become private in the derived class. They
can only be accessed by the member functions of the derived class.
Private mode is the default mode that is applied when we don’t specify any mode.
Example:
class ABC : private XYZ {...} // private derivation
class ABC: XYZ {...} // private derivation by default
Note: The private members in the base class cannot be directly accessed in the
derived class, while protected and public members can be directly accessed. To
access or update the private members of the base class in derived class, we have to
use the corresponding getter and setter functions of the base class or declare the
derived class as friend class.
Types Of Inheritance in C++
The inheritance can be classified on the basis of the relationship between the
derived class and the base class. In C++, we have 5 types of inheritances:
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one base
class is inherited by one derived class only.
Syntax
class subclass_name : access_mode base_class
{
// body of subclass
};

Example:

class A
{
... .. ...
};
class B: public A
{
... .. ...
};
2. Multiple Inheritance
Multiple Inheritance is a feature of C++ where a class can inherit from more than
one class. i.e one subclass is inherited from more than one base class.
Syntax
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access
mode for every base class must be specified and can be different.
Example:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A, public B
{
... ... ...
};
3. Multilevel Inheritance
In 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.
Syntax
class derived_class1: access_specifier base_class
{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....
example

class C
{
... .. ...
};
class B : public C
{
... .. ...
};
class A: public B
{
... ... ...
};

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

class derived_class1: access_specifier base_class


{
... .. ...
}
class derived_class2: access_specifier base_class
{
... .. ...
}

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

5. Hybrid Inheritance

Hybrid Inheritance is implemented by combining more than one type of inheritance.


For example: Combining Hierarchical inheritance 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.

Example:

Below image shows one of the combinations of hierarchical and multiple inheritances:

Constructors and Destructors in Inheritance

Constructors and Destructors are generally defined by the programmer and if not, the
compiler automatically creates them so they are present in every class in C++. Now,
the question arises what happens to the constructor and destructor when a class is
inherited by another class.

In C++ inheritance, the constructors and destructors are not inherited by the derived
class, but we can call the constructor of the base class in derived class.
• The constructors will be called by the complier in the order in which they are
inherited. It means that base class constructors will be called first, then derived
class constructors will be called.

• The destructors will be called in reverse order in which the compiler is declared.

• We can also call the constructors and destructors manually in the derived class.

Polymorphism in Inheritance
In Inheritance, we can redefine the base class member function in the derived class. This type of
inheritance is called Function Overriding. Generally, in other programming languages, function
overriding is runtime polymorphism but in C++, we can do it at both runtime and complile time.
For runtime polymorphism, we have to use the virtual functions.
Example

6.What is method overloading and how it is performed?


Method overloading is a feature in many programming languages that allows multiple
functions to have the same name but different parameters. This enhances code
readability and flexibility by allowing a function to perform different tasks based on
the input parameters. However, C does not support method overloading directly due to
its compiler limitations1.

Achieving Method Overloading in C

Although C does not support method overloading natively, similar functionality can be
achieved using various techniques. One common approach is to use a void * type
pointer as an argument to the function, along with another argument indicating the
actual data type of the first argument. Here is an example:

#include <stdio.h>

typedef struct {

int a;

} Struct1;
typedef struct {

double b;

} Struct2;

void foo(void *arg1, int arg2) {

if (arg2 == 0) {

Struct1 *struct1PtrVar = (Struct1 *)arg1;

printf("Struct1: %d\n", struct1PtrVar->a);

} else if (arg2 == 1) {

Struct2 *struct2PtrVar = (Struct2 *)arg1;

printf("Struct2: %f\n", struct2PtrVar->b);

} else {

// Error Handling

printf("Unknown type\n");

int main() {

Struct1 s1 = {10};

Struct2 s2 = {20.5};

foo(&s1, 0); // Here, arg1 is a pointer to Struct1

foo(&s2, 1); // Here, arg1 is a pointer to Struct2


return 0;

In this example, the foo function uses a void * pointer to accept different types of
arguments, and the second argument (arg2) indicates the type of the first argument.
Inside the function, the actual data type is determined by typecasting based on the
value of arg21.

Limitations and Considerations

While this approach allows for some level of method overloading, it has limitations
and requires careful handling of pointers and typecasting. Additionally, it may not be
as efficient or straightforward as native method overloading in languages like C++ or
Java2.

Another approach to achieve similar functionality is to use variadic functions


(varargs), which can accept a variable number of arguments. However, this also
requires careful handling and type checking to ensure correct behavior1.

In conclusion, while C does not support method overloading directly, similar


functionality can be achieved using techniques like void * pointers and variadic
functions. These approaches require careful handling and may not be as efficient as
native method overloading in other languages

7.Explain Friend Function. Write a program to demonstrate.

Data hiding is a fundamental concept of object-oriented programming. It restricts the


access of private members from outside of the class.

Similarly, protected members can only be accessed by derived classes and are
inaccessible from outside. For example,

class MyClass {

private:

int member1;
}

int main() {

MyClass obj;

// Error! Cannot access private members from here.

obj.member1 = 5;

However, there is a feature in C++ called friend functions that break this rule and allow
us to access member functions from outside the class.

Similarly, there is a friend class as well, which we will learn later in this tutorial.

friend Function in C++

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.

class className {

... .. ...

friend returnType functionName(arguments);

... .. ...

Example 1: Working of friend Function

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


#include <iostream>

using namespace std;

class Distance {

private:

int meter;

// friend function

friend int addFive(Distance);

public:

Distance() : meter(0) {}

};

// friend function definition

int addFive(Distance d) {

//accessing private members from the friend function

d.meter += 5;

return d.meter;

}
int main() {

Distance D;

cout << "Distance: " << addFive(D);

return 0;

Run Code

Output

Distance: 5

Here, addFive() is a friend function that can access both private and public data
members.

Though this example gives us an idea about the concept of a friend function, it doesn't
show any meaningful use.

A more meaningful use would be operating on objects of two different classes. That's
when the friend function can be very helpful.

8. What is dynamic memory allocation?

Dynamic memory allocation in C allows the size of a data structure, such as an array, to
be changed during runtime. This is particularly useful when the amount of memory
required is not known beforehand. C provides four standard library functions for
dynamic memory allocation: malloc(), calloc(), free(), and realloc(), all defined in
the <stdlib.h> header file12.

malloc()

The malloc() function allocates a single block of memory of a specified size and returns
a pointer to the beginning of the block. The memory is not initialized, so it contains
garbage values. If the allocation fails, it returns a NULL pointer.

Syntax:

ptr = (cast-type*) malloc(byte-size);


Example:

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 5;

ptr = (int*) malloc(n * sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

} else {

printf("Memory successfully allocated using malloc.\n");

for (int i = 0; i < n; ++i) {

ptr[i] = i + 1;

printf("The elements of the array are: ");

for (int i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

free(ptr);
return 0;

calloc()

The calloc() function allocates memory for an array of elements, initializes them to
zero, and returns a pointer to the memory. It takes two parameters: the number of
elements and the size of each element.

Syntax:

ptr = (cast-type*) calloc(n, element-size);

Example:

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 5;

ptr = (int*) calloc(n, sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

} else {

printf("Memory successfully allocated using calloc.\n");

for (int i = 0; i < n; ++i) {

ptr[i] = i + 1;
}

printf("The elements of the array are: ");

for (int i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

free(ptr);

return 0;

free()

The free() function deallocates the memory previously allocated by malloc(), calloc(),
or realloc(). This helps to prevent memory leaks by freeing up unused memory.

Syntax:

free(ptr);

Example:`

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr = (int*) malloc(5 * sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

}
free(ptr);

printf("Memory successfully freed.\n");

return 0;

realloc()

The realloc() function changes the size of previously allocated memory. It can increase
or decrease the size of the memory block while preserving the existing data.

Syntax:

ptr = realloc(ptr, newSize);

Example:

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

int n = 5;

ptr = (int*) calloc(n, sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

} else {

printf("Memory successfully allocated using calloc.\n");

for (int i = 0; i < n; ++i) {


ptr[i] = i + 1;

n = 10;

ptr = (int*) realloc(ptr, n * sizeof(int));

if (ptr == NULL) {

printf("Reallocation failed.\n");

exit(0);

printf("Memory successfully re-allocated using realloc.\n");

for (int i = 5; i < n; ++i) {

ptr[i] = i + 1;

printf("The elements of the array are: ");

for (int i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

free(ptr);

return 0;

Dynamic memory allocation provides flexibility and efficient memory usage, especially
when the memory requirements are not known in advance123. It is essential to manage
memory properly to avoid leaks and ensure optimal performance.
9. Explain Operator Overloading. Write a program to demonstrate.

C++ 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. Operator overloading is a compile-time
polymorphism. For example, we can overload an operator ‘+’ in a class like String so
that we can concatenate two strings by just using +. Other example classes where
arithmetic operators may be overloaded are Complex Numbers, Fractional Numbers,
Big integers, etc.

Example:

int a;
float b,sum;
sum = a + b;

Here, variables “a” and “b” are of types “int” and “float”, which are built-in data types.
Hence the addition operator ‘+’ can easily add the contents of “a” and “b”. This is
because the addition operator “+” is predefined to add variables of built-in data type
only.

Implementation:

// C++ Program to Demonstrate the

// working/Logic behind Operator

// Overloading

class A {

statements;

};

int main()

A a1, a2, a3;


a3 = a1 + a2;

return 0;

In this example, we have 3 variables “a1”, “a2” and “a3” of type “class A”. Here we are
trying to add two objects “a1” and “a2”, which are of user-defined type i.e. of type
“class A” using the “+” operator. This is not allowed, because the addition operator “+”
is predefined to operate only on built-in data types. But here, “class A” is a user-
defined type, so the compiler generates an error. This is where the concept of
“Operator overloading” comes in.

Now, if the user wants to make the operator “+” add two class objects, the user has to
redefine the meaning of the “+” operator such that it adds two class objects. This is
done by using the concept of “Operator overloading”. So the main idea behind
“Operator overloading” is to use C++ operators with class variables or class objects.
Redefining the meaning of operators really does not change their original meaning;
instead, they have been given additional meaning along with their existing ones.

Example of Operator Overloading in C++

// C++ Program to Demonstrate

// Operator Overloading

#include <iostream>

using namespace std;


5

class Complex {

private:

int real, imag;

10

public:

11

Complex(int r = 0, int i = 0)

12

13

real = r;

14

imag = i;

15

16
17

// This is automatically called when '+' is used with

18

// between two Complex objects

19

Complex operator+(Complex const& obj)

20

21

Complex res;

22

res.real = real + obj.real;

23

res.imag = imag + obj.imag;

24

return res;

25

26

void print() { cout << real << " + i" << imag << '\n'; }

27

};
28

29

int main()

30

31

Complex c1(10, 5), c2(2, 4);

32

Complex c3 = c1 + c2;

33

c3.print();

34

Output

12 + i9

10. Write short notes:

a. Virtual Function

b. Access Specifier

c. Static members

d. 'new' and 'delete' keyword.

e. Abstract class
f. Command Line arguments.

g. Inline Function

ans A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined (overridden) by a derived class. When
you refer to a derived class object using a pointer or a reference to the base class, you
can call a virtual function for that object and execute the derived class’s version of the
method.
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
• 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 for Virtual Functions
The rules for the virtual functions in C++ are as follows:
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class
type to achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the
derived class.
5. They are always defined in the base class and overridden in a derived class. It is
not mandatory for the derived class to override (or re-define the virtual
function), in that case, the base class version of the function is used.
6. A class may have a virtual destructor but it cannot have a virtual constructor.

B ans=Access modifiers are used to implement an important aspect of Object-Oriented


Programming known as Data Hiding. Consider a real-life example:
The Research and Analysis Wing (R&AW), having 10 core members, has come into
possession of sensitive confidential information regarding national security. Now we
can correlate these core members to data members or member functions of a class,
which in turn can be correlated to the R&A Wing. These 10 members can directly
access the confidential information from their wing (the class), but anyone apart from
these 10 members can’t access this information directly, i.e., outside functions other
than those prevalent in the class itself can’t access the information (that is not entitled
to them) without having either assigned privileges (such as those possessed by a
friend class or an inherited class, as will be seen in this article ahead) or access to one
of these 10 members who is allowed direct access to the confidential information
(similar to how private members of a class can be accessed in the outside world
through public member functions of the class that have direct access to private
members). This is what data hiding is in practice.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to
the class members, i.e., they set some restrictions on the class members so that they
can’t be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected
Note: If we do not specify any access modifiers for the members inside the class, then
by default the access modifier for the members will be Private. Understanding how to
use public, private, and protected access modifiers is essential.
Let us now look at each one of these access modifiers in detail:
1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be
accessed by other classes and functions too. The public members of a class can be
accessed from anywhere in the program using the direct member access operator (.)
with the object of that class.

C ans Static Member in C++


Static members of a class are not associated with the objects of the class. Just like a
static variable once declared is allocated with memory that can’t be changed every
object points to the same memory. To know more about the topic refer to a static
Member in C++.
Example:
class Person{
static int index_number;
};
Once a static member is declared it will be treated as same for all the objects
associated with the class.
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.

D ans
new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient
memory is available, a new operator initializes the memory and returns the address of the
newly allocated and initialized memory to the pointer variable.
Syntax to use new operator
pointer-variable = new data-type;
Here, the pointer variable is the pointer of type data-type. Data type could be any built-in
data type including array or any user-defined data type including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;

delete operator
Since it is the programmer’s responsibility to deallocate dynamically allocated
memory, programmers are provided delete operator in C++ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, the pointer variable is the pointer that points to the data object created by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer variable, use the following
form of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;

Example:
// It will free the entire array
// pointed by p.
delete[] p;

e.Abstract class
C++ Abstract Class
123

An abstract class in C++ is a class that cannot be instantiated directly and is used to
represent general concepts from which more specific classes can be derived. Abstract
classes are typically used as base classes for other classes and contain at least one
pure virtual function. A pure virtual function is a virtual function that is declared by
assigning 0 in its declaration, indicating that the function must be overridden by any
derived class12.
Example of Abstract Class and Pure Virtual Function
Here is an example of an abstract class with a pure virtual function:
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() = 0; // Pure virtual function
};

class Derived : public Base {


public:
void show() override {
cout << "Derived class implementation of show()" << endl;
}
};

int main() {
// Base b; // Error: cannot declare variable 'b' to be of abstract type 'Base'
Derived d;
d.show(); // Output: Derived class implementation of show()
return 0;
}
In this example, Base is an abstract class because it has a pure virtual function show().
The Derived class inherits from Base and provides an implementation for
the show() function, making it a concrete class2.
Key Points
1. Abstract Class Definition: An abstract class is defined by declaring at least one
pure virtual function using the syntax virtual void functionName() = 0;13.
2. Instantiation: Objects of an abstract class cannot be created directly. However,
pointers and references to an abstract class type can be used13.
3. Derived Classes: Any class that inherits from an abstract class must implement all
pure virtual functions of the base class. Otherwise, the derived class will also be
considered abstract2.
4. Constructors and Destructors: Abstract classes can have constructors and
destructors. Pure virtual destructors must have a definition, even if it is empty3.

You might also like