C++ Own Answer
C++ Own Answer
#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.
Introduction to OOP
Benefits of OOP:
• Reusability: OOP allows developers to reuse classes and objects across projects,
saving time and effort.
1. Abstraction
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
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.
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
Example
Example explained
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
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.
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.
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 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
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 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
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;
if (arg2 == 0) {
} else if (arg2 == 1) {
} else {
// Error Handling
printf("Unknown type\n");
int main() {
Struct1 s1 = {10};
Struct2 s2 = {20.5};
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.
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.
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;
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.
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 {
... .. ...
... .. ...
class Distance {
private:
int meter;
// friend function
public:
Distance() : meter(0) {}
};
int addFive(Distance d) {
d.meter += 5;
return d.meter;
}
int main() {
Distance 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.
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:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
if (ptr == NULL) {
exit(0);
} else {
ptr[i] = i + 1;
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:
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
if (ptr == NULL) {
exit(0);
} else {
ptr[i] = i + 1;
}
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() {
if (ptr == NULL) {
exit(0);
}
free(ptr);
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:
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
if (ptr == NULL) {
exit(0);
} else {
n = 10;
if (ptr == NULL) {
printf("Reallocation failed.\n");
exit(0);
ptr[i] = i + 1;
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++ 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:
// Overloading
class A {
statements;
};
int main()
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.
// Operator Overloading
#include <iostream>
class Complex {
private:
10
public:
11
Complex(int r = 0, int i = 0)
12
13
real = r;
14
imag = i;
15
16
17
18
19
20
21
Complex res;
22
23
24
return res;
25
26
void print() { cout << real << " + i" << imag << '\n'; }
27
};
28
29
int main()
30
31
32
Complex c3 = c1 + c2;
33
c3.print();
34
Output
12 + i9
a. Virtual Function
b. Access Specifier
c. Static members
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.
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
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
};
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.