0% found this document useful (0 votes)
26 views14 pages

C++ Interview Questions and Answers For Experienced

The document provides a comprehensive overview of the C++ programming language, including its history, key features, and importance in technical interviews. It includes commonly asked interview questions and answers related to C++ concepts such as memory structure, encapsulation, polymorphism, and templates. Additionally, it discusses the differences between C++ and Java, various ways to pass parameters, and the significance of namespaces and copy constructors.

Uploaded by

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

C++ Interview Questions and Answers For Experienced

The document provides a comprehensive overview of the C++ programming language, including its history, key features, and importance in technical interviews. It includes commonly asked interview questions and answers related to C++ concepts such as memory structure, encapsulation, polymorphism, and templates. Additionally, it discusses the differences between C++ and Java, various ways to pass parameters, and the significance of namespaces and copy constructors.

Uploaded by

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

About C++ Language

Get C++ detailed information on this page along with C++ Interview Questions and Answers for Experienced.

About C++ Language

C++ again is very important for placements and a lot of questions will be asked from theory concepts in Online tests of
various companies and also interviews
Basically, the concept of C++ is introduced in the early ’80s (1982) by a software engineer Bjarne Stroustrup was doing

work for his Ph.D. thesis in AT& T Bell Labs(American Telephone& Telegraph), located in Murray Hills, NewJersey, USA
Stroustrup is very interested in C language because of its powerful features like –

Multipurpose programming,
Portability
Pointers
Dynamic memory allocation,
Midlevel flavor…

and more. Click on the button below to know more about C++.

About C++ Language

IMPORTANT!!
Few Important pages to be checked

Check these pages to know more Technical Questions and prepare well for you Placements.

JAVA Experienced

DSA For Freshers

OOPS for Freshers

Software Engineering

Commonly Asked C++ Interview Questions and Answers for


Experienced
1. What Is The Memory Structure Of An Object?

Solution:-

Usually C++ objects are made by concatenating member variables.

For example;

class Test

int i;

float j;

};

is represented by an int followed by a float.

class TestSub: public Test

int k;

};

The above class is represented by Test and then an int(for int k). So finally it will be int, float and int.

In addition to this each object will have the vptr(virtual pointer) if the class has virtual function, usually as the first element in a
class.

2. Define Encapsulation in C++?


Solution:-

The process of encapsulating data and functions in a class is called encapsulation. For security purposes, it is used to prevent
direct access to data. This is accomplished by using class functions.

For example, the net banking facility for customers allows only the approved person with the proper login id and password to
access the information in the bank data source, and only for his or her part of the information.

3. What Is The Difference Between Exit And Abort?


Solution:-

Exit performs a graceful process termination by invoking the destructors for all constructed objects, while abort does not.

Exiting the local The destructors of the calling function’s and its callers’ variables will not be called.
4. Write C++ code to create an array of objects using new keyword and delete these objects.
Also, proof that all the objects are deleted properly.

Solution:-

C++ not only preserves all elements of the C language, but it also simplifies memory management and introduces a number of
new features, such as:

We know that when we generate a class object dynamically from heap memory with the new keyword, we must specifically
delete it after we are finished with its operations to prevent memory leaks in C++ programs.

As an example, consider the class Pen below.

class Pen {

public:
Pen() {
cout << "Constructor..." <<endl;
}

~Pen() {
cout << "Destructor...!" <<endl;
}
void write(){
cout << "Writing...!" <<endl;
}
};

Below is an example, how we create an object of the class Pen dynamically and delete it after we are done with operations.

int main()
{
//create an object dynamically
Pen* pen = new Pen();
pen->write();//operations

delete pen;//de-allocate the memory

return 0;
}

How to create array of objects of a class in C?

Let’s see how we create an array of objects in below C++ program example. In this example, we will create array of 3 objects,
perform operation and delete dynamic array of pointers properly.

