200 C++ interview questions and answers

          

C++ interview questions and answers


Part 2    Part 3    Part 4    Part 5    Part 6    Part 7    Part 8    Part 9    Part 10   

QUESTION - A property which is not true for classes is that they

-are removed from memory when not in use
-permit data to be hidden from other classes.
-bring together all aspects of an entity in one place.
-Can closely model objects in the real world.

View Answer / Hide Answer

ANSWER - bring together all aspects of an entity in one place.
 

QUESTION - Which of the following cannot be legitimately passed to a function

-A constant
-A variable.
-A structure
-A header file.

View Answer / Hide Answer

ANSWER - A header file.

QUESTION - this pointer

-implicitly points to an object
-can be explicitly used in a class.
-can be used to return an object.
-All of the above.

View Answer / Hide Answer

ANSWER - All of the above.

QUESTION - To perform stream I/O with disk files in C++, you should

-open and close files as in procedural languages.
-use classes derived from ios.
-use C language library functions to read and write data.
-include the IOSTREAM.H header file.

View Answer / Hide Answer

ANSWER - use classes derived from ios.

QUESTION - RunTime Polymorphism is achieved by ______

-friend function
-virtual function
-operator overloading
-function overloading

View Answer / Hide Answer

ANSWER - virtual function

QUESTION - In dynamic binding the code matching the object under current reference will be called at.

-Compile time
-Run time
-Editing time
-Binding time

View Answer / Hide Answer

ANSWER - Run time

QUESTION - Following are the object oriented programming language

-JAVA
-C++
-Small talk
-All of above

View Answer / Hide Answer

ANSWER - All of above

QUESTION - How many characters are recognized by ANSI C++?

-32
-64
-no limit
-none of these

View Answer / Hide Answer

ANSWER - no limit

QUESTION - Inheritance is the process by which

-Object of one class acquires the properties of objects of another class
-Variable of one class acquires the properties of variable of another class
-Object of one class acquires the properties of objects of same class
-Variable of one class acquires the properties of objects of another class

View Answer / Hide Answer

ANSWER - Object of one class acquires the properties of objects of another class

QUESTION - Class members are by default

-Public
-Private
-Protected
-Inherited

View Answer / Hide Answer

ANSWER - Private

QUESTION - How many words can be read by cin?

-one
-Two
-Three
-Four

View Answer / Hide Answer

ANSWER - one

QUESTION - A function that is called automatically when an object is created is called as

-constant
-constructor
-static
-friend

View Answer / Hide Answer

ANSWER - constructor

QUESTION - The null character will take space of

-0 byte
-2 byte
-1 byte
-8 byte
View Answer / Hide Answer

ANSWER - 1 byte

QUESTION - This operator is used to allocate memory

-new
-delete
-static
-real
View Answer / Hide Answer

ANSWER - new

QUESTION - Which one is correct to declare an interface in a class?

-By making all the methods pure virtual in a class
-By making all the methods abstract using the keyword abstract in a class
-By declaring the class as interface with the keyword interface
-It is not possible to create interface class in C++

View Answer / Hide Answer

ANSWER - By making all the methods pure virtual in a class

QUESTION - Keywords support dynamic method of resolution is

-abstract
-Virtual
-Dynamic
-Typeid

View Answer / Hide Answer

ANSWER - Virtual

QUESTION - Which pointer is implicit pointer passed as the first argument for non-static member functions?

-self pointer
-std::auto_ptr pointer
-Myself pointer
-this pointer

View Answer / Hide Answer

ANSWER - this pointer

QUESTION - Inventor of C++ language is

-John Dell
-Bjarne Stroustrup
-Thomusn Steve
-Karl Thomus

View Answer / Hide Answer

ANSWER - Bjarne Stroustrup

QUESTION - Destructor can have following number of argument

-2
-1
-0

View Answer / Hide Answer

ANSWER - 0

C++ interview questions contributed - April 06, 2013 at 15:00 PM by Kshipra Singh 

1. Explain abstraction.

- Simplified view of an object in user’s language is called abstraction.
- It is the simplest, well-defined interface to an object in OO and C++ that provides all the expected features and services to the user in a safe and predictable manner.
- It provides all the information that the user requires.
- Good domain knowledge is important for effective abstraction.
- It separates specifications from implementation & keeps the code simpler and more stable.

2. a.) What is the real purpose of class – to export data?

No, the real purpose of a class is not to export data. Rather, it is to provide services. Class provides a way to abstract behaviour rather than just encapsulating the bits.

b.) What things would you remember while making a interface?
- A class’s interface should be sensible enough. It should behave the way user expects it to.
- It should be designed from the outside in.

3. Explain the benefits of proper inheritance.

The biggest benefits of proper inheritance are : a.) substitutability and b.) extensibility.

Substitutability – The objects of a properly derived class can be easily and safely substituted for an object of its base class.

