0% found this document useful (0 votes)
27 views

C++ Imp Questions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

C++ Imp Questions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Define ‘std’?

‘std’ is also known as Standard or it can be interpreted as a namespace. The


command “using namespace std” informs the compiler to add everything
under the std namespace and inculcate them in the global namespace. This
all inculcation of global namespace benefits us to use “cout” and “cin”
without using “std::_operator_”.

4. What are references in C++?


When a variable is described as a reference it becomes an alias of the
already existing variable. In simple terms, a referenced variable is
another named variable of an existing variable keeping in mind that
changes made in the reference variable will be reflected in the
already existing variable. A reference variable is preceded with
a ‘&’ symbol.
Syntax:
int GFG = 10;

// reference variable
int& ref = GFG;

5. What do you mean by Call by Value and Call by Reference?


In this programming language to call a function we have 2
methods: Call by Value and Call by Reference
Call by Value Call by Reference

A variable itself is passed


A copy of a variable is passed.
fundamentally.

Calling a function by sending the Calling a function by sending the


values by copying variables. address of the passed variable.

The changes made in the The changes made in the functions


function are never reflected can be seen outside the function
outside the function on the on the passed function. In short,
Call by Value Call by Reference

variable. In short, the original


the original value is altered in Call
value is never altered in Call by
by reference.
Value.

Passed actual and formal Passed actual and formal


parameters are stored in parameters are stored in the same
different memory locations. memory location. Therefore,
Therefore, making Call by Value making Call by Reference a little
a little memory insufficient more memory efficient.

Define token in C++


A token is the smallest individual element of a program that is
understood by a compiler. A token comprises the following:
1. Keywords – That contain a special meaning to the compiler
2. Identifiers – That hold a unique value/identity
3. Constants – That never change their value throughout the
program
4. Strings – That contains the homogenous sequence of data
5. Special Symbols – They have some special meaning and
cannot be used for another purpose; eg: [] () {}, ; * = #
6. Operators – Who perform operations on the operand

What is the difference between struct and class?


Struct Class

Members of the class can be in


Members of the struct are
private, protected, and public
always by default public mode
modes.
Struct Class

Classes are of reference type. It


Structures are of the value type.
holds a reference of an object in
They only hold value in memory.
memory.

The memory in structures is The memory in classes is stored as


stored as stacks heaps.

What is the difference between reference and pointer?


Reference Pointer

The value of a reference cannot The value of a pointer can be


be reassigned reassigned

It can never hold a null value as It can hold or point at a null value
it needs an existing value to and be termed as a nullptr or null
become an alias of pointer

It cannot work with arrays It can work with arrays

To access the members of To access the members of


class/struct it uses a ‘ . ‘ class/struct it uses a ‘ -> ‘

The memory location of The memory location of a pointer


reference can be accessed easily cannot be accessed easily as we
or it can be used directly have to use a dereference ‘ * ‘
What is the difference between function overloading and
operator overloading?
Function Overloading Operator Overloading

It is basically defining a function


It is basically giving practice of
in numerous ways such that
giving a special meaning to the
there are many ways to call it or
existing meaning of an operator or
in simple terms you have
in simple terms redefining the pre-
multiple versions of the same
redefined meaning
function

Parameterized Functions are a


Polymorphism is a good example of
good example of Function
an operator overloading as an
Overloading as just by changing
object of allocations class can be
the argument or parameter of a
used and called by different classes
function you make it useful for
for different purposes
different purposes

Example of Function
Example of Operator Overloading:
Overloading:
1. int GFG() = X() + Y();
1. int GFG(int X, int Y);
2. int GFG() = X() – Y();
2. int GFG(char X, char Y);

What is the difference between an array and a list?


Arrays Lists

Array are contiguous memory Lists are classic individual elements


locations of homogenous data that are linked or connected to each
types stored in a fixed location other with the help of pointers and
or size. do not have a fixed size.

Arrays are static in nature. Lists are dynamic in nature


Arrays Lists

Uses more memory as it has to store


Uses less memory than linked
the value and the pointer memory
lists.
location

What is the difference between a while loop and a do-while loop?


While Loop do-while Loop

While loop is also termed an entry- The do-while loop is termed


