You are on page 1of 24

Frequently Asked Questions

1. What are the different data types present in C++?

The 4 data types in C++ are given below:

 Primitive Datatype(basic datatype). Example- char, short, int, float, long, double, bool,
etc.
 Derived datatype. Example- array, pointer, etc.
 Enumeration. Example- enum
 User-defined data types. Example- structure, class, etc.

2. What is the difference between C and C++?

The main difference between C and C++ are provided in the table below:

C C++
C++ is an object-oriented programming
C is a procedure-oriented programming language.
language.
Data is hidden by encapsulation to ensure
C does not support data hiding. that data structures and operators are used as
intended.
C is a subset of C++ C++ is a superset of C.
Function and operator overloading are not Function and operator overloading is
supported in C supported in C++
Namespace is used by C++, which avoids
Namespace features are not present in C
name collisions.
Functions can not be defined inside structures. Functions can be defined inside structures.
calloc() and malloc() functions are used for new operator is used for memory allocation
memory allocation and free() function is used for and deletes operator is used for memory
memory deallocation. deallocation.

3. What are class and object in C++?

A class is a user-defined data type that has data members and member functions. Data members
are the data variables and member functions are the functions that are used to perform operations
on these variables.

An object is an instance of a class. Since a class is a user-defined data type so an object can also
be called a variable of that data type.

A class is defined as-

class A{
private:
int data;
public:
void fun(){

}
};

Class and Object in C++

For example, the following is a class car that can have properties like name, color, etc. and they
can have methods like speed().

4. What is the difference between struct and class?

In C++ a structure is the same as a class except for a few differences like security. The difference
between struct and class are given below:

Structure Class
Members of the class are private by
Members of the structure are public by default.
default.
When deriving a struct from a class/struct, default access When deriving a class, default
specifiers for base class/struct are public. access specifiers are private.

5. What is operator overloading?


Operator Overloading is a very essential element to perform the operations on user-defined data
types. By operator overloading we can modify the default meaning to the operators like +, -, *, /,
<=, etc.

For example -

The following code is for adding two complex number using operator overloading-

class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}

6. What is polymorphism in C++?

Polymorphism in simple means having many forms. Its behavior is different in different
situations. And this occurs when we have multiple classes that are related to each other by
inheritance.

For example, think of a base class called a car that has a method called car brand(). Derived
classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation
of a cars

The two types of polymorphism in c++ are:

 Compile Time Polymorphism


 Runtime Polymorphism

Polymorphism in C++

7. Explain constructor in C++

The constructor is a member function that is executed automatically whenever an object is


created. Constructors have the same name as the class of which they are members so that
compiler knows that the member function is a constructor. And no return type is used for
constructors.

Example:

class A{
private:
int val;
public:
A(int x){ //one argument constructor
val=x;
}
A(){ //zero argument constructor
}
}
int main(){
A a(3);
return 0;
}

8. Tell me about virtual function

Virtual function is a member function in the base class that you redefine in a derived class. A
virtual function is declared using the virtual keyword. When the function is made virtual, C++
determines which function is to be invoked at the runtime based on the type of the object pointed
by the base class pointer.

9. Compare compile time polymorphism and Runtime polymorphism

The main difference between compile-time and runtime polymorphism is provided below:

Compile-time polymorphism Run time polymorphism


In this method, we would come to know at compile In this method, we come to know at run
time which method will be called. And the call is time which method will be called. The call
resolved by the compiler. is not resolved by the compiler.
It provides slow execution compared to
It provides fast execution because it is known at the
compile-time polymorphism because it is
compile time.
known at the run time.
It is achieved by function overloading and operator It can be achieved by virtual functions and
overloading. pointers.
Example -
Example -
class A{
int add(int a, int b){ public:
return a+b; virtual void fun(){
} cout<<"base ";
int add(int a, int b, int c){ }
return a+b+c; };
} class B: public A{
public:
int main(){ void fun(){
cout<<add(2,3)<<endl; cout<<"derived ";
cout<<add(2,3,4)<<endl; }
};
int main(){
return 0; A *a=new B;
} a->fun();

return 0;
}