Extensibility – The properly derived class can be freely and safely used in place of its base class even if the properly derived class is created a lot later than defining the user code. Extending the functionalities of a system is much easier when you add a properly derived class containing enhanced functionalities.

4. Does improper inheritance have a potential to wreck a project?

Many projects meet a dead end because of bad inheritance. So, it certainly has the potential to wreck a project.

Small projects still have a scope to avoid the complete consequence of bad inheritance if the developers communicate and co-ordinate with an easy system design. This kind of a luxury is not possible in big projects, which means that the code breaks in a way difficult and at times impossible way to fix it.

5. How should runtime errors be handled in C++?

- The runtime errors in C++ can be handled using exceptions.
- This exception handling mechanism in C++ is developed to handle the errors in software made up of independently developed components operating in one process and under synchronous control.
- According to C++, any routine that does not fulfil its promise throws an exception. The caller who knows the way to handle these exceptions can catch it.

6. When should a function throw an exception?

A function should throw an exception when it is not able to fulfil its promise.

As soon as the function detects a problem that prevents it from fulfilling its promise, it should throw an exception. If the function is able to handle the problem, recover itself and deliver the promise, the exception should not be thrown.

If an event happens very frequently then exception handling is not the best way to deal with it. It requires proper fixation.

7. Where are setjmp and longjmp used in C++?

-Setjmp and longjmp should not be used in C++.
- Longjmp jumps out of the function without unwinding the stack. This means that the local objects generated are not destructed properly.
- The better option is to use try/catch/throw instead. They properly destruct the local objects.

8. Are there ant special rules about inlining?

Yes, there are a few rules about inlining –
a.) Any source files that used the inline function must contain the function’s definition.
b.) An inline function must be defined everywhere. The easier way to deal with this to define the function once in the class header file and include the definition as required. The harder way is to redefine the function everywhere and learn the one-definition rule.
c.) Main() can not be inline.

9. Explain one-definition rule (ODR).

According to one-definition rule, C++ constructs must be identically defined in every compilation unit they are used in.

As per ODR, two definitions contained in different source files are called to be identically defined if they token-for-token identical. The tokens should have same meaning in both source files.

Identically defined doesn’t mean character-by-character equivalence. Two definitions can have different whitespace or comments and yet be identical.

10. What are the advantages of using friend classes?

- Friend classes are useful when a class wants to hide features from users which are needed only by another, tightly coupled class.
- Implementation details can be kept safe by providing friend status to a tightly cohesive class.

11. What is the use of default constructor?

- It is a constructor that does not accept any parameters.
- If there is no user-defined constructor for a class, the compiler declares a default parameterless constructor called default constructor. It is an inline public member of its class.
When the compiler uses this constructor to create an object – the constructor will have no constructor initializer and a null body.

12. Differentiate between class and structure.

- The members of structures are public while those of a class are private.
- Classes provide data hiding while structures don’t.
- Class bind both data as well as member functions while structures contain only data.

13. Explain container class.

-Class to hold objects in memory or external storage. It acts as a generic holder.
- It has a predefined behaviour and a known interface.
- It is used to hide the topology used for maintaining the list of objects in memory.

The container class can be of two types:

- Heterogeneous container – Here the container class contains a group of mixed objects
- Homogeneous container - Here the container contains all the same objects.

14. a.) What is namespace?

- Namespaces are used to group entities like classes, objects and functions under a name.

b.) Explain explicit container.
- These are constructors that cannot take part in an implicit conversion.
- These are conversion constructors declared with explicit keyword.
- Explicit container is reserved explicitly for construction. It is not used by the compiler to implement an implied conversion of types.

15. Explain class invariant.

- It is a condition that ensures correct working of a class and defines all the valid states for an object.
- When an object is created class invariants must hold.
- It is necessary for them to be preserved under all operations of the class.
- All class invariants are both preconditions as well as post-conditions for all operations or member functions of the class.

16. Differentiate between late binding and early binding. What are the advantages of early binding?

a.) Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time.

b.) Late binding occurs through virtual functions while early binding takes place when all the information needed to call a function is known at the time of compiling.

Early binding increases the efficiency. Some of the examples of early binding are normal function calls, overloaded function calls, and overloaded operators etc.

17. Explain public, protected, private in C++?

These are three access specifiers in C++.

- Public – Here the data members and functions are accessible outside the class.

- Protected - Data members and functions are available to derived classes only.

- Private - Data members and functions are not accessible outside the class.

