YouTube Icon

Interview Questions.

Advanced C++ Programming Interview Questions and Answers - Jul 17, 2022

fluid

Advanced C++ Programming Interview Questions and Answers

Q1. What is distinction among C and C++ ?

Ans:

C++ is Multi-Paradigm( no longer natural OOP, helps each procedural and item orientated) at the same time as C follows procedural style programming.

In C statistics security is less, however in C++ you can use modifiers on your elegance individuals to make it inaccessible from out of doors.

C follows pinnacle-down technique ( answer is created in grade by grade way, like each step is processed into details as we continue ) but C++ follows a bottom-up approach ( wherein base factors are established first and are related to make complicated answers ).

C++ helps function overloading while C does no longer guide it.

C++ lets in use of features in structures, however C does now not permit that.

C++ helps reference variables(  variables can point to same memory area ). C does not support this.

C does not have a built in exception managing framework, although we are able to emulate it with different mechanism. C++ immediately supports exception handling, which makes existence of developer easy.

Q2. What is a category?

Ans: [Probably this would be the first question for a Java/c++ technical interview for freshers and sometimes for experienced as well. Try to give examples when you answer this question.]

Class defines a datatype, it is kind definition of class of thing(s). But a class truely does not define the records, it simply specifies the structure of statistics. To use them you want to create objects out of the magnificence. Class can be taken into consideration as a blueprint of a building, you can not stay inner blueprint of constructing, you want to assemble constructing(s) out of that plan. You can create any range of homes from the blueprint, similarly you can create any quantity of items from a class.

Magnificence Vehicle

public:

int numberOfTyres;

double engineCapacity;

void drive()

// code to power the auto

;

Q3. What is an Object/Instance?

Ans: Object is the instance of a class, which is concrete. From the above instance, we are able to create instance of class Vehicle as given under

Vehicle vehicleObject;

We could have one-of-a-kind items of the magnificence Vehicle, for instance we can have Vehicle items with 2 tyres, 4tyres and so on. Similarly one of a kind engine capacities as nicely.

Q4. What do you imply by C++ get right of entry to specifiers ?

Ans: [Questions regarding access specifiers are common not just in c++ interview but for other object oriented language interviews as well.]

Access specifiers are used to define how the contributors (features and variables) may be accessed out of doors the elegance. There are three get admission to specifiers defined which can be public, non-public, and protected

personal:

Members declared as personal are handy most effective with inside the same magnificence and that they can not be accessed outside the class they may be declared.

Public:

Members declared as public are available from any in which.

Covered:

Members declared as protected can't be accessed from outside the class except a child magnificence. This access specifier has importance inside the context of inheritance.

Q5. What are the fundamentals standards of OOPS?

Ans:

Classes and Objects

Refer Questions 2 and 3 for the concepts approximately classes and objects

Encapsulation

Encapsulation is the mechanism through which facts and related operations/techniques are certain together and for that reason cover the records from outdoor global. It's additionally known as records hiding. In c++, encapsulation completed the usage of the get entry to specifiers (non-public, public and protected). Data contributors will be declared as private (as a result protecting from direct get entry to from outside) and public techniques can be supplied to access those records. Consider the below class

class Person

non-public:

int age;

public:

int getAge()

return age;

int setAge(int value)

if(price > 0)

age = fee;

;

In the elegance Person, get right of entry to to the records discipline age is included by maintaining it as non-public and supplying public access methods. What could have happened if there has been no access strategies and the sphere age turned into public? Anybody who has a Person item can set an invalid fee (negative or very big value) for the age subject. So by way of encapsulation we can stopping direct get entry to from outdoor, and for this reason have complete control, safety and integrity of the records.

Data abstraction

Data abstraction refers to hiding the inner implementations and display simplest the important details to the outdoor global. In C++ records abstraction is implemented using interfaces and summary classes.

Elegance Stack

public:

digital void push(int)=zero;

digital int pop()=0;

;

class MyStack : public Stack

personal:

int arrayToHoldData[]; //Holds the statistics from stack

public:

void push(int) 

// put in force push operation the usage of array

int pop()

// implement pop operation the use of array

;