controlled loop an exit control loop

Even if the condition is not


If the condition is not satisfied the
satisfied the statements
statements inside the loop will not
inside the loop will execute
execute
for at least one time

Example of a do-while loop:


Example of a while loop: do {
while(condition) statements to be executed;
{statements to be executed;}; } while(condition or
expression);

Discuss the difference between prefix and postfix?


prefix postfix

It simply means putting the It simply means putting the


operator before the operand operator after the operand
prefix postfix

It executes itself before ‘; ‘ It executes itself after ‘; ‘

Associativity of prefix ++ is right Associativity of postfix ++ is left


to left to right

What is the difference between new and malloc()?


new malloc()

new is an operator which malloc is a function that returns


performs an operation and accepts values

new calls the constructors malloc cannot call a constructor

new is faster than malloc as it is malloc is slower than new as it is


an operator a function

new returns the exact data type malloc returns void*

What is the difference between virtual functions and pure virtual


functions?
Virtual Function Pure Virtual Function

A Virtual Function is a A Pure Virtual Function is a member


member function of a base function of a base class that is only
class that can be redefined in declared in a base class and defined
Virtual Function Pure Virtual Function

in a derived class to prevent it from


another derived class.
becoming an abstract class.

A virtual Function has its There is no definition in Pure Virtual


definition in its respective Function and is initialized with a pure
base class. specifier (= 0).

The base class has a virtual A base class having pure virtual
function that can be function becomes abstract that cannot
represented or instanced; In be represented or instanced; In simple
simple words, its object can words, it means its object cannot be
be made. made

16. What are classes and objects in C++?


A class is a user-defined data type where all the member functions
and data members are tailor-made according to demands and
requirements in addition to which these all can be accessed with the
help of an object. To declare a user-defined data type we use a
keyword class.
An object is an instance of a class and an entity with value and state;
In simple terms, it is used as a catalyst or to represent a class
member. It may contain different parameters or none.
Note: A class is a blueprint that defines functions which are used by
an object. is a blueprint that defines functions which are use

d What are the various OOPs concepts in C++?


 Classes: It is a user-defined datatype
 Objects: It is an instance of a class
 Abstraction: It is a technique of showing only necessary
details
 Encapsulation: Wrapping of data in a single unit
 Inheritance: The capability of a class to derive properties
and characteristics from another class
 Polymorphism: Polymorphism is known as many forms of
the same thing

An
When should we use multiple inheritance?
Multiple inheritances mean that a derived class can inherit two or
more base/parent classes. It is useful when a derived class needs to
combine numerous attributes/contracts and inherit some, or all, of the
implementation from these attributes/contracts. To take a real-life
example consider your Parents where Parent A is your DAD Parent B
is your MOM and Chid C is you.

What is virtual inheritance?


Virtual inheritance is a technique that ensures only one copy of a
base class’s member variables is inherited by grandchild-derived
classes. Or in simple terms, virtual inheritance is used when we are
dealing with a situation of multiple inheritances but want to prevent
multiple instances of the same class from appearing in the inheritance
hierarchy.

. 22. What is polymorphism in C++?


Polymorphism is known as many forms of the same thing. In simple
terms, we can say that Polymorphism is the ability to display a
member function in multiple forms depending on the type of object
that calls them.
In other words, we can also say that a man can be an employee to
someone, a son of someone, a father of someone, and a husband of
someone; this is how polymorphism can be projected in real life.
There is 2 type of polymorphism:
1. Compile Time Polymorphism
 Function Overloading
 Operator Overloading
2. Run Time Polymorphism
 Function Overriding
 Virtual Function
What is polymorphism in C++?
Polymorphism is known as many forms of the same thing. In simple
terms, we can say that Polymorphism is the ability to display a
member function in multiple forms depending on the type of object
that calls them.
In other words, we can also say that a man can be an employee to
someone, a son of someone, a father of someone, and a husband of
someone; this is how polymorphism can be projected in real life.
There is 2 type of polymorphism:
1. Compile Time Polymorphism
 Function Overloading
 Operator Overloading
2. Run Time Polymorphism
 Function Overriding
 Virtual Function