10. What do you know about friend class and friend function?
A friend class can access private, protected, and public members of other classes in which it is
declared as friends.

Like friend class, friend function can also access private, protected, and public members. But,
Friend functions are not member functions.

For example -

class A{
private:
int data_a;
public:
A(int x){
data_a=x;
}
friend int fun(A, B);
}
class B{
private:
int data_b;
public:
A(int x){
data_b=x;
}
friend int fun(A, B);
}
int fun(A a, B b){
return a.data_a+b.data_b;
}
int main(){
A a(10);
B b(20);
cout<<fun(a,b)<<endl;
return 0;
}

Here we can access the private data of class A and class B.

11. What are the C++ access specifiers?

In C++ there are the following access specifiers:

Public: All data members and member functions are accessible outside the class.

Protected: All data members and member functions are accessible inside the class and to the
derived class.
Private: All data members and member functions are not accessible outside the class.

12. Define inline function

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. One of the important advantages of using an inline
function is that it eliminates the function calling overhead of a traditional function.

13. What is a reference in C++?

A reference is like a pointer. It is another name of an already existing variable. Once a reference
name is initialized with a variable, that variable can be accessed by the variable name or
reference name both.

For example-

int x=10;
int &ref=x; //reference variable

If we change the value of ref it will be reflected in x. Once a reference variable is initialized it
cannot refer to any other variable. We can declare an array of pointers but an array of references
is not possible.

14. What do you mean by abstraction in C++?

Abstraction is the process of showing the essential details to the user and hiding the details which
we don‟t want to show to the user or hiding the details which are irrelevant to a particular user.

15. Is deconstructor overloading possible? If yes then explain and if no then why?

No destructor overloading is not possible. Destructors take no arguments, so there‟s only one
way to destroy an object. That‟s the reason destructor overloading is not possible.

16. What do you mean by call by value and call by reference?

In call by value method, we pass a copy of the parameter is passed to the functions. For these
copied values a new memory is assigned and changes made to these values do not reflect the
variable in the main function.

In call by reference method, we pass the address of the variable and the address is used to access
the actual argument used in the function call. So changes made in the parameter alter the passing
argument.

17. What is an abstract class and when do you use it?


A class is called an abstract class whose objects can never be created. Such a class exists as a
parent for the derived classes. We can make a class abstract by placing a pure virtual function in
the class.

18. What are destructors in C++?

A constructor is automatically called when an object is first created. Similarly when an object is
destroyed a function called destructor automatically gets called. A destructor has the same name
as the constructor (which is the same as the class name) but is preceded by a tilde.

Example:

class A{
private:
int val;
public:
A(int x){
val=x;
}
A(){
}
~A(){ //destructor
}
}
int main(){
A a(3);
return 0;
}

19. What are the static members and static member functions?

When a variable in a class is declared static, space for it is allocated for the lifetime of the
program. No matter how many objects of that class have been created, there is only one copy of
the static member. So same static member can be accessed by all the objects of that class.

A static member function can be called even if no objects of the class exist and the static function
are accessed using only the class name and the scope resolution operator ::

20. Explain inheritance

Inheritance is the process of creating new classes, called derived classes, from existing classes.
These existing classes are called base classes. The derived classes inherit all the capabilities of
the base class but can add new features and refinements of their own.

Example-
Inheritance in C++

Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.

The most important thing about inheritance is that it permits code reusability.

21. What is a copy constructor?

A copy constructor is a member function that initializes an object using another object of the
same class.

Example-

class A{
int x,y;
A(int x, int y){
this->x=x;
this->y=y;
}

};
int main(){
A a1(2,3);
A a2=a1; //default copy constructor is called
return 0;
}
We can define our copy constructor. If we don‟t define a copy constructor then the default copy
constructor is called.

