What is C++?
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow objectoriented
programming.
C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.
C++ used for:
C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or consoleonly DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.
What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout <<>
}
Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?
There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.
What is constructor or ctor?
Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is
different from other methods in a class.
What about Virtual Destructor?
Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object caller is calling to, proper destructor will be called.
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An
overloaded assignment operator assigns the contents of an existing object to another existing
object of the same class.
Can a constructor throws an exception? How to handle the error when the constructor fails?
The constructor never throws an error.
What is default constructor?
Constructor with no arguments or all the arguments has default values.
What is copy constructor?
Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you. for example:
(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor
When are copy constructors called?
Copy constructors are called in following cases:
(a) when a function returns an object of that class by value
(b) when the object of that class is passed by value as an argument to a function
(c) when you construct an object based on another object of the same class
(d) When compiler generates a temporary object Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
No. It is specified in the definition of the copy constructor itself. It should generate an error if
a programmer specifies a copy constructor with a first argument that is an object and not a
reference.
What is conversion constructor?
constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.
for example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object
What is Virtual Destructor?
Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors
can also be declared as pure virtual functions for abstract classes.
if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.
Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
No. It is specified in the definition of the copy constructor itself. It should generate an error if
a programmer specifies a copy constructor with a first argument that is an object and not a
reference.
What's the order that local objects are destructed?
In reverse order of construction: First constructed, last destructed. In the following example, b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
...
}
What's the order that objects in an array are destructed?
In reverse order of construction: First constructed, last destructed.
In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}
Can I overload the destructor for my class?
No. You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It never takes any parameters, and it never returns anything.
You can't pass parameters to the destructor anyway, since you never explicitly call a destructor
(well, almost never).
Is there any difference between List x; and List x();?
A big difference!
Suppose that List is the name of some class. Then function f() declares a local List object called
x:
void f()
{
List x; // Local object named x (of class List)
...
}
But function g() declares a function called x() that returns a List:
void g()
{
List x(); // Function named x (that returns a List)
...
}
What is virtual function?
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class
object, then you must define this function in base class as 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()
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 a "pure virtual" member function?
The abstract class whose pure virtual method has to be implemented by all the classes which
derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure
virtual in base class.
How virtual functions are implemented C++?
Virtual functions are implemented using a table of function pointers, called the vtable.
There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed _rst which creates the vtable.
If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions
What is pure virtual function? or what is abstract class?
When you de_ne only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won't able to instantiate an object using this base class. You can make a pure virtual function or
abstract class this way.
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error
What is Pure Virtual Function? Why and when it is used?
The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
How Virtual functions call up is maintained?
Through Look up tables added by the compile to every class image. This also leads to performance penalty.
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a caller
or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete.
What is inheritance?
Inheritance allows one class to reuse the state and behavior of another class. The derived class
inherits the properties and method implementations of the base class and extends it by overriding methods and adding additional properties and methods.
When should you use multiple inheritance?
There are three acceptable answers:- "Never,""Rarely," and "When the problem domain cannot be accurately modeled any other way." Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles.
Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain.
The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other
types, when the format and behavior of those other types are unimportant to their containment or
management, and particularly when those other types are unknown (thus, the generality) to the
designer of the container or manager class.
What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?
Multiple Inheritance is the process whereby a child can be derived from more than one parent class.
The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships.
The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name.
What a derived class inherits or doesn't inherit?
Inherits: Every data member defined in the parent class (although such members may not always be accessible in the derived class!)
Every ordinary member function of the parent class (although such members may not always be
accessible in the derived class!) The same initial data layout as the base class.
Doesn't Inherit : The base class's constructors and destructor.
The base class's assignment operator. The base class's friends
What is Polymorphism?
Polymorphism allows a client to treat di_erent objects in the same way even if they were created from di_erent classes and exhibit di_erent behaviors. You can use implementation inheritance to achieve polymorphism in languages such as C++ and Java.
Base class object's pointer can invoke methods in derived class objects. You can also achieve polymorphism in C++ by function overloading and operator overloading.
What is problem with Runtime type identification?
The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
What is a class?
A class is an expanded concept of a data structure: instead of holding only data, it can hold
both data and functions.
What are the differences between a C++ struct and C++ class?
The default member and base class access specifies are different. This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifes, member functions, overloaded operators, and so on.
Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specified and private base-class inheritance.
How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a caller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
What is encapsulation?
Containing and hiding Information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object's operation from the rest of the
application.
For example, a client component asking for net revenue from a business object need not know the data's origin.
What is "this" pointer?
The this pointer is a pointer accessible only within the member functions of a class, struct, or
union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.
When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function.
For example, the following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object's address is available from within the member function as the this pointer. It is legal,
though unnecessary, to use the this pointer when referring to members of the class.
What is assignment operator?
Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)
What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don't define one?
(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator
What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a wellknown interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory.
When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
What is Overriding?
To override a method, a subclass of the class that originally declared the method must declare
a method with the same name, return type (or a subclass of that return type), and same parameter list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply
overriding functionality we need parent and child classes. In the child class you define the same
method signature as one defined in the parent class.
What is a local class? Why can it be useful?
Local class is a class defined within the scope of a function _ any function, whether a member function or a free function.
For example:
int f()
{
class LocalClass
{
// ...
};
// ...
};
Like nested classes, local classes can be a useful tool for managing code dependencies.
What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
What is difference between new and malloc?
Both malloc and new functions are used for dynamic memory allocations and the basic difference is: malloc requires a special "typecasting" when it allocates memory for eg.
if the pointer used is the char pointer then after the processor allocates memory then this allocated memory needs to be typecasted to char pointer i.e (char*).but new does not requires any typecasting. Also, free is the keyword used to free the memory while using malloc and delete the keyword to free memory while using new, otherwise this will lead the memory leak.
What is the difference between delete and delete[]?
Whenever you allocate memory with new[], you have to free the memory using delete[].
When you allocate memory with 'new', then use 'delete' without the brackets. You use new[] to
allocate an array of values (always starting at the index 0).
What is the difference between "new" and "operator new" ?
"operator new" works like malloc.
Why should I use new instead of trustworthy old malloc()?
Constructors/destructors, type safety, overridability. Constructors/destructors: unlike malloc(sizeof(Fred)), new Fred() calls Fred's constructor.
Similarly, delete p calls *p's destructor. Type safety: malloc() returns a void* which isn't type safe. new Fred() returns a pointer of the right type (a Fred*).
Overridability: new is an operator that can be overridden by a class, while malloc() is not overridable on a per-class basis.
Can I use realloc() on pointers allocated via new?
No! When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves. They use their own copy constructor or assignment operator.
Besides all that, the heap that new uses may not be the same as the heap that malloc() and
realloc() use!
Do I need to check for NULL before delete p?
No! The C++ language guarantees that delete p will do nothing if p is equal to NULL. Since you
might get the test backwards, and since most testing methodologies force you to explicitly test
every branch point, you should not put in the redundant if test.
Wrong:
if (p != NULL)
delete p;
Right:
delete p;
What happens when a function throws an exception that was not specified by an exception specification for this function?
Unexpected() is called, which, by default, will eventually trigger abort().
Depends. Might be "zero." Objects that are thrown must have a publicly accessible copy-constructor. The compiler is allowed to generate code that copies the thrown object any number of times, including zero.
However even if the compiler never actually copies the thrown object, it must make sure the
exception class's copy constructor exists and is accessible.
What should I throw?
C++, unlike just about every other language with exceptions, is very accomodating when it comes to what you can throw. In fact, you can throw anything you like. That begs the question
then, what should you throw?
Generally, it's best to throw objects, not built-ins. If possible, you should throw instances of
classes that derive (ultimately) from the std::exception class. By making your exception class
inherit (ultimately) from the standard exception base-class, you are making life easier for your
users (they have the option of catching most things via std::exception), plus you are probably
providing them with more information (such as the fact that your particular exception might be a
refinement of std::runtime_error or whatever).
The most common practice is to throw a temporary:
#include
class MyException : public std::runtime_error {
public:
MyException() : std::runtime_error("MyException") { }
};
void f()
{
...
throw MyException();
}
Here, a temporary of type MyException is created and thrown. Class MyException inherits from
class std::runtime_error which (ultimately) inherits from class std::exception.
What should I catch?
In keeping with the C++ tradition of "there's more than one way to do that" (translation: "give
programmers options and tradeoffs so they can decide what's best for them in their situation"),
C++ allows you a variety of options for catching.
You can catch by value.
You can catch by reference.
You can catch by pointer.
In fact, you have all the flexibility that you have in declaring function parameters, and the rules
for whether a particular exception matches (i.e., will be caught by) a particular catch clause are
almost exactly the same as the rules for parameter compatibility when calling a function.
Given all this flexibility, how do you decide what to catch? Simple: unless there's a good reason
not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the
copy can have different behavior from what was thrown. Only under very special circumstances
should you catch by pointer.
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.
What is Memory Leak?
Memory which has no pointer pointing to it and there is no way to delete or reuse this memory(object), it causes Memory leak.
{
Base *b = new base();
}
Out of this scope b no longer exists, but the memory it was pointing to was not deleted. Pointer b
itself was destroyed when it went out of scope.
What is auto pointer?
The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. Auto Pointer only takes care of Memory leak and does nothing about dangling pointers
issue. You can find it in the header . Here is part of auto_ptr's implementation, to illustrate what
it does:
template class auto_ptr
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};
As you can see, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful
operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the
destructor takes care of deleting the pointer.
For the user of auto_ptr, this means that instead of writing:
void foo()
{
MyClass* p(new MyClass);
p->DoSomething();
delete p;
}
You can write:
void foo()
{
auto_ptr p(new MyClass);
p->DoSomething();
}
And trust p to cleanup after itself.
What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap objects not being
deleted even if the exception is thrown.
What is the difference between a pointer and a reference?
A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.
What is the difference between const char *myPointer and char *const myPointer?
Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.
How do I convert an integer to a string?
The simplest way is to use a stringstream:
#include
#include
#include
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
int main()
{
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();
cout << ss << " " << p << "\n";
}
Naturally, this technique works for converting any type that you can output using << to a string.
Is there anything you can do in C++ that you cannot do in C?
No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C
What are the differences between a struct in C and in C++?
In C++ a struct is similar to a class except for the default access specifier( refere to other question in the document). In C we have to include the struct keyword when declaring struct. In c++ we don’t have to.
What does extern "C" int func(int *, Foo) accomplish?
It will turn o_ "name mangling" for func so that one can link to code compiled by a C
compiler.
What are the access privileges in C++? What is the default access level?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.
Name the operators that cannot be overloaded?
sizeof, ., .*, .->, ::, ?:
What is overloading?
With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope.
- Any two functions in a set of overloaded functions must have different argument lists.
- Overloading functions with argument lists of the same types, based on return type alone, is an
error.
How are prefix and postfix versions of operator++() differentiated?
The postfix version of operator++() has a dummy parameter of type int. The prefix version
does not have dummy parameter.
Can you overload a function based only on whether a parameter is a value or a reference?
No. Passing by value and by reference looks identical to the caller.
What are the benefits of operator overloading?
By overloading standard operators on a class, you can exploit the intuition of the users of that
class. This lets users program in the language of the problem domain rather than in the language
of the machine. The ultimate goal is to reduce both the learning curve and the defect rate.
What are some examples of operator overloading?
Here are a few of the many examples of operator overloading:
myString + yourString might concatenate two std::string objects
myDate++ might increment a Date object
a * b might multiply two Number objects
a[i] might access an element of an Array object
x = *p might dereference a "smart pointer" that "points" to a disk record_ it could seek to the location on disk where p "points" and return the appropriate record into x
What operators can/cannot be overloaded?
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof, which is
technically an operator). C++ adds a few of its own operators, most of which can be overloaded
except :: and .*.
Here's an example of the subscript operator (it returns a reference). First without operator
overloading:
class Array {
public:
int& elem(unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};
int main()
{
Array a;
a.elem(10) = 42;
a.elem(12) += a.elem(13);
...
}
Now the same logic is presented with operator overloading:
class Array {
public:
int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};
int main()
{
Array a;
a[10] = 42;
a[12] += a[13];
...
}
Can I overload operator== so it lets me compare two char[] using a string comparison?
No: at least one operand of any overloaded operator must be of some user-defined type (most
of the time that means a class).
But even if C++ allowed you to do this, which it doesn't, you wouldn't want to do it anyway
since you really should be using a std::string-like class rather than an array of char in the first
place since arrays are evil.
What do you mean by inline function?
The idea behind inline functions is to insert the code of a called function at the point
where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always)
an increase in the size of the generated binary executables.
What is a template?
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any
of the two following ones:
Template function_declaration; template function_declaration; The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.
What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
- The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
- An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.
What is a class?
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.
What is friend function?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.
What is a scope resolution operator?
A scope resolution operator (::), can be used to define the member functions of a class outside the class.
Why are arrays usually processed with for loop?
The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a. length -1. That is exactly what a loop does.
What’s the best way to declare and define global variables?
The best way to declare global variables is to declare them after including all the files so that it can be used in all the functions.
What does extern mean in a function declaration?
It tells the compiler that a variable or a function exists, even if 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.
Explain the scope resolution operator.
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifiers are different.
How many ways are there to initialize an int with a constant?
Two. There are two formats for initializers in C++ as shown in the example that follows.
The first format uses the traditional C notation. The second format uses constructor
notation.
int foo = 123;
int bar (123);
What is a mutable member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.
What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose
is reserved explicitly for construction.
In C++, what is the difference between method overloading and method overriding?
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
Article of : "C++ Interview Questions And Answers For Fresher"
Give Your Feedback ...