To know more about it, refer to Polymorphism
23. What are the different types of polymorphism in C++?
There is 2 type of polymorphism
Compile Time Polymorphism or Static Binding
This type of polymorphism is achieved during the compile time of the
program which results in it making a bit faster than Run time. Also,
Inheritance is not involved in it. It is comprised of 2 further
techniques:
Function Overloading: When there are multiple functions with the
same name but different parameters then this is known as function
overloading.
C++
// same name different arguments
int GFG() {}
int GFG(int a) {}
float GFG(double a) {}
int GFG(int a, double b) {}
Operator Overloading: It is basically giving practice of giving a
special meaning to the existing meaning of an operator or in simple
terms redefining the pre-redefined meaning
C++
class GFG {
// private and other modes
statements public returnType
operator symbol(arguments){ statements } statements
};

Run-Time Polymorphism or Late Binding


Run-time polymorphism takes place when functions are invoked
during run time.

Function Overriding: Function overriding occurs when a base class


member function is redefined in a derived class with the same
arguments and return type.
C++
// C++ program to demonstrate
// Function overriding
#include
<iostream> using namespace std;
class GFG {
public:
virtual void display()
{
cout << "Function of base class" << endl;
}
};
class derived_GFG : public GFG {
public:
void display()
{
cout << "Function of derived class" << endl;
}
};
int main()
{
derived_GFG dg;
dg.display();
return 0;
}
Output:
Function of derived class
Compare compile-time polymorphism and Runtime
polymorphism
Compile-Time
Polymorphism Runtime Polymorphism

It is also termed static binding It is also termed Dynamic binding


and early binding. and Late binding.

It is slow as compared to compile-


It is fast because execution is
time because execution is known at
known early at compile time.
runtime.

It is achieved by function
It is achieved by virtual functions
overloading and operator
and function overriding
overloading.

Explain the constructor in C++.


A constructor is a special type of member function of a class, whose
name is the same as that of the class by whom it is invoked and
initializes value to the object of a class.
There are 3 types of constructors:
A. Default constructor: It is the most basic type of constructor which
accepts no arguments or parameters. Even if it is not called the
compiler calls it automatically when an object is created.
Example:
C++
class Class_name {

public:

Class_name() { cout << "I am a default constructor"; }

};
B. Parameterized constructor: It is a type of constructor which accepts
arguments or parameters. It has to be called explicitly by passing
values in the arguments as these arguments help initialize an object
when it is created. It also has the same name as that of the class.

Also, It is used to overload constructors.


Example:
C++
// CPP program to demonstrate

// parameterized constructors

#include

<iostream> using namespace std;

class GFG {

private:

int x, y;

public:

// Parameterized Constructor

GFG(int x1, int y1)

x = x1;

y = y1;

int getX() { return x; }

int getY() { return y; }

};

int main()

// Constructor called

GFG G(10, 15);

// Access values assigned by constructor


cout << "G.x = " << G.getX() << ", G.y = " << G.getY();

return 0;

Output
G.x = 10, G.y = 15

. Copy Constructor: A copy constructor is a member function that


initializes an object using another object of the same class. Also, the
Copy constructor takes a reference to an object of the same class as
an argument.
Example:
C++
Sample(Sample& t) { id = t.id; }

What are destructors in C++?


Destructors are members of functions in a class that delete an object
when an object of the class goes out of scope. Destructors have the
same name as the class preceded by a tilde (~) sign. Also,
destructors follow a down-to-top approach, unlike constructors which
follow a top-to-down.
Syntax:
~constructor_name(); // tilde sign signifies that it is a
destructor

For more information, refer to Destructor.


27. What is a virtual destructor?
When destroying instances or objects of a derived class using a base
class pointer object, a virtual destructor is invoked to free up memory
space allocated by the derived class object or instance.
Virtual destructor guarantees that first the derived class’ destructor is
called. Then the base class’s destructor is called to release the space
occupied by both destructors in the inheritance class which saves us
from the memory leak. It is advised to make your destructor virtual
whenever your class is polymorphic.
28. Is destructor overloading possible? If yes then explain
and if no then why?
The simple answer is NO we cannot overload a destructor. It is
mandatory to only destructor per class in C++. Also to mention,
Destructor neither take arguments nor they have a parameter that
might help to overload.