In the above example, the out of doors world most effective want to realize approximately the Stack magnificence and its push, pop operations. Internally stack may be carried out the usage of arrays or linked lists or queues or something that you can think of. This way, so long as the frenzy and dad technique plays the operations paintings as anticipated, you have got the freedom to alternate the internal implementation without affecting different packages that use your Stack class.

Inheritance

Inheritance lets in one elegance to inherit houses of some other class. In other phrases, inheritance permits one elegance to be defined in phrases of some other class.

Elegance SymmetricShape

public:

int getSize()

return size;

void setSize(int w)

length = w;

protected:

int size;

;

// Derived elegance

magnificence Square: public SymmetricShape

public:

int getArea()

return (length * size);

;

In the above instance, elegance Square inherits the houses and methods of sophistication SymmetricShape. Inheritance is the one of the very vital standards in C++/OOP. It enables to modularise the code, enhance reusability and reduces tight coupling between additives of the gadget.

Q6.  What is the use of volatile key-word in c++? Give an example.

Ans: Most of the times compilers will do optimization to the code to speed up this system. For instance within the under code,

int a = 10;

while( a == 10)

// Do something

compiler might imagine that value of 'a' isn't getting modified from this system and update it with 'at the same time as(proper)', on the way to result in an endless loop. In real situation the price of 'a' may be getting updated from out of doors of the program.

Volatile keyword is used to inform compiler that the variable declared using volatile may be used from outside the modern-day scope so that compiler wont observe any optimization. This topics most effective in case of multi-threaded programs.

In the above instance if variable 'a' became declared using volatile, compiler will not optimize it. In shot, value of the volatile variables might be read from the reminiscence place without delay.

Q7. In how many approaches we will initialize an int variable in C++?

Ans: In c++, variables may be initialized in  approaches, the conventional C++ initialization using "=" operator and 2d using the constructor notation.

Traditional C++ initilization

int i = 10;

variable i will get initialized to 10.

Using C++ constructor notation

int i(10);

Implicit conversions are accomplished while a kind (say T) is utilized in a context where a well suited type (Say F) is predicted so that the kind T will be promoted to kind F.

Quick a = 2000 + 20;

In the above example, variable a will get robotically promoted from quick to int. This is referred to as implicit conversion/coercion in c++.

Q8. What is implicit conversion/coercion in c++?

Ans: Implicit conversions are accomplished while a kind (say T) is used in a context wherein a compatible kind (Say F) is expected so that the sort T can be promoted to kind F.

Brief a = 2000 + 20;

In the above instance, variable a will get routinely promoted from short to int. This is called implicit conversion/coercion in c++.

Q9. What are C++ inline features?

Ans: C++ inline features are unique functions, for which the compiler replaces the function name with frame/definition of function. Inline capabilities makes this system execute quicker than the everyday capabilities, because the overhead involved in saving modern state to stack on the characteristic name is avoided. By giving developer the manipulate of making a feature as inline, he can similarly optimize the code based on utility good judgment. But truely, it's the compiler that makes a decision whether or not to make a characteristic inline or not regardless of it is declaration. Compiler might also pick out to make a non inline feature inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler might also ignore. So, please be aware this factor for the interview that, it's far upto the compiler to make a characteristic inline or no longer.

Inline int min(int a, int b)

go back (a < b)? A : b;

int fundamental( )

cout << "min (20,10): " << min(20,10) << endl;

cout << "min (zero,200): " << min(zero,2 hundred) << endl;

cout << "min (100,1010): " << min(100,1010) << endl;

return 0;

If the complier makes a decision to make the characteristic min as inline, then the above code will internally look as if it turned into written like

int predominant( )

cout << "min (20,10): " << ((20 < 10)? 20 : 10) << endl;

cout << "min (0,200): " << ((0 < 2 hundred)? Zero : 200) << endl;

cout << "min (a hundred,1010): " << ((a hundred < 1010)? A hundred : 1010) << endl;

go back zero;

Q10. What do you suggest via translation unit in c++?