22. What is the difference between shallow copy and deep copy?

The difference between shallow copy and a deep copy is given below:

Shallow Copy Deep Copy


Shallow copy stores the references of Deep copy makes a new and separate copy of an
objects to the original memory address. entire object with its unique memory address.
Shallow copy is faster. Deep copy is comparatively slower.
Shallow copy reflects changes made to the Deep copy doesn‟t reflect changes made to the
new/copied object in the original object. new/copied object in the original object

23. What is the difference between virtual functions and pure virtual functions?

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

Example-

class base{
public:
virtual void fun(){

}
};

A pure virtual function is a function that has no implementation and is declared by assigning 0. It
has no body.

Example-

class base{
public:
virtual void fun()=0;
};

Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything.
It is used to simply tell the compiler that a function will be pure and it will not have anybody.

24. If class D is derived from a base class B. When creating an object of type D in what
order would the constructors of these classes get called?
The derived class has two parts, a base part, and a derived part. When C++ constructs derived
objects, it does so in phases. First, the most-base class(at the top of the inheritance tree) is
constructed. Then each child class is constructed in order until the most-child class is constructed
last.
So the first Constructor of class B will be called and then the constructor of class D will be
called.

During the destruction exactly reverse order is followed. That is destructor starts at the most-
derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.

25. Can we call a virtual function from a constructor?

Yes, we can call a virtual function from a constructor. But the behavior is a little different in this
case. When a virtual function is called, the virtual call is resolved at runtime. It is always the
member function of the current class that gets called. That is the virtual machine doesn‟t work
within the constructor.

For example-

class base{
private:
int value;
public:
base(int x){
value=x;
}
virtual void fun(){

}
}

class derived{
private:
int a;
public:
derived(int x, int y):base(x){
base *b;
b=this;
b->fun(); //calls derived::fun()
}
void fun(){
cout<<”fun inside derived class”<<endl;
}
}
26. What are void pointers?

A void pointer is a pointer which is having no datatype associated with it. It can hold addresses
of any type.

For example-

void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch

We can assign a pointer of any type to a void pointer but the reverse is not true unless you
typecast it as

str=(char*) ptr;

27. What is this pointer in C++?

The member functions of every object have a pointer named this, which points to the object
itself. The value of this is set to the address of the object for which it is called. It can be used to
access the data in the object it points to.

Example

class A{
private:
int value;
public:
void setvalue(int x){
this->value=x;
}
};

int main(){
A a;
a.setvalue(5);
return 0;
}

28. What is the C++ OOPs concept?

 Object
 Class
 Inheritance
 Polymorphism
 Encapsulation
 Abstraction

Object: Anything that exists physically in the real world is called an object.

Class: The collection of objects is called class.

Inheritance: Properties of parent class inherited into child class is known as inheritance.

Polymorphism: It is the ability to exist in more than one form.

Encapsulation: Binding of code and data together into a single unit.

Abstraction: Hiding internal details and showing functionality to the user.

29. When is void() return type used?

You use the void() return type when you don‟t want to return any value. It specifies that the
function doesn‟t return a value. A function with a void return type completes its task and then
returns the control to the caller.

30. What is call by value and call by reference in C++?

In the call by value method, you pass the copies of actual parameters to the function's formal
parameters. This means if there is any change in the values inside the function, then that change
will not affect the actual values.

In the call-by-reference method, the reference or address of actual parameters is sent to the
function's formal parameters. This means any change in values inside the function will be
reflected in the actual values.

31. What is an inline function?

An inline function when called expands in line. When you call this function, the whole code of
the inline function gets inserted or substituted at the inline function call.

Syntax:

Inline return-type function-name(parameters)

32. What are pointers in C++?


Pointers are the variables that store the memory address of another variable. The type of the
variable must correspond with the type of pointer.

Syntax: type *name

33. What is a scope resolution operator?

A scope resolution operator is represented as ::

This operator is used to associate function definition to a particular class.