Explain Copy Constructor
When do you call copy constructors?
Name the implicit member functions of a class.
Explain storage qualifiers in C++.
Explain dangling pointer
In what situations do you have to use initialization list rather than assignment in constructors.
When does a class need a virtual destructor?
What is the type of “this” pointer? When does it get created?
How would you differentiate between a pre and post increment operators while overloading?
What is a pdb file?
You run a shell on UNIX system. How would you tell which shell are you running?
What are Stacks? Give an example where they are useful.
Differentiate between an external iterator and an internal iterator? What is the advantage of an external iterator
Do you think the following code is fine? If not, what is the problem?
In a function declaration, what does extern mean?
You want to link a C++ program to C functions. How would you do it?
Exlpain STL.
What are the different types of STL containers?
Explain Stack unwinding
How would you find out if a linked-list is a cycle or not?

1. Explain Copy Constructor.

It is a constructore which initializes it's object member variable with another object of the same class. If you don't implement a copy constructor in your class, the compiler automatically does it.

2. When do you call copy constructors?

Copy constructors are called in these situations:
i.)when compiler generates a temporary object
ii.)when a function returns an object of that class by value
iii.)when the object of that class is passed by value as an argument to a function
iv.)when you construct an object based on another object of the same class

3. Name the implicit member functions of a class.

i.) default ctor
ii.) copy ctor
iii.) assignment operator
iv.) default destructor
v.) address operator

4. Explain storage qualifiers in C++.

i.) Const - This variable means that if the memory is initialised once, it should not be altered by a program.
ii.) Volatile - This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
iii.) Mutable - This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

5. Explain dangling pointer.

When the address of an object is used after its lifetime is over, dangling pointer comes into existence. Some examples of such situations are: Returning the addresses of the automatic variables from a function or using the address of the memory block after it is freed.

6. In what situations do you have to use initialization list rather than assignment in constructors.

When you want to use non-static const data members and reference data members you should use initialization list to initialize them.

7. When does a class need a virtual destructor?

If your class has at least one virtual function, you should have a virtual destructor. This allows you to delete a dynamic object through a baller to a base class object. In absence of this, the wrong destructor will be invoked during deletion of the dynamic object.

8. What is the type of “this” pointer? When does it get created?

It is a constant pointer type. It gets created when a non-static member function of a class is called.

9. How would you differentiate between a pre and post increment operators while overloading?

Mentioning the keyword int as the second parameter in the post increment form of the operator++() helps distinguish between the two forms.

10. What is a pdb file?

A program database (PDB) file contains debugging and project state information that allows incremental linking of a Debug configuration of the program. This file is created when you compile a C/C++ program with /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug.

11. You run a shell on UNIX system. How would you tell which shell are you running?

To check this you can simply do the Echo $RANDOM.

The results will be:

- Undefined variable if you are from the C-Shell,
- A return prompt if you are from the Bourne shell,
- A 5 digit random number if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

12.What are Stacks? Give an example where they are useful. 

A Stack is a linear structure in which insertions and deletions are always made at one end i.e the top - this is termed as last in, first out (LIFO). Stacks are useful when we need to check some syntex errors like missing parentheses. 

13. Differentiate between an external iterator and an internal iterator? What is the advantage of an external iterator. 

An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through while an internal iterator is implemented with member functions of the class that has items to step through. With an external iterator many different iterators can be active simultaneously on the same object - this is its basic advantage. 

14. Do you think the following code is fine? If not, what is the problem? 

T *p = 0;
delete p;

No, the code has a problem. The program will crash in an attempt to delete a null pointer.  

15. In a function declaration, what does extern mean?

The extern here tells the compiler about the existence of a variable or a function, even though the compiler hasn’t yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

16. You want to link a C++ program to C functions. How would you do it?

This can be done by using the extern "C" linkage specification around the C function declarations.

17. Exlpain STL.

STL stands for Standard Template Library. It is a library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.

18. What are the different types of STL containers?

Following are the 3 types of STL containers:

1. Adaptive containers - for e.g. queue, stack
2. Associative containers - for e.g. set, map
3. Sequence containers - for e.g. vector, deque

19. Explain Stack unwinding

Stack unwinding is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

20. How would you find out if a linked-list is a cycle or not?

We can find out if the linked-list is not a cycle by using two pointers. One of them goes 2 nodes every time while the second one goes at 1 node each time. If there is a cycle, the one that goes 2 nodes each time will meet the one that goes slower. If this happens, you can say that the linked-list is a cycle else not.  

When is dynamic checking necessary?

Latest answer: Dynamic checking is necessary in the following scenarios: Whenever the definition of a variable is not necessary before its usage..............
Read answer

Define structured programming. posted on April 01, 2011

Latest answer: Structured programming techniques use functions or subroutines to organize the programming code. The programming purpose is broken into smaller pieces.............
Read answer

Explain object oriented programming. 

Latest answer: Object oriented programming uses objects to design applications. This technique is designed to isolate data. The data and the functions that operate on the data are combined into single unit..............
Read answer

What are the ways to comment statement in C++?

Latest answer: C++ supports two types of comments..............
Read answer

What is structure in C++?

Latest answer: The C++ programming technique allows defining user defined datatypes through structure. The syntax to declare structure is as follows:.............
Read answer