29. Which operations are permitted on pointers?


Pointers are the variables that are used to store the address location
of another variable. Operations that are permitted to a pointer are:
7. Increment/Decrement of a Pointer
8. Addition and Subtraction of integer to a pointer
9. Comparison of pointers of the same type

30. What is the purpose of the “delete” operator?


The delete operator is used to delete/remove all the
characteristics/properties from an object by deallocating its memory;
furthermore, it returns true or false in the end. In simple terms, it
destroys or deallocates array and non-array(pointer) objects which are
created by new expressions.
C++
int GFG = new int[100];

// uses GFG for deletion

delete[] GFG;

How delete [] is different from delete?


delete[] delete

It is used for deleting a whole array It is used to delete only one


delete[] delete

single pointer

It is used for deleting the objects It is used for deleting the objects
of new[]; By this, we can say of new; By this, we can say
that delete[] is used to delete an that delete is used to delete a
array of objects single object

It can call as many destructors it It can only call the destructor of


wants a class once

What do you know about friend class and friend function?


A friend class is a class that can access both the protected and
private variables of the classes where it is declared as a friend.
Example of friend class:
C++
class Class_1st {

// ClassB is a friend class of ClassA

friend class Class_2nd;

statements;

} class Class_2nd {

statements;

A friend function is a function used to access the private, protected,


and public data members or member functions of other classes. It is
declared with a friend keyword. The advantage of a friend function is
that it is not bound to the scope of the class and once it is declared in
a class, furthermore to that, it cannot be called by an object of the
class; therefore it can be called by other functions. Considering all the
mentioned points we can say that a friend function is a global
function.
Example of friend function:
C++
class GFG {

statements;

friend dataype function_Name(arguments);

statements;

} OR class GFG {

statements' friend int divide(10, 5);

statements;

What is an Overflow Error?


Overflow Error occurs when the number is too large for the data type
to handle. In simple terms, it is a type of error that is valid for the
defined but exceeds used the defined range where it should
coincide/lie.
For example, the range of int data type is –
2,147,483,648 to 2,147,483,647 and if we declare a variable of
size 2,247,483,648 it will generate a overflow error.
34. What does the Scope Resolution operator do?
A scope resolution operator is denoted by a ‘::‘ symbol. Just like its
name this operator resolves the barrier of scope in a program. A
scope resolution operator is used to reference a member function or a
global variable out of their scope furthermore to which it can also
access the concealed variable or function in a program.
Scope Resolution is used for numerous amounts of tasks:
10. To access a global variable when there is a local variable
with the same name
11. To define the function outside the class
12. In case of multiple inheritances
13. For namespace

What are the C++ access modifiers?


The access restriction specified to the class members( whether it is
member function or data member) is known as access
modifiers/specifiers.
Access Modifiers are of 3 types:
14. Private – It can neither be accessed nor be viewed from
outside the class
15. Protected – It can be accessed if and only if the accessor is
the derived class
16. Public – It can be accessed or be viewed from outside the
class

Can you compile a program without the main function?


Yes, it is absolutely possible to compile a program without a main().
For example Use Macros that defines the main
C++
// C++ program to demonstrate the

// a program without main()

#include

<stdio.h>

#define fun main

int fun(void)

printf("Geeksforgeeks");

return 0;
}

What is STL?
STL is known as Standard Template Library, it is a library that provides
4 components like container, algorithms, and iterators.

Define inline function. Can we have a recursive inline


function in C++?
An inline function is a form of request not an order to a compiler
which results in the inlining of our function to the main function body.
An inline function can become overhead if the execution time of the
function is less than the switching time from the caller function to
called function. To make a function inline use the
keyword inline before and define the function before any calls are
made to the function.
Inline Function Explanation

Syntax:
inline data_type function_name()
{
Body;
}

The answer is No; It cannot be recursive.


An inline function cannot be recursive because in the case of an inline
function the code is merely placed into the position from where it is
called and does not maintain a piece of information on the stack
which is necessary for recursion.
Plus, if you write an inline keyword in front of a recursive function, the
compiler will automatically ignore it because the inline is only taken
as a suggestion by the compiler.
What is an abstract class and when do you use it?
An abstract class is a class that is specifically designed to be used as
a base class. An abstract class contains at least one pure virtual
function. You declare a pure virtual function by using a pure
specifier(= 0) in the declaration of a virtual member function in the
class declaration
You cannot use an abstract class as a parameter type, a function
return type, or the type of an explicit conversion, nor can you declare
an object of an abstract class. However, it can be used to declare
pointers and references to an abstract class.
An abstract class is used if you want to provide a common,
implemented functionality among all the implementations of the
component. Abstract classes will allow you to partially implement
your class, whereas interfaces would have no implementation for any
members whatsoever. In simple words, Abstract Classes are a good fit
if you want to provide implementation details to your children but
don’t want to allow an instance of your class to be directly
instantiated.
40. What are the static data members and static member
functions?
The static data member of a class is a normal data member but
preceded with a static keyword. It executes before main() in a
program and is initialized to 0 when the first object of the class is
created. It is only visible to a defined class but its scope is of a
lifetime.
Syntax:
static Data_Type Data_Member;

The static member function is the member function that is used to


access other static data members or other static member functions. It
is also defined with a static keyword. We can access the static
member function using the class name or class objects.
Syntax:
classname::function name(parameter);
What is the main use of the keyword “Volatile”?
Just like its name, things can change suddenly and unexpectantly; So
it is used to inform the compiler that the value may change anytime.
Also, the volatile keyword prevents the compiler from performing
optimization on the code. It was intended to be used when interfacing
with memory-mapped hardware, signal handlers, and machine code
instruction.

Define storage class in C++ and name some


Storage class is used to define the features(lifetime and visibility) of a
variable or function. These features usually help in tracing the
existence of a variable during the runtime of a program.
Syntax:
storage_class var_data_type var_name;

What is a mutable storage class specifier? How can they


be used?
Just like its name, the mutable storage class specifier is used only on
a class data member to make it modifiable even though the member
is part of an object declared as const. Static or const, or reference
members cannot use the mutable specifier. When we declare a
function as const, this pointer passed to the function becomes const.

Define the Block scope variable.


So the scope of a variable is a region where a variable is accessible.
There are two scope regions, A global and block or local.
A block scope variable is also known as a local scope variable. A
variable that is defined inside a function (like main) or inside a block
(like loops and if blocks) is a local variable. It can be used ONLY inside
that particular function/block in which it is declared. a block-scoped
variable will not be available outside the block even if the block is
inside a function.
What is the function of the keyword “Auto”?
The auto keyword may be used to declare a variable with a complex
type in a straightforward fashion. You can use auto to declare a
variable if the initialization phrase contains templates, pointers to
functions, references to members, etc. With type inference
capabilities, we can spend less time having to write out things the
compiler already knows. As all the types are deduced in the compiler
phase only, the time for compilation increases slightly but it does not
affect the runtime of the program.

Define namespace in C++.


Namespaces enable us to organize named items that would otherwise
have global scope into smaller scopes, allowing us to give them
namespace scope. This permits program parts to be organized into
distinct logical scopes with names. The namespace provides a place
to define or declare identifiers such as variables, methods, and
classes.
Or we could say that A namespace is a declarative zone that gives the
identifiers (names of types, functions, variables, and so on) within it a
scope. Namespaces are used to arrange code into logical categories
and to avoid name clashes, which might happen when you have many
libraries in your code base.

When is void() return type used?


The void keyword, when used as a function return type, indicates that
the function does not return a value. When used as a parameter list
for a function, void indicates that the function takes no parameters.
Non-Value Returning functions are also known as void functions.
They’re called “void” since they’re not designed to return anything.
True, but only partially. We can’t return values from void functions, but
we can certainly return something. Although void functions have no
return type, they can return values.
What is the difference between shallow copy and deep
copy?
Shallow Copy Deep Copy

In Shallow copy, a copy of the In Deep copy, the copy of the


original object is stored and only original object and the repetitive
the reference address is finally copies both are stored. In simple
copied. In simple terms, Shallow terms, Deep copy duplicates
copy duplicates as little as possible everything

A shallow copy of a collection is a


A deep copy of a collection is
copy of the collection structure,
two collections with all of the
not the elements. With a shallow
elements in the original
copy, two collections now share
collection duplicated.
individual elements.

Deep copy is comparatively


A shallow copy is faster
slower.

. Can we call a virtual function from a constructor?


Yes, we can call a virtual function from a constructor. But it can throw
an exception of overriding.
50. What are void pointers?
Just like its name a void pointer is a pointer that is not associated with
anything or with any data type. Nevertheless, a void pointer can hold
the address value of any type and can be converted from one data
type to another.
What is ‘this‘ pointer in C++?
this pointer enables every object to have access to its own address
through an essential pointer. All member functions take this pointer as
an implicit argument. this pointer may be used to refer to the calling
object within a member function.

17. this pointer is used to pass an object as a parameter to


another method.
18. Each object gets its own copy of the data member.
19. this pointer is used to declare indexers.

6.What is a Friend Class?


If a class is mentioned as a friend class to another class, then it can access
private and protected members of the other class.

Example:

class ClassA

private:

int a;

public:

ClassA()

a=10;

}
friend class FriendClass;

};