The scope operator is used for the following purposes:

 To access a global variable when you have a local variable with the same name.
 To define a function outside the class.

34. What is a constructor?

A constructor is defined as a member function that is invoked whenever you create an object; it
has the same name as that of the class.

There are two types of constructors:

 Default constructor: This auto-generated constructor doesn‟t take any arguments.


 Parameterized constructor: In this constructor, it can pass arguments.

35. Define operator overloading and function overloading.

An example of compile-time polymorphism is operator overloading. It is the concept of


modifying an existing C++ operator without altering its original meaning.

Let us take an example for this

class A
{
};
int main()
{
A a1,a2,a3;
a3= a1 + a2;
return 0;
}
36. How to input strings in C++ with spaces?
37. Discuss the difference between new and malloc

new malloc
new is an operator malloc() is a function
The malloc function doesn‟t call the
It calls the constructor
constructor
There is no need to specify memory size while using
You have to specify the memory size
new()
new operator can be overloaded malloc() can never be overloaded

38. What is operator overloading?

Operator overloading is a mechanism in which a special meaning is given to an operator.

For example, you can overload the „+‟ operator in a class-like string to concatenate two strings
by only using „+.‟

39. What are the differences between references and pointers?

Both references and pointers can be used to change the local variables of one function inside
another function. Both of them can also be used to save copying of big objects when passed as
arguments to functions or returned from functions, to get efficiency gain. Despite the above
similarities, there are the following differences between references and pointers.
References are less powerful than pointers as:

 Once a reference is created, it cannot be later made to reference another object, it cannot
be reseated. This is often done with pointers.
 References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing
 A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data structures
like Linked List, Tree, etc. In Java, references don‟t have the above restrictions and can be used
to implement all data structures. References being more powerful in Java is the main reason Java
doesn‟t need pointers.
References are safer and easier to use:

Safer: Since references must be initialized, wild references like wild pointers are unlikely to
exist. It is still possible to have references that don‟t refer to a valid location (See questions 5 and
6 in the below exercise)

Easier to use: References don‟t need dereferencing operator to access the value. They can be
used like normal variables. „&‟ operator is needed only at the time of declaration. Also, members
of an object reference can be accessed with dot operator („.‟), unlike pointers where arrow
operator (->) is needed to access members.

40. What are virtual functions – Write an example?

Virtual functions are used with inheritance, they are called according to the type of the object
pointed or referred to, not according to the type of pointer or reference. In other words, virtual
functions are resolved late, at runtime. The virtual keyword is used to make a function virtual.

Following things are necessary to write a C++ program with runtime polymorphism (use of
virtual functions)

 A base class and a derived class.


 A function with the same name in base class and derived class.
 A pointer or reference of base class type pointing or referring to an object of a derived
class.

Example: In the following program bp is a pointer of type Base, but a call to bp->show() calls
show() function of Derived class because bp points to an object of Derived class.

// C++ program for the above approach


#include <iostream>
using namespace std;

class Base {
public:
virtual void show() { cout << " In Base \n"; }
};

class Derived : public Base {


public:
void show() { cout << "In Derived \n"; }
};

// Driver's code
int main(void)
{
Base* bp = new Derived;

// Function call
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}

41. What is this pointer?

The „this‟ pointer is passed as a hidden argument to all nonstatic member function calls and is
available as a local variable within the body of all nonstatic functions. „this‟ pointer is a constant
pointer that holds the memory address of the current object. „this‟ pointer is not available in
static member functions as static member functions can be called without any object (with class
name).

42.What Is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Yet each also
defines additional features that make them different. Object-oriented programming allows
classes to inherit commonly used state and behavior from other classes

43. What is Static Member?

Static is a keyword in C++ used to give special characteristics to an element. Static elements are
allocated storage only once in a program lifetime in static storage area. And they have a scope till
the program lifetime. Static Keyword can be used with following,