Ans: We organize our C++ programs into one of a kind supply documents (.Cpp, .Cxx and so forth). When you recollect a source file, at the preprocessing degree, some more content might also get added to the supply code ( as an instance, the contents of header documents blanketed) and a few content material may also get eliminated ( for instance, the a part of the code in the #ifdef of #ifndef block which solve to false/0 based on the symbols described). This powerful content is called a translation unit. In different phrases, a translation unit includes

Contents of source document

Plus contents of files protected without delay or circuitously

Minus source code traces omitted by way of any conditional pre processing directives ( the lines ignored with the aid of #ifdef,#ifndef and so on)

HubSpot Video

 

Q11. What do you mean by way of inner linking and outside linking in c++?

Ans: A image is said to be connected internally when it could be accessed most effective from with-in the scope of a unmarried translation unit. By outside linking a image may be accessed from different translation units as properly. This linkage may be controlled via the usage of static and extern key phrases.

Q12. What do you imply by way of storage instructions?

Ans: Storage elegance are used to specify the visibility/scope and life time of symbols(features and variables). That manner, storage training specify where all a variable or characteristic can be accessed and till what time the ones variables can be to be had in the course of the execution of application.

Q13. How many storage classes are to be had in C++?

Ans: Storage elegance are used to specify the visibility/scope and life time of symbols(functions and variables). That method, garage classes specify in which all a variable or function may be accessed and till what time the ones variables might be to be had throughout the execution of application.

Following storage classes are available in C++

vehicle

It's the default garage elegance for local variables. They may be accessed only from with within the statement scope. Car variables are allotted at the beginning of enclosing block and deallocated at the cease of enclosing block.

Void changeValue(void)

vehicle int i = 1 ;

i++;

printf ( "%d ", i ) ;

int fundamental()

changeValue();

changeValue();

changeValue();

changeValue();

go back zero;

Output:-

2 2 2 2

In the above instance, every time the approach changeValue is invoked, reminiscence is allotted for i and de allocated at the cease of the technique. So it's output can be equal.

Sign up

It's much like auto variables. Difference is that register variables is probably saved on the processor check in instead of RAM, that means the most size of sign in variable should be the dimensions of CPU sign up ( like 16bit, 32bit or 64bit). This is commonly used for regularly accessed variables like counters, to improve overall performance. But word that, putting forward a variable as sign up does now not imply that they'll be saved in the check in. It depends at the hardware and implementation.

Int essential()

sign up int i;

int array[10] = 0,1,2,three,4,5,6,7,8,9;

for (i=zero;i<10;i++)

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

return 0;

Output:-

zero 1 2 three four 5 6 7 8 9

The variable i is probably saved at the CPU register and due to which the get right of entry to of i inside the loop may be faster.

Static

A static variable might be saved in life till the end of this system not like creating and destroying on every occasion they flow into and out of the scope. This facilitates to preserve their fee although control is going out of the scope. When static is used with worldwide variables, they may have inner linkage, that means it can not be accessed with the aid of other supply documents. When static is used in case of a class member, it'll be shared through all of the gadgets of a category in place of developing separate copies for every object.

Void changeValue(void)

static int i = 1 ;

i++;

printf ( "%d ", i ) ;

int fundamental()

changeValue();

changeValue();

changeValue();

changeValue();

go back zero;

Output:-

2 three 4 five

Since static variable might be saved in lifestyles till the cease of program, variable i will preserve it's fee across the technique invocations.

Extern

extern is used to inform compiler that the image is described in another translation unit (or in a manner, source files) and now not inside the modern one. Which manner the image is related externally. Extern symbols have static garage period, that is handy via out the lifestyles of application. Since no storage is allotted for extern variable as part of declaration, they cannot be initialized even as maintaining.

Int x = 10;

int predominant( )

extern int y ;

printf("x: %d ", x );

printf("y: %d", y);

return zero;

int y = 70 ;

Output:-

x: 10 y: 70

extern variable is like global variable, it is scope is through out the program. It can be described everywhere inside the c++ software.

Mutable

mutable storage class may be used simplest on non static non const facts a member of a class. Mutable records member of a category can be modified even is it is a part of an item which is said as const.

Class Test

public:

Test(): x(1), y(1) ;

mutable int x;

int y;

;

int important()

const Test item;

x = 123;

//item.Y = 123;

/*

* The above line if uncommented, will create compilation errors.

*/

cout<< "X:"<< item.X << ", Y:" << item.Y;

return 0;

Output:-

X:123, Y:1

In the above instance, we're able to exchange the fee of member variable x though it's part of an object which is said as const. This is due to the fact the variable x is asserted as mutable. But in case you attempt to adjust the fee of member variable y, compiler will throw errors.

You can discover the precis of c++ garage magnificence specifiers below

C++ Storage Specifier    Storage Location    Scope Of Variable    Life Time

car    Memory (RAM)    Local    With in function

static    Memory (RAM)    Local    Life time is from when the go with the flow reaches the primary assertion to the termination of software.

Sign up    CPU register    Local    With in characteristic

extern    Memory (RAM)    Global    Till the quit of most important application
 

Q14. What is 'Copy Constructor' and when it's far known as?

Ans: This is a frequent c++ interview question. Copy constructor is a unique constructor of a category which is used to create copy of an object. Compiler will provide a default replica constructor in case you do not define one. This implicit constructor will replica all the contributors of supply item to target object.

Implicit replica constructors are not recommended, due to the fact if the source item carries hints they will be copied to target object, and it can cause heap corruption when each the gadgets with hints regarding the equal area does an update to the reminiscence place. In this situation its higher to outline a custom reproduction constructor and do a deep reproduction of the item.

Class SampleClass

public:

int* ptr;

SampleClass();

// Copy constructor statement

SampleClass(SampleClass &obj);

;

SampleClass::SampleClass()

ptr = new int();

*ptr = five;

// Copy constructor definition

SampleClass::SampleClass(SampleClass &obj)

//create a brand new item for the pointer

ptr = new int();

// Now manually assign the value

*ptr = *(obj.Ptr);

cout<<"Copy constructor...N";

Q15. What is realloc() and unfastened()? What is difference between them?

Ans:

void* realloc (void* ptr, size_t length)

This characteristic is used to alternate the size of memory item pointed through address ptr to the size given by means of size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour can also arise relying the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by unfastened(), or dealloc() or ptr do now not healthy a pointer back through an malloc(), calloc() or realloc().

Void free (void* ptr)

This characteristic is used to deallocate a block of memory that became allocated using malloc(), calloc() or realloc(). If ptr is null, this function does now not doe whatever.

Q16. What is difference between shallow reproduction and deep copy? Which is default?

Ans:

[This question can be expected in any interviews, not just c++ interviews. This is a usual question in most of the java interviews.]

When you do a shallow replica, all of the fields of the source item is copied to target object as it's miles. That manner, if there is a dynamically created discipline in the supply item, shallow replica will copy the same pointer to target object. So you may have two items with fields that are pointing to identical reminiscence place which isn't always what you generally want.

In case of deep copy, rather than copying the pointer, the item itself is copied to target. In this situation in case you modify the goal item, it will not have an effect on the source. By default copy constructors and assignment operators do shallow reproduction. To make it as deep replica, you want to create a custom copy constructor and override assignment operator.

Q17. What do you imply by means of chronic and non chronic gadgets?

Ans: Persistent items are the ones which we may be serialized and written to disk, or every other move. So before preventing your application, you may serialize the item and on restart you may deserialize it. [ Drawing applications usually use serializations.]

Objects that cannot be serialized are known as non continual objects. [ Usually database objects are not serialized because connection and session will not be existing when you restart the application. ]

Q18. Is it possible to get the source code back from binary report?

Ans: Technically it's far viable to generate the supply code from binary. It is referred to as reverse engineering. There are lot of opposite engineering tools available. But, in real case maximum of them will not re generate the precise source code again because many facts could be misplaced because of compiler optimization and other interpretations.

Q19. What are virtual capabilities and what's its use?

Ans: Virtual capabilities are member capabilities of class which is said using key-word 'virtual'. When a base class type reference is initialized the use of item of sub elegance type and an overridden method which is declared as digital is invoked the usage of the bottom reference, the approach in child elegance item will get invoked.

Magnificence Base

int a;

public:

Base()

a = 1;

digital void approach()

cout << a;

;

elegance Child: public Base

int b;

public:

Child()

b = 2;

digital void technique()

cout << b;

;

int main()

Base *pBase;

Child oChild;

pBase = &oChild;

pBase->approach();

return 0;

In the above instance despite the fact that the approach in invoked on Base magnificence reference, technique of the child will get invoked since its declared as digital.

Q20. What do you mean by natural virtual features in C++? Give an instance?

Ans: Pure digital characteristic is a characteristic which doesn't have an implementation and the same wishes to be applied by using the the next on the spot non-abstract elegance. (A magnificence turns into an summary elegance if there is at-least a single natural digital feature and as a consequence pure digital features are used to create interfaces in c++).

Q21. How to create a pure virtual characteristic?

Ans: A feature is made as pure digital characteristic by means of the the use of a selected signature, " = zero" appended to the characteristic statement as given underneath,

class SymmetricShape

public:

// draw() is a natural virtual characteristic.

Virtual void draw() = zero;

;

Q22. Why pure digital functions are used if they don't have implementation / When does a pure virtual characteristic become useful?

Ans: Pure virtual capabilities are used while it does not make experience to offer definition of a virtual characteristic in the base magnificence or a proper definition does not exists in the context of base class. Consider the above instance, elegance SymmetricShape is used as base magnificence for shapes with symmetric shape(Circle, rectangular, equilateral triangle and so on). In this example, there exists no proper definition for function draw() in the base class SymmetricShape alternatively the kid instructions of SymmetricShape (Cirlce, Square and so forth) can enforce this approach and draw right form.

Q23. What is digital destructors? Why they are used?

Ans: [This c++ interview question is in a way related to polymorphism.]

Virtual destructors are used for the identical motive as virtual features. When you get rid of an item of subclass, that's referenced by means of a parent elegance pointer, best destructor of base elegance gets achieved. But if the destructor is defined using virtual keyword, each the destructors [ of parent and sub class ] gets invoked.

Q24. What you mean with the aid of early binding and overdue binding? How it's far associated with dynamic binding?

Ans: [This c++ interview question is related to question about virtual functions ]

Binding is the method of linking actual address of capabilities or identifiers to their reference. This happens particularly two instances.

During compilation : This is known as early binding

For all the direct characteristic references compiler will update the reference with real deal with of the technique.

At runtime : This is referred to as past due binding.

In case of virtual characteristic calls the use of a Base reference, as in proven in the example of query no: 2, compiler does not understand which approach will get called at run time. In this situation compiler will update the reference with code to get the deal with of characteristic at runtime.

Dynamic binding is another name for overdue binding.

Q25. What is supposed by using reference variable in C++?

Ans: In C++, reference variable permits you create an alias (2d call) for an already existing variable. A reference variable may be used to access (read/write) the unique information. That manner, both the variable and reference variable are attached to equal reminiscence area. In effect, if you exchange the price of a variable the use of reference variable, each gets changed (because each are connected to same memory region).

Q26. How to create a reference variable in C++

Ans: Appending an ampersand (&) to the cease of datatype makes a variable eligible to apply as reference variable.

Int a = 20;

int& b = a;

The first announcement initializes a an integer variable a. Second announcement creates an integer reference initialized to variable a

Take a study the beneath instance to peer how reference variables paintings.

Int major ()

int   a;

int&  b = a;

 

a = 10;

cout << "Value of a : " << a << endl;

cout << "Value of a reference (b) : " << b  << endl;

 

b = 20;

cout << "Value of a : " << a << endl;

cout << "Value of a reference (b) : " << b  << endl;

 

return zero;

Above code creates following output.

Value of a : 10

Value of a reference (b) : 10

Value of a : 20

Value of a reference (b) : 20

Q27. What are the distinction between reference variables and tips in C++?

Ans: [This question is usually asked in a twisted way during c++ interviews. Sometimes the interviewer might use examples and ask you to find the error.]

Pointers    Reference Variables

Pointers can be assigned to NULL    References cannot be assigned NULL. It must constantly be related to actual memory, now not NULL.

Pointers may be (re)pointed to any object, at any time, any variety of times all through the execution.    Reference variables must be initialized with an object when they're created and that they can't be reinitialized to consult another item

Pointer has own reminiscence deal with and area on stack    Reference variables has vicinity on stack, however shares the identical memory region with the item it discuss with.
 

Q28. What will the road of code below print out and why?

Ans: cout << 25u - 50;

The answer is not -25. Rather, the answer (which will surprise many) is 4294967271, assuming 32 bit integers. Why?

In C++, if the types of two operands differ from one another, then the operand with the “lower type” will be promoted to the type of the “higher type” operand, using the following type hierarchy (listed here from highest type to lowest type): long double, double, float, unsigned long int, long int, unsigned int, int (lowest).

So when the two operands are, as in our example, 25u (unsigned int) and 50 (int), the 50 is promoted to also being an unsigned integer (i.E., 50u).

Moreover, the result of the operation will be of the type of the operands. Therefore, the result of 25u - 50u will itself be an unsigned integer as well. So the result of -25 converts to 4294967271 when promoted to being an unsigned integer.

C++ supports multiple inheritance. What is the “diamond problem” that can occur with multiple inheritance? Give an example.

Let’s consider a simple example. A university has people who are affiliated with it. Some are students, some are faculty members, some are administrators, and so on. So a simple inheritance scheme might have different types of people in different roles, all of whom inherit from one common “Person” class. The Person class could define an abstract getRole() method which would then be overridden by its subclasses to return the correct role type.

But now what happens if we want to model a the role of a Teaching Assistant (TA)? Typically, a TA is both a grad student and a faculty member. This yields the classic diamond problem of multiple inheritance and the resulting ambiguity regarding the TA’s getRole() method:

Which getRole() implementation should the TA inherit? That of the Faculty Member or that of the Grad Student? The simple answer might be to have the TA class override the getRole() method and return newly-defined role called “TA”. But that answer is also imperfect as it would hide the fact that a TA is, in fact, both a faculty member and a grad student.

Q29. What is the error in the code below and how should it be corrected?

Ans: my_struct_t *bar;

/* ... Do stuff, including setting bar to point to a defined my_struct_t object ... */

memset(bar, 0, sizeof(bar));

The last argument to memset should be sizeof(*bar), not sizeof(bar). Sizeof(bar) calculates the size of bar (i.E., the pointer itself) rather than the size of the structure pointed to by bar.

The code can therefore be corrected by using sizeof(*bar) as the last argument in the call to memset.

A sharp candidate might point out that using *bar will cause a dereferencing error if bar has not been assigned. Therefore an even safer solution would be to use sizeof(my_struct_t). However, an even sharper candidate must know that in this case using *bar is absolutely safe within the call to sizeof, even if bar has not been initialized yet, since sizeof is a compile time construct.

Q30. What will i and j equal after the code below is executed? Explain your answer.

Ans: int i = 5;

int j = i++;

After the above code executes, i will equal 6, but j will equal 5.

Understanding the reason for this is fundamental to understanding how the unary increment (++) and decrement (--) operators work in C++.

When these operators precede a variable, the value of the variable is modified first and then the modified value is used. For example, if we modified the above code snippet to instead say int j = ++i;, i would be incremented to 6 and then j would be set to that modified value, so both would end up being equal to 6.

However, when these operators follow a variable, the unmodified value of the variable is used and then it is incremented or decremented. That’s why, in the statement int j = i++; in the above code snippet, j is first set to the unmodified value of i (i.E., 5) and then i is incremented to 6.

Q31. What is the problem in the code below? What would be an alternate way of implementing this that would avoid the problem?

Ans: size_t sz = buf->length();

while ( --sz >= 0 )

/* do something */

The trouble in the above code is that --sz >= zero will constantly be proper so that you’ll in no way go out the while loop (so that you’ll probable come to be corrupting reminiscence or inflicting a few type of reminiscence violation or having a few other software failure, depending on what you’re doing in the loop).

The motives that --sz >= 0 will continually be genuine is that the kind of sz is size_t. Size_t is truely just an alias to one of the essential unsigned integer kinds. Therefore, when you consider that sz is unsigned, it is able to in no way be less than zero (so the condition can in no way be actual).

One instance of an alternative implementation that would keep away from this hassle might be to as an alternative use a for loop as follows:

for (size_t i = 0; i < sz; i++)

/* do something */

Q32. Consider the two code snippets below for printing a vector. Is there any advantage of one vs. The other? Explain.

Option 1:

vector vec;

/* ... .. ... */

for (auto itr = vec.Begin(); itr != vec.End(); itr++) 

itr->print();

Option 2:

vector vec;

/* ... .. ... */

for (auto itr = vec.Begin(); itr != vec.Quit(); ++itr) 

itr->print();

Ans: Although both alternatives will accomplish exactly the equal aspect, the second alternative is higher from a overall performance viewpoint. This is due to the fact the post-increment operator (i.E., itr++) is extra high priced than pre-increment operator (i.E., ++itr). The underlying implementation of the post-increment operator makes a copy of the element before incrementing it and then returns the copy.

Q33. Implement a template function IsDerivedFrom() that takes class C and sophistication P as template parameters. It must return actual whilst elegance C is derived from magnificence P and false in any other case.

Ans: This query checks know-how of C++ templates. An skilled developer will realize that that is already part of the C++11 std library (std::is_base_of) or part of the boost library for C++ (improve::is_base_of). Even an interviewee with handiest passing understanding need to write some thing much like this, usually probable involving a helper class:

template<typename D, typename B>

magnificence IsDerivedFromHelper

class No  ;

class Yes  No no[3]; ;

 

static Yes Test( B* );

static No Test( ... );

public:

enum  Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) ;

;

template <class C, class P>

bool IsDerivedFrom() 

go back IsDerivedFromHelper<C, P>::Is;

Q34. Implement a template boolean IsSameClass() that takes magnificence A and B as template parameters. It need to evaluate class A and B and go back fake whilst they may be distinct lessons and genuine if they're the identical magnificence.

Ans: template <typename T, typename U>

struct is_same

static const bool value = false;

;

template <typename T>

struct is_same<T, T>

static const bool fee = authentic;

;

template <class A, class B>

bool IsSameClass() 

return is_same<A, B>::fee;

 

Q35. Is it feasible to have a recursive inline characteristic?

Ans: Although you can call an inline function from within itself, the compiler will now not generate inline code because the compiler can not determine the depth of recursion at compile time.

Q36. What is the output of the following code:

Ans: #encompass <iostream>

elegance A 

public:

A() 

~A() 

throw 42;

;

int fundamental(int argc, const char * argv[]) 

try 

A a;

throw 32;

 seize(int a) 

std::cout << a;

This application will terminate abnormally. Throw 32 will start unwinding the stack and break class A. The elegance A destructor will throw every other exception throughout the exception dealing with, so that it will motive program to crash. This query is checking out if developer has revel in operating with exceptions.

Q37. You are given library elegance Something as follows:

elegance Something 

public:

Something() 

topSecretValue = forty two;

public:

bool somePublicBool;

int somePublicInt;

std::string somePublicString;

non-public:

int topSecretValue;

;

Implement a technique to get topSecretValue for any given Something* item. The method have to be move-platform well suited and not rely upon sizeof (int, bool, string).

Ans: Create another magnificence which has all the individuals of Something within the identical order, but has extra public method which returns the price. Your duplicate Something class must appear like:

class SomethingReplica 

public:

int getTopSecretValue()  go back topSecretValue; 

public:

bool somePublicBool;

int somePublicInt;

std::string somePublicString;

private:

int topSecretValue;

;

Then, to get the fee:

int foremost(int argc, const char * argv[]) 

Something a;

SomethingReplica* b = reinterpret_cast<SomethingReplica*>(&a);

std::cout << b->getTopSecretValue();

It’s important to avoid code like this in a very last product, however it’s nonetheless an excellent approach whilst handling legacy code, as it may be used to extract intermediate calculation values from a library class. (Note: If it seems that the alignment of the outside library is mismatched in your code, you could solve this the use of #pragma percent.)

Q38. Implement a void feature F that takes guidelines to two arrays of integers (A and B) and a length N as parameters. It then populates B where B[i] is the fabricated from all A[j] in which j != i.

For example: if A = 2, 1, five, 9, then B would be forty five, 90, 18, 10

Ans: This problem seems easy at first look so a careless developer would possibly write some thing like this:

void F(int* A, int* B, int N) 

int m = 1;

for (int i = zero; i < N; ++i) 

m *= A[i];

for (int i = 0; i < N; ++i) 

B[i] = m / A[i];

This will work for the given example, but whilst you add a zero into input array A, this system will crash due to department by means of 0. The correct solution should take that part case into account and seem like this:

void F(int* A, int* B, int N) 

int m = 1;

int numZero = zero;

int zeroIndex = -1;

for (int i = 0; i < N; ++i) 

B[i] = zero;

if (A[i] == 0) 

++numZero;

zeroIndex = i;

 else 

m *= A[i];

if (numZero == zero) 

for (int i = zero; i < N; ++i) 

B[i] = m / A[i];

return;

if (numZero >= 2) 

return;

B[zeroIndex] = m;

The presented answer above has a Big O complexity of O(n). While there are simpler answers available (ones that could ignore the need to take zero into account), that simplicity has a price of complexity, typically jogging notably slower.

Q39. When you must use digital inheritance?

Ans: While it’s perfect to keep away from virtual inheritance altogether (you need to realize how your magnificence is going to be used) having a strong understanding of the way digital inheritance works continues to be essential:

So if you have a class (elegance A) which inherits from 2 parents (B and C), both of which proportion a determine (magnificence D), as established under:

#encompass <iostream>

elegance D 

public:

void foo() 

std::cout << "Foooooo" << std::endl;

;

magnificence C:  public D 

;

class B:  public D 

;

class A: public B, public C 

;

int main(int argc, const char * argv[]) 

A a;

a.Foo();

If you don’t use digital inheritance in this example, you may get two copies of D in elegance A: one from B and one from C. To restore this you need to exchange the declarations of classes C and B to be digital, as follows:

magnificence C:  digital public D 

;

elegance B:  virtual public D 

;

 Q40. Is there a distinction between class and struct?

Ans: The only difference among a category and struct are the access modifiers. Struct participants are public with the aid of default; magnificence individuals are non-public. It is ideal practice to apply training while you want an item that has methods and structs if you have a easy records item.

Q41. What is the output of the following code:

Ans: #encompass <iostream>

int most important(int argc, const char * argv[]) 

int a[] = 1, 2, 3, 4, five, 6;

std::cout << (1 + three)[a] - a[0] + (a + 1)[2];

The above will output eight, due to the fact that:

(1+3)[a] is the same as a[1+3] == 5

a[0] == 1

(a + 1)[2] is similar to a[3] == 4

This query is checking out pointer mathematics understanding, and the magic in the back of square brackets with tips.

While some may argue that this isn’t a valuable query as it appears to most effective take a look at the functionality of analyzing C constructs, it’s nevertheless crucial for a candidate so that it will paintings thru it mentally; it’s not a solution they’re anticipated to recognise off the top of their head, but one in which they talk approximately what conclusion they attain and the way.

 Q42. What is the output of the subsequent code:

Ans: #encompass

magnificence Base 

virtual void technique() std::cout << "from Base" << std::endl;

public:

virtual ~Base() technique();

void baseMethod() method();

;

class A : public Base

void method() std::cout << "from A" << std::endl;

public:

~A() method();

;

int main(void) 

Base* base = new A;

base->baseMethod();

delete base;

return 0;

The above will output:

from A

from A

from Base

The important thing to word here is the order of destruction of instructions and how Base’s approach reverts lower back to its own implementation once A has been destroyed.

 Q43. Explain the risky and mutable key phrases

Ans: The risky key-word informs the compiler that a variable may be used by more than one threads. Variables which are declared as volatile will now not be cached by using the compiler to make sure the most up to date value is held.

The mutable keyword can be used for class member variables. Mutable variables are allowed to alternate from within const member capabilities of the magnificence.

Q44. How frequently will this loop execute? Explain your solution.

Ans: unsigned char half_limit = 150;

for (unsigned char i = 0; i < 2 * half_limit; ++i)

// do something;

If you said 300, you'll had been accurate if i had been declared as an int. However, due to the fact that i was declared as an unsigned char, the corrct answer is this code will result in an endless loop.

Here’s why:

The expression 2 * half_limit will get promoted to an int (based totally on C++ conversion regulations) and will have a price of 300. However, on the grounds that i is an unsigned char, it's miles rerepsented with the aid of an eight-bit cost which, after accomplishing 255, will overflow (so it will move back to 0) and the loop will therefore go on for all time.




CFG