class FriendClass

private:

int b;

public:

void printClassA(ClassA& p)

cout<<“a=”<<p.a<<endl;

};

int main()

ClassA x;

FriendClass y;

y.printClassA();

return 0;

}
How can we access data members and member functions of a
class?
Dot-Operator( . ) helps to access data members and member functions of a
class.

9. What are the different types of inheritances?


There are different types of Inheritances-

20. Single inheritance


21. Multiple inheritance
22. Multi-level inheritance
23. Hierarchical inheritance
24. Hybrid inheritance

10. What is single inheritance?


In Single Inheritance, there is one derived class and one base class.

11. What is multilevel inheritance?


In multi-level inheritance, a class is derived from another derived class.

12. What is multiple inheritance?


This is when a class can be derived with more than one parent class.

13. What is hierarchical inheritance?


In hierarchical inheritance, many classes are derived from a single parent
class.

14. What is Hybrid Inheritance?


This is a combination of more than one inheritance, called hybrid inheritance.
It is also called virtual inheritance.

15. What is Template?


A template is a method for creating generic classes and generic functions.

16. What are access specifiers? What are the different types?
Access Specifiers define the accessibility of the members of the class. There
are three types of access specifiers:

25. Private – they are only accessible from inside of the class
26. Protected – like private specifiers but with an extra feature —
they are also accessible in derived classes
27. Public – they are accessible from both inside and outside the
class