Interesting facts about Static Members Functions in C++

 static member functions do not have this pointer.


 A static member function cannot be virtual
 Member function declarations with the same name and the name parameter-type-
list cannot be overloaded if any of them is a static member function declaration.
 static member function can not be declared const, volatile, or const volatile.

44. What is Object Oriented Programming?


Object Oriented Programming (OOP) is a programming paradigm where the complete software
operates as a bunch of objects talking to each other. An object is a collection of data and methods
that operate on its data.

45. Why OOP?


The main advantage of OOP is better manageable code that covers following.

1) The overall understanding of the software is increased as the distance between the
language spoken by developers and that spoken by users.
2) Object orientation eases maintenance by the use of encapsulation. One can easily change
the underlying representation by keeping the methods same.
OOP paradigm is mainly useful for relatively big software.

46. What are main features of OOP?


Encapsulation
Polymorphism
Inheritance

47. What is encapsulation?


Encapsulation is referred to one of the following two notions.
1) Data hiding: A language feature to restrict access to members of an object. For example,
private and protected members in C++.
2) Bundling of data and methods together: Data and methods that operate on that data are
bundled together.

48. What is Polymorphism? How is it supported by C++?


Polymorphism means that some code or operations or objects behave differently in different
contexts. In C++, following features support polymorphism.

Compile Time Polymorphism: Compile time polymorphism means compiler knows which
function should be called when a polymorphic call is made. C++ supports compiler time
polymorphism by supporting features like templates, function overloading and default
arguments.

Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea
is, virtual functions are called according to the type of object pointed or referred, not
according to the type of pointer or reference. In other words, virtual functions are resolved
late, at runtime.

49. What is Inheritance? What is the purpose?


The idea of inheritance is simple, a class is based on another class and uses data and
implementation of the other class.
The purpose of inheritance is Code Reuse.

50. What is Abstraction?


Abstraction is similar to data encapsulation and very important in OOP. It shows only the
necessary information and hides the other irrelevant information. Abstraction is implemented
using Abstraction classes and interfaces . The problems in Abstraction are solved at design or
interface level.

51. What are Manipulators?

Manipulators are the functions which can be used in conjunction with the insertion (<<) and
extraction (>>) operators on an object. Examples are endl and setw.

52. What is destructor?

A destructor is a method which is automatically called when the object is made of scope or
destroyed. Destructor name is also same as class name but with the tilde symbol before the name.

53. What is the difference between function overloading and operator overloading?

Function overloading: Function overloading is defined as we can have more than one version of
the same function. The versions of a function will have different signature means that they have
a different set of parameters.

Operator overloading: Operator overloading is defined as the standard operator can be


redefined so that it has a different meaning when applied to the instances of a class.

54. What is the difference between struct and class?

Structures class
The class is a user-defined data type which
A structure is a user-defined data type which
contains member variables and member
contains variables of dissimilar data types.
functions.
The variables of a structure are stored in the The variables of a class are stored in the heap
stack memory. memory.
We can initialize the member variables
We cannot initialize the variables directly.
directly.
If access specifier is not specified, then by If access specifier is not specified, then by
default the access specifier of the variable is default the access specifier of a variable is
"public". "private".
The instance of a structure is a "structure
variable".
Declaration of a structure: Declaration of class:
struct structure_name class class_name
{ {
// body of structure; // body of class;
}; }
A structure is declared by using a struct
The class is declared by using a class keyword.
keyword.
The structure does not support the inheritance. The class supports the concept of inheritance.
The type of a structure is a value type. The type of a class is a reference type.

55. What is the difference between function overloading and operator overloading?

Function overloading: Function overloading is defined as we can have more than one version of
the same function. The versions of a function will have different signature means that they have
a different set of parameters.

Operator overloading: Operator overloading is defined as the standard operator can be


redefined so that it has a different meaning when applied to the instances of a class.

56. What does Scope Resolution operator do?

A scope resolution operator(::) is used to define the member function outside the class.

57. What is function overriding?