What is reference variable in C++?

Latest answer: A reference variable is just like pointer with few differences. It is declared using & operator. A reference variable must always be initialized. The reference variable.............
Read answer

What is class using C++?

Latest answer: A class holds the data and functions that operate on the data. It serves as the template of an object..............
Read answer

What is local class in C++?

Latest answer: Local class is define within the scope of a function and nested within a function..............
Read answer

What is the default access level?

Latest answer: The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private..............
Read answer

What is friend class in C++?

Latest answer: When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods..............
Read answer

Explain default constructor. What is a default constructor?

Latest answer: Default constructor is the constructor with no arguments or all the arguments has default values..............
Read answer

Define abstraction. What is abstraction? What is an abstraction and why is it important?

Latest answer: The process of hiding unnecessary data and exposing essential features is called abstraction. Abstraction is separating the logical properties from implementation details..............
Read answer

What is overriding?

Latest answer: Defining a function in the derived class with same name as in the parent class is called overriding. In C++, the base class member can be overridden by the derived.............
Read answer

What is copy constructor?

Latest answer: A copy constructor is a special type of constructor that is used to create an object as a copy of an existing object..............
Read answer

Define private, protected and public access control.

Latest answer: Private is the default access specifier for every declared data item in a class. Private data belongs to the same class in which it is created and can only be used.............
Read answer

What is Turbo C++?