17. What is a friend function?


A friend function to a class has access to all the members of the class, even
the private ones. We declare it outside the class.

18. What is a virtual function?


A virtual function is a function declared as a member function of a class, but
its definition is inside its derived class.

In how many ways is scope resolution used?


There are many ways to use scope resolution. Some use examples include:

28. To define a member function outside the class


29. To access data members of various classes while in inheritance

24. What are inline functions?


If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.

25. State the advantage of inline functions.


The inline functions increase the execution time of the program.

26. What is the difference between structure and class?


The variables of the structures are public, whereas the data member of the
class can be made as private.

27.What is the difference between a Local and a Global Variable?


A variable, when declared inside a code block, is called a local variable. We
can use this Local Variable only inside the code block. A global variable is
declared on the top of the program, before all the function definitions. It can
be accessed from anywhere in the code.

28.What is Compilation Time and Run Time?


The time Compiler takes for compiling a piece of code is called Compilation
Time of the code. The time taken by the program to run is called Run Time.

Empower your team. Lead the industry.


Get a subscription to a library of online courses and digital learning tools for
your organization with Udemy Business.

Request a demo

29.What is an Assignment Operator?


We use Assignment Operator for assigning value to a variable. It is denoted
by ‘=’.

30. What is function overriding?


Re-defining the member function of base class in the derived class is function
overriding.

31. Explain polymorphism.


If an object follows polymorphism, then it acts differently in different
conditions. There are two types of polymorphism:

30. Compile-time polymorphism (static binding)


31. Run-time polymorphism (dynamic binding)

32. What is inner class?


A nested class is a class which is declared inside another class.

33. Explain exception handling.


Exception handling is used when some exception is encountered in the
program. Three keywords are used for exception handling: try, catch, throw.

34. What is a destructor?