i t i ()
int main()
{
//create an array of objects
Pen* pen = new Pen[3];

pen[0].write();
pen[1].write();
pen[2].write();

delete [] pen;//de-allocate array of objects

return 0;
}

Output:

Constructor…
Constructor…
Constructor…
Writing…!
Writing…!
Writing…!
Destructor…!
Destructor…!
Destructor…!

Proof of proper deletion of array of objects in C++

First, note that if we create an object of a class and delete the object then class constructor and destructor will be called
respectively.

In above example, we have created an array of 3 objects and delete it using statement delete [] pen; if we look at the output
the class constructor and destructor were called 3 times each. means, we have deleted objects properly.

Now, If we delete the object using the statement “delete pen” ( This is general mistake a programmer make) then the
destructor will be called only once and for rest 2 objects destructor will not be called and program will crash. and this will proof
that objects are not deleted properly.

Lets see the output if we use statement “delete pen”

int main()
{
//create an array of objects
Pen* pen = new Pen[3];

pen[0].write();
pen[1].write();
pen[2].write();

//this is not a prper way to delete


//array of objects
delete pen;

return 0;
}

Output:
Output:

Constructor…
Constructor…
Constructor…
Writing…!
Writing…!
Writing…!
Destructor…!

and then program will crash at run time.

Conclusion:
In C++, single object of a class created dynamically is deleted using statement “delete pointer” and array of objects are deleted
using statement “delete [ ] pointer”.

5. How would you establish the relationship between abstraction and


encapsulation?
Solution:-

In a C++ program, data abstraction refers to representing only the most important features of a real-world object. This entire
procedure is devoid of any code description or context information. Classes and objects are used to enforce abstraction, with
data encapsulation being the most important aspect of a class.

In C++, data encapsulation refers to the grouping together of data members and member functions that work on the data
into a single unit known as a class. Encapsulation prohibits members of the class from having unrestricted access.

6. What is the purpose of extern storage specifier.

Solution:-

Used to resolve the scope of global symbol

#include

using namespace std;


main() {
extern int i;

cout</span<<i<<endl;
}
int i = 20;
7. Why do we need the Friend class and function?
Solution-

It’s often necessary to grant specific class access to a class’s private or protected members. A friend class is a solution since it
can access both protected and private members of the class in which it is declared as a friend. A friend feature, like the friend
class, has access to private and safe class members.

Friendship is not something you inherit.


Friendship is not reciprocal, because if one class is a friend of another, such as NotAFriend, it does not immediately
become a friend of the Friend class.
The total number of friend classes and friend functions in a programme should be restricted because too many of them will
degrade the principle of encapsulation of separate classes, which is an intrinsic and desirable quality of object-oriented
programming.

8. Consider the following C++ code segment and answer the question associated with it:

#include
using namespace std;
class Test
{
int ID;
float max, min, marks;
public:
Test() // Function 1
{
ID = 121;
max = 100;
min = 33.33;
marks = 75;
}
Test(int r_no, int Marks) // Function 2
{
ID = r_no;
max = 100;
min = 33.33;
marks = Marks;
}
~Test() // Function 3
{
cout<<"Finished Test"<<endl;
}
void display() // Function 4
{
cout<<ID<<"\t"<<max<<"\t"<<"\t"<<min<<endl;
cout<<"Your marks: "<<marks<<endl;
}
}

Which OOP concept is illustrated through “Function 1” and “Function 2” together?

Solution:-

Both functions together illustrate the concepts of polymorphism and function Object() { [native code] } overloading.

9. Explain The Isa And Hasa Class Relationships. How Would You
9. Explain The Isa And Hasa Class Relationships. How Would You
Implement Each In A Class Design?
Solution:-

A specialised class “is” a specialisation of another class and therefore shares an ISA relationship with it. An ISA person who
works for the business. Inheritance is the only way to implement this partnership. The word “employee” comes from the word
“person.” It is possible for a class to contain an instance of another class. Employees, for example, “have” salaries, because the
Employee class has a HASA relationship with the Wage class.