Latest answer: Turbo C++ provides an environment called IDE (Integrated Development.............
Read answer

How to control the number of chars read in a string by using scanf()?

Latest answer: Doing this limits the length of the characters that will be read by scanf() to 20 characters maximum although the buffer can hold 25 characters. .............
Read answer

How to detect an end of a file?

Latest answer: You can either use the ifstream object ‘fin’ which returns 0 on an end of file or you can use eof().............
Read answer

What are recursive functions? What are the advantages and disadvantages of Recursive algorithms?

Latest answer: A recursive function is a function which calls itself.  The advantages of recursive functions are: -Avoidance of unnecessary calling of functions. A substitute for iteration where the iterative solution is very complex..............
Read answer

What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator.

Latest answer: An internal iterator is implemented by the member functions of the class which has the iteration logic..............
Read answer

Explain passing objects by reference, passing objects by value and passing objects by pointer.

Latest answer: Pass by value: The callee function receives a set of values that are to be received by the parameters. All these copies of values have local scope, i.e., they can be accessed only by the callee function..............
Read answer

Explain the concepts of throwing and catching exceptions with an example using C++.

Latest answer: C++ provides a mechanism to handle exceptions which occurs at runtime. C++ uses the keywords – throw, catch and try to handle exception mechanism..............
Read answer

What are the advantages of “throw.....catch” in C++?

Latest answer: The following are the advantages of throw and catch in c++. Code isolation: All code that is to be handled when an exception raises is placed in the catch block, which is not part of the original code..............
Read answer

What are friend classes? What are advantages of using friend classes?

Latest answer: The friend function is a ‘non member function’ of a class. It can access non public members of the class. A friend function is external to the class definition..............
Read answer

What are zombie objects in C++? Explain its purpose.

Latest answer: An object creation of a class is failed before executing its constructor. As a constructor would not return a value, there is no confirmation that whether the constructor is executed completely or not..............
Read answer

Explain the difference between Stack and Queue

Latest answer: Stack is a Last in First out (LIFO) data structure whereas Queue is a First in First out (FIFO) data structure..............
Read answer

What is Stack? Explain its uses.

Latest answer: Stack is a Last in First out (LIFO) data structure. It is a linear structure and one can insert and delete from one end only which is called the top. It is very effective in.............
Read answer

What is a Wrapper class?

Latest answer: Wrapper classes are classes that allow primitive types to be accessed as objects..............
Read answer

What do you mean by stack unwinding?

Latest answer: When an exception is thrown, C++ calls destructors to destroy all the objects formed since the beginning of the try block. The objects are destroyed in the.............
Read answer

What is the use of ‘using’ declaration?

Latest answer: In using-declaration, we have using keyword followed by a fully qualified name of a namespace member..............
Read answer

What is the difference between Mutex and Binary semaphore?

Latest answer: Semaphore synchronizes processes where as mutex synchronizes threads running in the same process..............
Read answer

What is the scope resolution operator?

Latest answer: Scope resolution operator allows a program to reference an identifier in the global scope that is hidden by another identifier with the same name in the local scope..............
Read answer

What are the advantages of inheritance?

Latest answer: Code reusability
Saves time in program development..............
Read answer

What is a conversion constructor?

Latest answer: It is a constructor that accepts one argument of a different type..............
Read answer

Explain the advantages of inline functions.

Latest answer: It relieves the burden involved in calling a function. It is used for functions that need fast execution..............
Read answer

Explain the different access specifiers for the class member in C++.

Latest answer: private: It is default one and can be access from class member of the same class.
protected: The protected members can be access from member functions of the.............
Read answer

What is the importance of mutable keyword?

Latest answer: The mutable keyword allows the data member of a class to change within a const member function..............
Read answer

Pointer vs. reference.

Latest answer: A reference must be initialized at the time of declaration whereas not needed in case of pointer. A pointer can point to a null object..............
Read answer

Explain how to call C functions from C++.

Latest answer: The extern keyword is used to call C functions from C++.............
Read answer

How do we declare a class as a friend of another class?
Class vs. Structure

Latest answer: Class: Class has private as default access specifier. Default inheritance type is private..............
Read answer

Explain how to call a base member function from derived class member function.
Is it possible to overload a constructor?

Latest answer: Yes it is possible. A constructor can be overloaded to pass different arguments to the object..............
Read answer

Overriding vs. overloading

Latest answer: Overloading means having methods with same name but different signature
Overriding means rewriting the virtual method of the base class.............
Read answer

What do you mean by binding? Static vs. dynamic binding

Latest answer: Binding means connecting the function call to a function implementation..............
Read answer

What is abstract class?

Latest answer: A class whose object can't be created is abstract class. You can create a class as abstract by declaring one or more virtual functions to pure..............
Read answer

Vector vs. Map

Latest answer: In a vector, all the elements are in a sequence whereas Map stores element in the form of a key-value association pair..............
Read answer

List down elements of an object oriented language.

Latest answer: A class is a user defined data type. It serves as a template of the objects.....
Read answer

Explain constructors and destructors.

Latest answer: Constructors are the member functions of the class that executes automatically whenever an object.......
Read answer

Define access privileges in C++.

Latest answer: You have access privileges in C++ such as public, protected and private that helps.........
Read answer

Explain the difference between structures and classes

Latest answer: Syntactically and functionally, both structures and classes are...........
Read answer

Explain container class and its types in C++.

Latest answer: A container stores many entities and provide sequential or direct access to them. List, vector and strings are............
Read answer

Define storage classes in C++

Latest answer: Storage class defined for a variable determines the accessibility and longevity of the variable. The accessibility.......
Read answer

Define an Iterator class

Latest answer: A container class hold group of objects and iterator class is used to traverse through the objects maintained..........
Read answer

What are pure virtual functions?

Latest answer: The base class with pure virtual function can't be instantiated since there is no definition...........
Read answer

ATL Server interview questions

Latest answer: Explain the concepts and capabilities of ATL Server. Explain the ATL Server architecture.
Why ATL Server? What is SRF Files? Explain with an example................
Read answer

C++ COM and Active X: Interview Questions

Latest answer: What is the STL, standard template library? What is the object serialization? What are ActiveX and OLE. What are GUID? Why does COM need GUIDs? What is a type library? What is the IUnknown interface? Explain Binary object model. How does COM provide language transparency?..........
Read answer

What is object oriented programming (OOP)?
What are the various elements of OOP?
Explain an object, class and Method.
Define Encapsulation and Information Hiding in OOP.
Explain Inheritance and Polymorphism in OOP.
What are the advantages of OOP? 

Write your comment - Share Knowledge and Experience

Discussion Board
Advanced C++ interview questions - senior level C++ interview

Explain the public method for the data type conversions.

• A class may be having a public method for the specific data type conversions.

for example:

class B
{
double value;
public:
B(int i )
operator double()
{
return value;
}
};

B BObject;

double i = BObject; // the conversion operator is called to assign the value.


What is diff between malloc()/free() and new/delete?

• The malloc allocates memory for object in the heap but not invokes object's constructor for initiallizing the object.

• new also allocates thememory and also invokes constructor to initialize the object.

• malloc() and free() are not able to support object semantics but does not construct and destruct any objects

• string * ptr = (string *)(malloc (sizeof(string)))

• int *p = ( int * ) ( malloc ( sizeof(int) ) );

• int * p = new int;


new and delete,both can be overloaded in a class :

• "delete" first calls the object's termination routine and then releases the space the object occupied on the heap memory.

If an array of objects are created using new, then delete will be dealing with an array by preceding the name & with an empty [] :-

Int_t *my_ints = new Int_t[10];

...

delete []my_ints;


Define macro.

• There is no way for the compiling to verify that the macro parameters are of compatible types.

• The macro can be expanded without any special type checking.

• If macro parameter is having a post incremented variable ( like c++ ), the increment will be performed twice.

for example:

Macro:

#define min(i, j) ( i < j ? i : j )

template:
template
T min ( T i, T j )
{
return i < j ? i : j ;
}



What are C++ storage classes?

storage classes types are :

• auto: This the default . Variables are naturally created and initialized when they are defined and are destroyed at the end of the block contained their definition.

• register: It's a type of auto variable. This helps the compiler to use a CPU register for performance

• static: It's a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function.

• extern: It's a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file.

What is a virtual function?

• If the derived class overrides the base class method by redefining the same function, then if client will want to access redefined the method from derived class through a pointer from base class object, then we have to define this function in the base class as a virtual function.

class parent
{
void Show()
{
cout << "i'm parent" << endl;
}
};

class child : public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_ object_ ptr -> show() // calls parent->show() i

now we goto virtual world...

class parent
{
virtual void Show()
{
cout << "i'm parent" << endl;
}
};

class child : public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls child->show()


What is pure virtual function? or what is abstract class?

While we define function prototype in a base class without implementation .The base class is called abstract class

Example of a pure virtual function or abstract class this way..

class B
{
void f() = 0;
}

B MyB; // compilation error


Advanced C++ interview 07-18-2012 06:09 AM

Basic C++ interview questions - Frequently asked C++ interview

Write some differences between an external iterator and an internal iterator? Describe the advantage of an external iterator.

• An external iterator gets implemented as a separate class that can be "attach" to the object which is having items to step through .

• In case of an internal iterator it is implemented with a member function of the class which are having the items to step through.

• With the help of an external iterator many different iterators can be activated simultaneously on the same object.


Verify the following code. Point out the problems.

T *p = 0;

delete p;

• No, the code has a problem.

• The program will be crashed for an attempt to delete a null pointer.


Incase of a function declaration, what is extern means?

• The extern tells the compiler regarding the existence of a variable or a function.

• The variable or function can be defined within another file


How can you link a C++ program to C functions?

This can be done Intwo methods ;

• First by using the extern "C" linkage specification

• The linkage is done in the C function declarations.

Define STL.

• STL stands for Standard Template Library.

• It is the library for container templates.

• This is approved by the ANSI committee for including in the standard C++ specification.

Name the different types of STL containers.

The 3 types of STL containers are:

• Adaptive containers - e.g. stack, queue,

• Associative containers - for e.g. set, map

• Sequence containers - e.g. vector, deque

What is Stack unwinding?

• Stack unwinding is the process for exception handling

• It takes place when the destructor is being called.

• The destructor calls all the local objects between the place where the exception had been thrown and where it had been caught.

How come you find out if a linked-list is a cycle or not?

We can find out if the linked-list is cycle or not by the use of two pointers:

• One of them will go 2 nodes

• Each time when the second one goes at node 1 .

• Incase there is a cycle, the one that goes 2 nodes each time will meet the one that goes slower. If this occurs, we can confirm that the linked-list is a cycle else not.


Define a nested class. Explain how it can be useful.

• A nested class is said to be a class which is enclosed in the scope of another class.

For example:

// Example : Nested class
//
class OuterClass
{
class NestedClass
{
// ...
};
// ...
};

• Nested classes are of great use for organizing code and for controlling access and dependencies.

• Nested classes do obey access rules.

So, if NestedClass is when public ,any code can be named as OuterClass::NestedClass.


When does the C++ compiler create temporary variables?

If the function parameter is a "const reference", the compiler generates temporary variables in the following 2 ways.

• a) If the actual argument is the correct type, but it isn't Lvalue