A destructor is a special member function. The Destructor destructs the
object and frees up space.

35. What is the use of a virtual destructor?


When we try to delete an object of the derived class using a base class
pointer, some undefined is encountered. To prevent this, a virtual destructor
should be defined in the base class.

36. What is the full form of STL?


STL stands for Standard Template Library.

37. Can we store duplicate values in a set?


No, we cannot store duplicate values in a set.

38. What type of data structure does map use?


Map uses BST as its data structure.

Courses by Abdul Bari

Learn JAVA Programming - Beginner to Master

Abdul Bari

4.6 (21,672)
Learn C++ Programming -Beginner to Advance- Deep Dive in C++

Abdul Bari

4.6 (26,751)
Mastering Data Structures & Algorithms using C and C++

Abdul Bari

4.6 (49,417)
Bestseller

Learn Python Programming - Beginner to Master

Abdul Bari

4.6 (5,008)
【AI 자막】 C 와 C++ 를 사용하여 데이터 구조 및 알고리즘 마스터하기

Abdul Bari

4.8 (17)
Courses by Abdul Bari
39. Can we initialize a vector with an array?
Yes, we can initialize a vector with an array.

40. What are some components of STL?


Some of the components of STL are iterators, containers, and algorithms.

41. How is ‘final’ used?


We add ‘final’ after the function name at the time of declaring to prevent
overriding in derived classes.

42. Write a C++ program for finding the length of a string using a
string iterator.

# include<iostream>

using namespace std;


int main()

string str="welcome";

string::iterator it;

int count=0;

for(it=str.begin();it!=str.end();it++)

cout<<"length is"<<count<<endl;

return 0;

43. Write a C++ program to change the given string to all upper
cases.

#include<iostream>

using namespace std;

int main()

string str="wELcoMe7";

for(int i=0;str[i]!='\0';i++)

if(str[i]>=97 && str[i]<=122)

{
str[i]=str[i]-32;

cout<<str<<endl;

return 0;

44. Write a C++ program to check if a string is a palindrome.

# include<iostream>

using namespace std;

int main()

string str="MADAM";

string rev="";

int len=(int)str.length();

rev.resize(len);

for(int i=0;j=len-1;i<len;i++;j--)

rev[i]=str[j];

rev[len]='\0';

if(str.compare(rev)==0)
cout<<"palindrome"<<endl;

else

cout<<"not a palindrome"<<endl;

return 0;

45. Write a C++ program to show function templates.

# include<iostream>

using namespace std;

template<class t>

t maxim(t a,t b)

return a>b?a:b;

int main()

cout<<maxim(12,14)<<endl;

cout<<maxim(2.3,1.4)<<endl;

cout<<maxim(2.3f,5.6f)<<endl;

return 0;

46. Write a C++ program to show pointers to an object.


# include<iostream>

using namespace std;

class rectangle

public:

int length;

int breadth;

int area()

return length*breadth;

int perimeter()

return perimeter 2*(length+breadth);

};

int main()

rectangle r1;

rectangle *ptr;

ptr=&r1;

ptr->length=10;
ptr->breadth=5;

cout<<ptr->area()<<endl;

cout<<ptr->perimeter()<<endl;

47. Write a C++ program showing operator overloading using


friend functions.

# include<iostream>

using namespace std;

class complex

private:

int real;

int img;

public:

complex(int r=0,i=0)

real=r;

img=i;

void display()

cout<<real<<"+i"<<img;
}

friend complex opreator+(complex c1,complex c2);

};

complex operator+(complex c1,complex c2)

complex temp;

temp.real=c1.real+c2.real;

temp.img=c1.img+v2.img;

return temp;

int main()

complex c1(5,3),c2(10,5),c3;

c3=c1+c2;

c3.display();

48. Write a C++ program using access specifiers.

# include<iostream>

using namespace std;

class base

{
public:

int a;

void display()

cout<<"display of base"<<a<<endl;

};

class derived:public base

public:

void show()

cout<<"show of derived"<<endl;

};

int main()

derived d;

d.a=100;

d.display();

d.show();

}
49. Write a C++ program showing inheritance.

# include<iostream>

using namespace std;

class rectangle

private:

int length;

int breadth;

public:

void setlength(int l)