The best way to enforce this relationship is to embed a Salary class object in the Employee class.

10. Draw a comparison between C++ and Java


Solution:-

Destructors are called automatically when an object is destroyed in C++. Automatic garbage collection is a function of
Java.
Multiple inheritance, operator overloading, pointers, structures, templates, and unions are all supported in C++. None of
them are available in Java.
To build a new thread, Java has a Thread class that is inherited. Threads aren’t supported by C++ by default.
In C++, a goto statement offers a way to jump from a location to some labeled statement in the same function. There is
no goto statement in Java
C++ run and compile using the compiler, which converts the source code into machine level language. Hence, it is
platform-dependent. Java compiler, on the other hand, converts the source code into JVM bytecode, which is platform-
independent.

11. Take a look at the following C++ program:

#include
using namespace std;
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) { cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}

What will be the output?

Solution-

The program will ask the user to enter 5 numbers and will then present with their sum as the output For instance
The program will ask the user to enter 5 numbers and will then present with their sum as the output. For instance,

Enter 5 numbers: 22
25
32
46
66

Sum = 191

12. If you are given a binary file named “Phone.dat” that consists of records of a phonebook
directory, how would you copy the records of the file that have their AreaCode as “400” from
“Phone.dat” to “Copy.dat”?

The given binary file has the following content:

class Directory
{
string name, address;
char phone_no[15];
char area_code[5];
public:
void input();
void output();
int checkcode(string ac)
{
return strcmp( area_code, ac)
}
};

Solution:-

We will define a function to perform the above-stated task:

void copy400()
{
ifstream fin;
ofstream fout;
Directory ph;
fin.open("Phone.dat", ios::in | ios::binary);
fout.open("Copy.dat", ios::out | ios::binary);
while(!fin.eof())
{
fin.read((char*)&ph. sizeof(ph));
if(ph.checkcode("400")==0)
fout.write((char*)&ph, sizeof(ph));
}
fin.close();
fout.close()

13. What are command line arguments?


Solution:-

Command line arguments are the arguments that we send to the main() function when running the programme. The parameters
are often strings, which are stored in the function’s second argument (below in args), which is an array of character pointers.
The first statement is the count of arguments (below in count), which is automatically modified by the operating system.

main( int count, char *args[]) {


}

14. What is the difference between typecasting and automatic type


conversion? Explain with the help of an example.
Solution:-

Typecasting in C++ is done by the programmer in order to convert a value from one data type to another data type.

For example,
float pi = (float) 22/7;

On the other hand, automatic type conversion is automatically done by the C++ compiler as and when required.

For example,
float value = 10;

15. Explain Virtual Functions and the concept of Runtime Polymorphism in C++ with a code
example.

Solution:-

When the virtual keyword is present, every function takes on the actions of a virtual function. Unlike normal functions, which are
invoked based on the type of pointer or reference used, virtual functions are invoked based on the type of the object pointed to
or referred to.

Virtual functions, to put it simply, resolve at runtime, not before. Using virtual functions is similar to writing a C++ program that
makes use of the principle of runtime polymorphism. The following are requirements for writing a virtual function in C++:

A base class
A derived class
A function with the same name in both the classes i.e. the base class and the derived class
A pointer or reference of base class type that points or refers, respectively to an object of the derived class

An example demonstrating the use of virtual functions (or runtime polymorphism at play) is:

#include
using namespace std;
l {
class Base {
public:
virtual void show() { cout<<" In Base \n"; }
};
class Derived: public Base {
public:
void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->show(); // <- Runtime
Polymorphism in Action
return 0;
}

In the aforementioned program bp is a pointer of type Base. A call to bp->show() calls show() function of the Derived class.
This is because bp points to an object of the Derived class.

16.Why do we use templates in C++?


Solution:-

In C++, templates are a fast and efficient way to achieve polymorphism, which is an essential concept in OOP. It assists us in
dealing with a variety of criteria, reducing the time spent debugging and checking the code.

17. What does a Static member in C++ mean?


Solution:-

A static member is only given storage in the static storage area once during the program’s lifespan, as indicated by the static
keyword. The following are some relevant facts about static members:

Any static member function can’t be virtual


Static member functions don’t have ‘this’ pointer
The const, const volatile, and volatile declaration aren’t available for static member functions

18. What are the different ways of passing parameters to the functions? Which to
use when?
Solution:-

Call by value − We send only values to the function as parameters. We choose this if we do not want the actual
parameters to be modified with formal parameters but just used.

Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual
parameters to be modified with formal parameters.

Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We
choose this if we do want the actual parameters to be modified with formal parameters.

19. What Problem Does The Namespace Feature Solve?


Solution:-

When an application attempts to connect with two or more libraries, multiple providers of libraries can use common global
identifiers, resulting in a name collision. The namespace function creates a specific namespace around a library’s external
declarations, which removes the possibility of collisions. Of course, this approach assumes that no two library vendors use the
same namespace identifier.

20. Define the Copy Constructor used in C++ along with its general
function prototype. Also, explain the various scenarios in which it is called.
Solution:-

In C++, a copy function Object() { [native code] } is a member function that uses another object of the same class to initialise
an object. It’s also possible to make the Copy Constructor private. Any of the following four scenarios will result in a call to the
Copy Constructor:

1. The compiler generates a temporary object


2. An object is constructed or based on some another object of the same class
3. An object of the class is returned by value
4. An object of the class is passed (i.e. to a function) by value as an argument

The general function prototype for the Copy Constructor is:

ClassName (const ClassName &old_obj);


Point(int x1, int y1) { x=x1; y=y1;}
Point(const Point &p2) { x=p2.x; y=p2.y; }

21. Difference between Declaration and Definition of a variable.

Solution:-

The name of a variable and its data type are also specified in the declaration of a variable. As a result of the declaration, we tell
the compiler to set aside memory space for a variable of the specified data type.
Example:

int Result;
char c;
int a,b,c;

All of the preceding declarations are right. Also, notice that the variable’s value is unknown as a consequence of the declaration.

A description, on the other hand, is an implementation/instantiation of the declared variable in which we bind appropriate values
to the declared variable so that the linker can link references to the correct entities.

From above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

22. Comment on Local and Global scope of a variable.


Solution:-

The scope of a variable is the amount of program code within which it can be declared, described, or operated with.

In C++, there are two forms of scope: local and global.

1. When a variable is declared within a code block, it is said to have a local scope or be local. The variable is only active
inside the code block and is not available outside of it.
2. When a variable is available in the program, it is said to have a global reach. Before all the function descriptions, a global
variable is declared at the top of the program.

23. What is the precedence when there are a Global variable and a Local variable in the program
with the same name?

Solution:-

Whenever there is a local variable with the same name as that of a global variable, the compiler gives precedence to the local
variable.

Example:
#include <iostream.h>
int globalVar = 2;
int main()
{
int globalVar = 5;
cout<<globalVar<<endl;
}

The output of the above code is 5. This is because, although both the variables have the same name, the compiler has given
preference to the local scope.

24. When there are a Global variable and Local variable with the same name, how will you access
the global variable?

Solution:-

When two variables have the same name but different scopes, for example, one is a local variable and the other is a global
variable, the compiler would favour the local variable.

We use a “scope resolution operator (::)” to get access to the global variable. We can get the value of the global variable with
this operator.

Example:

#include
int x= 10;
int main()
{
int x= 2;
cout<<”Global Variable x = “<<::x;
cout<<”\nlocal Variable x= “<<x;
}

Output:
Global Variable x = 10
local Variable x= 2

25. How many ways are there to initialize an int with a Constant?
Solution:-

There are two ways:

The first format uses traditional C notation.


int result = 10;
The second format uses the constructor notation.
int result (10);

You might also like