double Cubes(const double & num)
{
numb = numb * numb * numb;

return numb;

}

double temp = 2.0;

double value = cubes(3.0 + temp); // the argument is said to be an expression ,not the Lvalue;


• b) A type can be converted to the correct type

long temp = 3 L;

double value = cuberoot ( temp ) ;


Explain the differences between List x; & List x();.

There exists a big difference which is explained via a code below:

• Let, List is a name of any class.

Then function f() evokes a local List object x:

void f()

{

List x; // Local object x

...

}

But the function g() invokes f() which eventually returns a List:

void g()

{


List x(); // function which returns the List

...

}

What is conversion constructor?

• The constructor with a single argument is called as conversion constructor and it can be used for the type conversion.

for example:

class B
{
public:
B( int i );
};


B B Object = 10 ; // assigning int 10 B object

Basic C++ interview 07-18-2012 06:08 AM

C++ interview questions and answers for freshers

Define Copy Constructor.

• It is a simple constructor.

• With a different object of the same class, it initializes it's object member variable.

• If we don't implement copy constructor, it does automatically.

When do we use copy constructors?

Copy constructors are called in these scenarios below:

• At the time of generating a temporary object by the compiler.

• If a function is returning an object of that particular class by value

• At the time of passing by value as an argument to a function by the object of that class

• At the time of constructing an object based on a different object of the same class

What are the implicit member functions of class?

The implicit member functions are

• default ctor

It is mainly used for initializing.

• copy ctor

It is used for creating a new object as a copy of the existing one.

• assignment operator

It is the operator used for assigning values to the variables.

• default destructor

It acts just like the inverse of constructor for de-initializing variables.

• address operator

It connects an operand to its pointer variable.

What are the storage qualifiers?