If you inherit a class into a derived class and provide a definition for one of the base class's
function again inside the derived class, then this function is called overridden function, and this
mechanism is known as function overriding.

58. What is a destructor?

A Destructor is used to delete any extra resources allocated by the object. A destructor function
is called automatically once the object goes out of the scope.

Rules of destructor:

 Destructors have the same name as class name and it is preceded by tilde.
 It does not contain any argument and no return type.
59. Define friend function.

Friend function acts as a friend of the class. It can access the private and protected members of
the class. The friend function is not a member of the class, but it must be listed in the class
definition. The non-member function cannot access the private data of the class. Sometimes, it is
necessary for the non-member function to access the data. The friend function is a non-member
function and has the ability to access the private data of the class.

60. What is the difference between new() and malloc()?

 new() is a preprocessor while malloc() is a function.


 There is no need to allocate the memory while using "new" but in malloc() you have to
use sizeof().
 "new" initializes the new memory to 0 while malloc() gives random value in the newly
allotted memory location.
 The new() operator allocates the memory and calls the constructor for the object
initialization and malloc() function allocates the memory but does not call the constructor
for the object initialization.
 The new() operator is faster than the malloc() function as operator is faster than the
function.

61. What is namespace in C++?

If there are two or more functions with the same name defined in different libraries then how will
the compiler know which one to refer to? Thus namespace came to the picture. A namespace
defines the scope and differentiates functions, classes, variables etc. with the same name
available in different libraries. The namespace starts with the keyword “namespace”. The syntax
for the same is as follows:

namespace namespace_name
{

// code declarations

62. What is using namespace std in C++?

Using namespace std in C++ tells the compiler that you will be making use of the namespace
called „std‟. The „std‟ namespace contains all the features of the standard library. You need to put
this statement at the start of all your C++ codes if you don‟t want to keep on writing std:: infront
of every variable/string or whatever standard library feature you are making use of, as it becomes
tedious to do so.
63. What is stream in C++?

Stream refers to a stream of characters to be transferred between program thread and i/o.

64. What is iostream in C++?

It is a header file that includes basic objects such as cin, cout, cerr, clog.

65. What is :: in C++?

:: is called a scope resolution operator which is used to access global variables with the same
name as of local variables, for defining functions outside the class, for accessing static variables,
and for referring to a class inside of another class.

66. What is enum in C++?

enum is abbreviation of Enumeration which assigns names to integer constant to make a program
easy to read. Syntax for the same:

1enum enum_name{const1, const2, ....... };

67. What is endl in C++?

Endl is a predefined object of ostream class to insert a new line characters.

68. How to include all libraries in C++?

The library <bits/stdc++.h> in c++ is used to include all the libraries.

69. What is scope resolution operator in C++?

Scope resolution operator in c++ is denoted by double colon (::). It can be used:

– when there is a local variable with same name as of global variable

– When a function has to be defined outside a class

– When class‟s static variables needs to be accessed

– When a class inside another class has to be referred

– In case of multiple Inheritance

70. What is a virtual base class in C++?

Let‟s understand this with an example.


You Have 4 classes: W,X,Y,Z

Here X & Y inherit from W. So they both have similar features being inherited from W.

Now, Z inherits from both X & Y

Here Z may inherit similar features from X & Y as they both have inherited them from W. This
can cause issues and that‟s why we use virtual base classes as they stop multiple features of a
class from appearing in another class.

71. How to access private members of a class in C++?

Private members of the class are not accessible by object or function outside the class. Only
functions inside the class can access them or friend functions. However, pointers can be used to
access private data members outside the class.

The sample code is as follows:

#include <iostream>

using namespace std;

class sample_test{

private:

int n;

public:

sample_test() { n = 45; }

int display() {

return n;

};

How to call a base class constructor from a derived class in C++?

A base class constructor will be called whenever the derived class constructor is called. Upon the
creation of a derived class object, the order of constructor execution is: base class constructor
then Default class constructor.

You might also like