if(l>0)

length=l;

else

length=1;

void setbreadth( int b)

if(b>0)

breadth=b;

else

breadth=1;
}

int getlength()

return length;

int getbreadth()

return breadth;

int area()

return length*breadth;

int perimeter()

return 2*(length+breadth);

};

int main()

rectangle r1;

r1.setlength(10);
r1.setbreadth(5);

cout<<"r1.area()<<endl;

cout<<"r1.perimeter()<<endl;

cout<<"length"<<r1.getlength()<<endl;

cout<<"breadth"<<r1.getbreadth()<<endl;

50. Write a C++ program showing polymorphism.

# include<iostream>

using namespace std;

class car

public:

virtual void start()

cout<<"car started"<<endl;

};

class innova:public car

public:

void start()
{

cout<<"innova started"<<endl;

};

class swift:public car

public:

void start()

cout<<"swift started"<<endl;

};

int main()

car *p=new innova();

ptr->start();

p=new swift();

ptr->start();

51. Write a C++ example program for nested classes.

# include<iostream>
using namespace std;

class outer

class inner;

public:

void fun()

i.display();

class inner

public:

void display()

cout<<"display of inner"<<endl;

};

inner i;

};

int main()

outer::inner i;
}

52. Write a C++ program to show throw and catch between


functions.

# include<iostream>

using namespace std;

int division(int a,int b)

if(b==0)

throw 1;

return a/b;

int main()

int x=10,y=2,z;

try

if(y==0)

throw 1;

z=x/y;

cout<<z<<endl;

catch(int e)
{

cout<<"division by zero"<<e<<endl;

cout<<"bye"<<endl;

53. Write a C++ program using vectors from STL.

# include<vector>

using namespace std;

int main()

vector<int> v={2,4,6,8,10};

v.push_back(20);

v.push_back(30);

vector<int>::iterator itr;

cout<<"using iterator"<<endl;

for(itr=v.begin();itr!=v.end();itr++)

cout<<++*itr<<endl;

cout<<"using for each loop"<<endl;

for(int x:v)

cout<<x<<endl;

}
54. Write a C++ program using map from STL.

# include<iostream>

# include<map>

using namespace std;

int main()

map<int,string> m;

m.insert(pair<int,string>(1,"john"));

m.insert(pair<int,string>(2,"ravi"));

m.insert(pair<int,string>(3,"khan"));

map<int,string>::iterator itr;

for(itr=m.begin();itr!=m.end();itr++)

cout<<itr->first<<" "<<itr->second<<endl;

map<int,string>::iterator itr1;

itr1=m.find(2);

cout<<"value found is"<<endl;

cout<<itr1->first<<" "<<itr1->second<<endl;

55. Write a C++ program showing the use of auto.


# include<iostream>

using namespace std;

float fun()

return 2.34f;

int main()

double d=12.3f;

int i=9;

auto x=2*d+i;

cout<<x;

56. Write a C++ program to show Lambda functions.

# include<iostream>

using namespace std;

int main()

[](int x,int y)

cout<<"sum is "<<x+y<<endl;
}

(10,30);

57. Write a C++ program for ellipses.

#include<iostream>

#include<cstdarg>

using namespace std;

int sum(int n,...)

va_list list;

va_start(list,n);

int x;

int s=0;

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

x=va_arg(list,int);

s+=x;

return s;

int main()
{

cout<<sum(3,10,20,30)<<endl;

cout<<sum(5,1,2,3,4,5)<<endl;

58. Write a C++ program to write in a file.

# include<iostream>

# include<fstream>

using namespace std;

int main()

ofstream ofs("my.text",ios::trunc);

ofs<<"john"<<endl;

ofs<<25<<endl;

ofs<<"cs"<<endl;

ofs.close();

59. Write a C++ program for reading a file.

# include<iostream>

# include<fstream>

using namespace std;


int main()

ifstream ifs;

ifs.open("my.txt");

if(ifs_open())

cout<<"file is opened"<<endl;

string name;

int roll;

string branch;

ifs>>name>>roll>>branch;

ifs.close();

cout<<"name"<<name<<endl;

cout<<"roll"<<rollendl;

cout<<"branch"<<branch<<endl;

You might also like