The storage qualifiers are:

• Const - If the memory gets initialized once, it will remain indifferent.

• Volatile - If the value in the memory location will be altered though nothing is changed in the program code, this value may be changed.

• Mutable - This means that if a member of a structure or class can be altered though a particular structure variable, class, or class member function will remain constant.

What is dangling pointer?

• Pointer that does not point to a proper or valid object of the correct type is called Dangling pointer.

• If the address of an object is used after its lifetime, the concept of dangling pointer will come.

The examples of such situations can be given as:

• To return the addresses of any automatic variable from the function or by using the address of the memory block after it has got freed.

Do we have to use initialization list in spite of the assignment in constructors?

• We can use non-static const data members and reference data members.

• We have to use initialization list for initializing them.

When does a class need a virtual destructor?

• If our class has at least one virtual function, we have to have a virtual destructor.

• This will allow deleting a dynamic object.

• In absence of this, the wrong destructor will be invoked during deletion of the dynamic object.

What is type of “this” pointer? Explain when it is get created?

• ''this' is a constant pointer type.

• It will get created if a non-static member function of the class is called up.

How we can differentiate between a pre and post increment operators during overloading?

• We have to mention the keyword int as the second parameter

• It is to be mentioned the post increment form of the operator++() .

Define a pdb file.

• It's a program database (PDB) file.

• This file contains debugging and project state information which does the incremental linking of a Debug configuration for the program.

• This file gets created at the time of compiling a C/C++ program with the help of /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug.

When do we run a shell in the UNIX system? How will you tell which shell you are running?

• For checking this we can simply run the command Echo $RANDOM.

Thus the results obtained will be:

• Undefined variable if we'll do this in the C-Shell.

• A return prompt will be available if we'll execute in the Bourne shell,

• A 5 digit random number will be available if we’ll execute in the Korn shell.

• We can also run a ps -l and look for the shell having the highest PID.

Define Stacks. Provide an example where they are useful.

• A Stack is of course a linear structure.

• In stack insertions and deletions are being made at the one end i.e the top - which is termed as last in, first out (LIFO).

• Application of Stacks can be used when we need to debug some syntax errors like missing parentheses.


Freshers C++ questions 07-18-2012 06:06 AM

C++

Answer of question 14 is wrong.
Code will work fine. There should be no problem in deletion of NULL pointer.
If pointer is uninitialized then only it will crash.


Madhumita 03-20-2012 08:19 AM

C++ interview questions and answers

What is the type of “this” pointer?

It is a constant pointer.

When does a “this” pointer get created?

When a non-static member function of a class is called.

Define VPTR.

The address of the VTABLE stored in the object is known as VPTR.

Define upcasting.

Storing the address of the derived class object in the base class pointer.

Explain how to initialize a const data member.

The const data member can be initialized with constructor initializer list.


Jitendra 12-5-2011 05:40 AM

C++ interview questions and answers

Explain the difference between C++ and Java.

C++ has pointers whereas Java does not.
Java is platform independent whereas C++ is not.
Java has garbage collection whereas C++ does not.

Define virtual constructor.

There is no such concept in C++.


Define anonymous class.

A class that is defined without any name is called anonymous class.

Explain how to initialize a const member data.

Use constructor initializer list.

Difference between delete and free.

Delete invokes destructor, free will not


Kavita 12-5-2011 05:40 AM

C++ interview questions and answers

Define destructor.

Destructor destroys any extra resources allocated by the object.

Define default constructor.

Constructor with no arguments or all the arguments has default values.


Define copy constructor.

It initializes it's object member variables with another object of the same class.


Define Default assignment operator.

It handles assigning one object to another of the same class.


What are storage qualifiers in C++ ?

const, volatile, mutable

What is a dangling pointer?

A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.


Rakesh 12-5-2011 05:40 AM

C++ interview questions and answers

Brief about mutable member.

mutable member can be modified by the class.

Is C an object-oriented language?

C is not an object-oriented language.


What are the traits of an object-oriented language?

Encapsulation, inheritance, and polymorphism

Define pure virtual function.

A pure virtual function is one with an initializer of = 0 in its declaration

What is semaphore?

Semaphore performs atomic operations, once a semaphore is called it can not be interrupted.


Define constructor.

Constructor creates an object and initializes it.
It also creates vtable for virtual functions.


Neelam 12-5-2011 05:39 AM

C++ interview questions and answers

Define an object.

Objects have state and behavior and it is a bundle of variables and related methods.

Name the keyword used when defining a function in base class to allow this function to be a polimorphic function.

virtual

What do you understand by binding of data and functions?

Encapsulation.

Define a class.

Class is a user-defined data type in C++.
After creation the user need not know the specifics of the working of a class.


Can you show the way to link a C++ program to C functions?

You can do so by using the extern "C" linkage specification around the C function declarations.

Define a conversion constructor.

A constructor that accepts one argument of a different type.


Rajesh 12-5-2011 05:39 AM

C++ interview questions and answers

Explain the advantages of inheritance.

Inheritance allows code reusability that saves time in program development.
It encourages the reuse of proven and debugged high-quality software.


Define inline function.

Inline functions is to insert the code of a called function at the point where the function is called.
Improve the application's performance in exchange for increased compile time.


Does c++ support multilevel and multiple inheritance?
Yes.

Define encapsulation
Encapsulation is keeping an object’s variables within its methods.

What is abstraction?

Abstraction is of the process of hiding unwanted details from the user.



Raj 12-5-2011 05:39 AM

C++ Interview questions Answer

Nice link, quite helpful, thanks for posting such an exhaustive interview series

Nitin P 11-8-2011 03:47 AM

 

C++ interview questions - posted on September 30, 2009 at 15:50 AM by Vidya Sagar

Explain how to call C code from C++ code. Explain with an example.

To call a C program in C++ , the basic requirement is both the compilers and runtime libraries must be compatible. They must define the primitive data types such as int, float, char etc.

Accessing C Code From Within C++ Source:

A linkage specification is provided by C++, which is used to declare a function that follows the program linkage conventions for a supported language. C++ compilers support C linkage for compatible C compilers.

To access a function with C linkage, the function need to be declared to have C linkge.

The following code snippet depicts the linkage declaration:

extern "C" {
          void f(); // C linkage
          extern "C++" {
                  void g(); // C++ linkage
                  extern "C" void h(); // C linkage
                  void g2(); // C++ linkage
          }
          extern "C++" void k();// C++ linkage
                     void m(); // C linkage
}

The following code snippet depicts the inclusion of a c header file.

extern "C"
{
       #include "header.h"
}

How can an object of a C++ class be passed to or from a C function?

Define a header file for both C and C++ compilers. The following code snippet does this.

Fred.h:

/* This header can be read by both C and C++ compilers */

#ifndef FRED_H
#define FRED_H

#ifdef __cplusplus
    class Fred {
    public:
         Fred();
         void wilma(int);
    private:
         int a_;
     };
#else
     typedef
          struct Fred
          Fred;
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if defined(__STDC__) || defined(__cplusplus)
      extern void c_function(Fred*); /* ANSI C prototypes */
      extern Fred* cplusplus_callback_function(Fred*);
#else
      extern void c_function(); /* K&R style */
      extern Fred* cplusplus_callback_function();
#endif

#ifdef __cplusplus
}
#endif

#endif /*FRED_H*/

Write C++ code as follows:

Fred.cpp:
// This is C++ code

#include "Fred.h"

Fred::Fred() : a_(0) { }
void Fred::wilma(int a) { }
Fred* cplusplus_callback_function(Fred* fred)
{
     fred->wilma(123);
     return fred;
}

main.cpp:
// This is C++ code

#include "Fred.h"

int main()
{
     Fred fred;
     c_function(&fred);
     ...
}

Write the following C program as follows:

c-function.c:
/* This is C code */

#include "Fred.h"
void c_function(Fred* fred)
{
      cplusplus_callback_function(fred);
}

Why does COM require GUIDs?

Globally Unique Identifier, a unique 128-bit number used in a windows registry to identify COM DLL. Lot of COM object information is known by identifying the registry and the correct GUID. Windows also identifies the user accounts by a user name and assigns it a GUID. GUIDS are also used by database administrators as primary key values in the databases.

What happens when an object is destroyed that doesn't have an explicit destructor?

Destructor synthesizing is done by a compiler of an object’s class.
For instance, if an object of a class Sample is destroyed without invoking the destructor explicitly, the compiler synthesizes the destructor which destroys the object of the class Sample. This process is done by invoking
Sample::~Sample().

Explain the problem with dynamic type checking.

Authoring code without errors is very difficult using dynamic type checking.
It is hard to read or modify or maintain the code for dynamic type checking.

What is wrong with an object being assigned to itself?

A segfault occurs at runtime.

Explain how static member functions are called.

Static member functions are called by referencing its containing class without using an object. The following code snippet illustrates the use of static member functions.

Test::set_number(22);
Test::print_number();

where set_number() and print_number() are static functions and they are defined as follows in the class Test:

static void set_number(int arg) {
                   si = arg; // si is an int var
         }
         static void print_number() {
             cout << "Value of si = " << si << endl;
         }

What happens when a pointer is deleted twice?

It is not certain and depends. If the value of the pointer is set to 0 soon after first delete, then not operation will perform. If not, there are chances for program crash.

Test your C++ knowledge with our multiple choice questions!

Send request to get more ASP.NET, C++ questions, sample CV and personal interview tips in PDF format

Next>>
 
Interview questions
 
Home | Want a Job? Submit Key Skills | Employer login | My key skills | About us | Sitemap | Contact us