You are on page 1of 21

C++

Q-What is constructor?
Ans: A constructor is a member function of a class which initializes objects of a class.
Example:

#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
/***Constructor****/
Point(int x1, int y1) { x = x1; y = y1; }
int getX()
{ return x; }
int getY()
{ return y; }
};
int main()
{
Point p1(10, 15); // constructor is called here
// Let us access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Q - How constructors are different from a normal member function?
Ans- constructor is different from normal functions in following ways:
(i) Constructor has same name as the class itself
(ii) Constructors dont have return type
(iii) A constructor is automatically called when an object is created.
(iv) If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no
parameters and has an empty body)
Q Why constructor is declared as private?
Ans: Constructor are declared private in case of singleton design pattern.(class which can have only one
object)

Q -Access Specifiers
Ans:

Q-types of inheritance?
Ans :

Q-Initialization list?
A. Initializer List is used to initialize data members of a class.
Example :
#include<iostream>
using namespace std;
class Point {

private:
int x;
int y;
public:
Point(int i = 0, int j = 0):x(i), y(j) {}

Q When do we use initializer list?


Ans : 1. For initialization of non-static const data members:
const data members must be initialized using Initializer List. In the following example, t is a const data
member of Test class and is initialized using Initializer List.
#include<iostream>
using namespace std;
class Test {
const int t;
public:
Test(int t):t(t) {} //Initializer list must be used
int getT() { return t; }
};
2. For initialization of reference members:
Reference members must be initialized using Initializer List. In the following example, t is a reference
member of Test class and is initialized using Initializer List.
// Initialization of reference data members
#include<iostream>
using namespace std;
class Test {
int &t;
public:
Test(int &t):t(t) {} //Initializer list must be used
int getT() { return t; }
};
3) For initialization of member objects which do not have default constructor:
In the following example, an object a of class A is data member of class B, and A doesnt have
default constructor. Initializer List must be used to initialize a.
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int );
};
A::A(int arg) {
i = arg;
cout << "A's Constructor called: Value of i: " << i << endl;
}

// Class B contains object of A


class B {
A a;
public:
B(int );
};
B::B(int x):a(x) { //Initializer list must be used
cout << "B's Constructor called";
}
int main() {
B obj(10);
return 0;
}
/* OUTPUT:
A's Constructor called: Value of i: 10
B's Constructor called
*/
4) For initialization of base class members : Like point 3, parameterized constructor of base class can
only be called using Initializer List.
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int );
};
A::A(int arg) {
i = arg;
cout << "A's Constructor called: Value of i: " << i << endl;
}
// Class B is derived from A
class B: A {
public:
B(int );
};
B::B(int x):A(x) { //Initializer list must be used
cout << "B's Constructor called";
}
int main() {
B obj(10);
return 0;
}

5).For

Performance

reasons:

It is better to initialize all class variables in Initializer List instead of assigning values inside body. Consider
the following example:
// Without Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a) {

// Assume that Type is an already


// declared class and it has appropriate
// constructors and operators

variable = a;
}
};
Here
compiler
follows
following
steps
to
create
an
object
of
type
1.
Types
constructor
is
called
first
for
2. The assignment operator of Type is called inside body of MyClass() constructor to assign

MyClass
a.

variable = a;

3. And then finally destructor of Type is called for a since it goes out of scope.
Now consider the same code with MyClass() constructor with Initializer List
// With Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a):variable(a) {

// Assume that Type is an already

// declared class and it has appropriate


// constructors and operators
}
};
With
the
Initializer
List,
following
steps
are
followed
by
compiler:
1. Copy constructor of Type class is called to initialize : variable(a). The arguments in initializer list are

used
to
copy
construct
2. Destructor of Type is called for a since it goes out of scope.

variable

directly.

As we can see from this example if we use assignment inside constructor body there are three function
calls: constructor + destructor + one addition assignment operator call. And if we use Initializer List there
are only two function calls: copy constructor + destructor call.
Q- Destructor?
Ans : A destructor is a special member function of a class that is executed

whenever an object of it's class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class.
Q-When
do
we
need
to
write
a
user-defined
destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us. The default
destructor works fine unless we have dynamically allocated memory or pointer in class. When a class
contains a pointer to memory allocated in class, we should write a destructor to release memory before
the class instance is destroyed. This must be done to avoid memory leak.
Q- Can a destructor be virtual?
Ans :Yes .
Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in
undefined behavior.
For example :
// A program without virtual destructor causing undefined behavior
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;

Output :
Constructing
Constructing
Destructing base

base
derived

Making base class destructor virtual guarantees that the object of derived class is destructed properly,
i.e., both base class and derived class destructors are called.
Example :
/ A program with virtual destructor
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
virtual ~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Q- Copy Constructor
Ans :

The copy constructor is a constructor which creates an object by initializing it with an


object of the same class, which has been created previously.
classname (const classname &obj) {
// body of constructor
}

Q -When is copy constructor called?


Ans: In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
MyClass foo ()

MyClass temp;
..
..
return temp; //copy constructor called

2. When an object of the class is passed (to a function) by value as an argument.


void foo(MyClass a);
foo(a); //copy constructor invoked

3. When an object is constructed based on another object of the same class.


MyClass A,B;
A = new MyClass();
B=A; //copy constructor called

4. When compiler generates a temporary object.


Q Friend Function ?
Ans : A friend function is permitted full access to private and protected members of a

class.
Example :

class Box
{

double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

Q- Inline Function?
Ans If a function is inline, the compiler places a copy of the code of that function

at each point where the function is called at compile time.


Example :
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl;


cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}

Q- this pointer ?
Ans : Every object has a special pointer this which points to the object itself.

Every object in C++ has access to its own address through an important
pointer called this pointer. The this pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be used
to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
Q - static member ?
Ans : When we declare a member of a class as static it means no matter how

many objects of the class are created, there is only one copy of the static
member.
A static member is shared by all objects of the class. All static data is initialized
to zero when the first object is created, if no other initialization is present. We
can't put it in the class definition but it can be initialized outside the
class as done in the following example by redeclaring the static variable, using
the scope resolution operator :: to identify which class it belongs to.
Example:
#include <iostream>

using namespace std;


class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;

height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length;
double breadth;
double height;

// Length of a box
// Breadth of a box
// Height of a box

};

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void)
{
Box Box1(3.3, 1.2, 1.5);

// Declare box1

Box Box2(8.5, 6.0, 2.0);

// Declare box2

// Print total number of objects.


cout << "Total objects: " << Box::objectCount << endl;

return 0;
}

Q Static member function?


Ans : By declaring a function member as static, you make it independent of any

particular object of the class. A static member function can be called even
if no objects of the class exist and the static functions are accessed using
only the class name and the scope resolution operator ::.
A static member function can only access static data member, other static
member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to
determine whether some objects of the class have been created or not.

Q Inheritance ?
Ans: NOTE :

A derived class inherits all base class methods with the following
exceptions:

Constructors, destructors and copy constructors of the base class.

Overloaded operators of the base class.

The friend functions of the base class.

Q- Virtual Function:

A virtual function is a function in a base class that is declared using the


keyword virtual. Defining in a base class a virtual function, with another
version in a derived class, signals to the compiler that we don't want static
linkage for this function.

Q-Stack Unwinding in C++


Ans -The process of removing function entries from function call stack at run time is
called Stack Unwinding.
Q- The Standard Template Library

Ans :The Standard Template Library is a collection of classes that provide templated
containers, algorithms, and iterators.
Component

Description

Containers

Containers are used to manage collections of objects of a


certain kind. There are several different types of
containers like deque, list, vector, map etc.

Algorithms

Algorithms act on containers. They provide the means by


which you will perform initialization, sorting, searching,
and transforming of the contents of containers.

Iterators

Iterators are used to step through the elements of


collections of objects. These collections may be
containers or subsets of containers.

Q Types of STL containers?


Ans : Sequence containers, Associative containers, and Container adapters.
Sequence Containers
Sequence containerss are container classes that maintain the ordering of elements
in the container. A defining characteristic of sequence containers is that you can choose
where to insert your element by position. The most common example of a sequence
container is the array: if you insert four elements into an array, the elements will be in the
exact order you inserted them.
The STL contains 3 sequence containers: vector, deque, and list.
Vector Example:
#include <vector>
#include <iostream>
int main()
{
using namespace std;
vector<int> vect;
for (int nCount=0; nCount < 6; nCount++)
vect.push_back(10 - nCount); // insert at end of array
for (int nIndex=0; nIndex < vect.size(); nIndex++)
cout << vect[nIndex] << " ";
cout << endl;
}
List Example

list<int> L;
L.push_back(0);
// Insert a new element at the end
L.push_front(0);
// Insert a new element at the
beginning
L.insert(++L.begin(),2);
// Insert "2" before position
of first argument
// (Place before second argument)
L.push_back(5);

L.push_back(6);
list<int>::iterator i;
for(i=L.begin(); i != L.end(); ++i) cout << *i << " ";
cout << endl;
Associative Containers
Associative contains are containers that automatically sort their inputs when those inputs
are inserted into the container.

A set is a container that stores unique elements, with duplicate elements disallowed.
The elements are sorted according to their values.

A multiset is a set where duplicate elements are allowed.

A map (also called an associative array) is a set where each element is a pair, called
a key/value pair. The key is used for sorting and indexing the data, and must be
unique. The value is the actual data.

Example:

std::map<char,int> first;
first['a']=10;
first['b']=30;
first['c']=50;
first['d']=70;

A multimap (also called a dictionary) is a map that allows duplicate keys. Real-life
dictionaries are multimaps: the key is the word, and the value is the meaning of the
word. All the keys are sorted in ascending order, and you can look up the value by
key. Some words can have multiple meanings, which is why the dictionary is a
multimap rather than a map.
Multimap Example
std::multimap<char,int> mymm;
mymm.insert (std::make_pair('x',10));
mymm.insert (std::make_pair('y',20));
mymm.insert (std::make_pair('z',30));
mymm.insert (std::make_pair('z',40));
std::multimap<char,int>::iterator it = mymm.find('x');
mymm.erase (it);
mymm.erase (mymm.find('z'));

Container Adapters

Container adapters are special predefined containers that are adapted to specific uses. The
interesting part about container adapters is that you can choose which sequence container
you want them to use.

A stack is a container where elements operate in a LIFO (Last In, First Out) context,
where elements are inserted (pushed) and removed (popped) from the end of the
container. Stacks default to using deque as their default sequence container (which
seems odd, since vector seems like a more natural fit), but can use vector or list as
well.

A queue is a container where elements operate in a FIFO (First In, First Out)
context, where elements are inserted (pushed) to the back of the container and
removed (popped) from the front. Queues default to using deque, but can also use
list.

A priority queue is a type of queue where the elements are kept sorted (via
operator<). When elements are pushed, the element is sorted in the queue.
Removing an element from the front returns the highest priority item in the priority
queue.

Q- Vtables
Ans : When working with virtual functions in C++, its the vtable thats being used behind the scenes
to help achieve polymorphism.
Whenever a class itself contains virtual functions or overrides virtual functions from a parent class the
compiler builds a vtable for that class. This means that not all classes have a vtable created for
them by the compiler. The vtable contains function pointers that point to the virtual functions in that
class. There can only be one vtable per class, and all objects of the same class will share the same
vtable.
Associated with every vtable is whats called a vpointer. The vpointer points to the vtable, and is used
to access the functions inside the vtable. The vtable would be useless without avpointer.

Q-Composition
Ans:
This process of building complex objects from simpler ones is calledcomposition (also
known as object composition).
More specifically, composition is used for objects that have a has-arelationship to each
other. A car has-a metal frame, has-an engine, and has-atransmission. A personal
computer has-a CPU, a motherboard, and other components. You have-a head, a body,
some limbs.
Ex:

#include "CPU.h"
#include "Motherboard.h"
#include "RAM.h"
class PersonalComputer
{
private:
CPU m_cCPU;

Motherboard m_cMotherboard;
RAM m_cRAM;
};
PersonalComputer::PersonalComputer(int nCPUSpeed, char *strMotherboardModel,
int nRAMSize)
: m_cCPU(nCPUSpeed), m_cMotherboard(strMotherboardModel),
m_cRAM(nRAMSize)
{
}
Note : When complex object is destroyed then subobjects also get destroyed.
Q- Aggregation?
Ans
An aggregation is a specific type of composition where no ownership between the complex
object and the subobjects is implied. When an aggregate is destroyed, the subobjects are
not destroyed.
For example, consider the math department of a school, which is made up of one or more
teachers. Because the department does not own the teachers (they merely work there), the
department should be an aggregate. When the department is destroyed, the teachers
should still exist independently (they can go get jobs in other departments).
#include <string>
using namespace std;
class Teacher
{
private:
string m_strName;
public:
Teacher(string strName)
: m_strName(strName)
{
}
string GetName() { return m_strName; }
};
class Department
{
private:
Teacher *m_pcTeacher; // This dept holds only one teacher
public:
Department(Teacher *pcTeacher=NULL)
: m_pcTeacher(pcTeacher)
{
}
};
int main()
{
// Create a teacher outside the scope of the Department
Teacher *pTeacher = new Teacher("Bob"); // create a teacher
{
// Create a department and use the constructor parameter to pass
// the teacher to it.
Department cDept(pTeacher);

} // cDept goes out of scope here and is destroyed


// pTeacher still exists here because cDept did not destroy it
delete pTeacher;
}

Q function pointer?
Ans : Exmple ://fcnPtr is a pointer to a function that takes no arguments and returns

an integer
int (*fcnPtr)();
Example:
int foo()
{
return 5;
}
int goo()
{
return 6;
}
int main()
{
int (*fcnPtr)() = foo; // fcnPtr points to function foo
fcnPtr = goo; // fcnPtr now points to function goo
return 0;
}

Q- Assignment Operator?
Ans : the assignment operator, '=', is the operator used for assignment.

The copy assignment operator, often just called the "assignment operator", is a special case of
assignment operator where the source (right-hand side) and destination (left-hand side) are of the
same class type.
The copy assignment operator differs from the copy constructor in that it must clean up the data
members of the assignment's target (and correctly handle self-assignment) whereas the copy
constructor assigns values to uninitialized data members
Overloaded Assignment operator;
class My_Array
{
int * array;
int count;
public:
My_Array & operator= (const My_Array & other)
{
if (this != &other) // protect against invalid self-assignment
{
// 1: allocate new memory and copy the elements

int * new_array = new int[other.count];


std::copy(other.array, other.array + other.count, new_array);
// 2: deallocate old memory
delete [] array;
// 3: assign the new memory to the object
array = new_array;
count = other.count;
}
// by convention, always return *this
return *this;
}
// ...
};
Q- Dynamic Cast?
Ans : dynamic_cast can only be used with pointers and references to classes (or with void*). Its
purpose is to ensure that the result of the type conversion points to a valid complete object of the
destination pointer type.
This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the
same way as allowed as an implicit conversion.
But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived)

Base * pba = new Derived;


Base * pbb = new Base;
Derived * pd;

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";
pd = dynamic_cast<Derived*>(pbb);//(error thrown here).
if (pd==0) cout << "Null pointer on second type-cast.\n";
Q const rules?
Ans : All const variables must be initialized at time of creation.
const class objects can only call const member functions.( A const member
function is a member function that guarantees it will not change any class variables
or call any non-const member functions.)
When a function is declared as const, it can be called on any type of object. Non-const functions
can only be called by non-const objects.
Q Smart Pointers?

Ans : A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage

the lifetime of the object being pointed to.


Ex:
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class SmartPtr
{
T *ptr; // Actual pointer
public:
// Constructor
explicit SmartPtr(T *p = NULL) { ptr = p; }
// Destructor
~SmartPtr() { delete(ptr); }
// Overloading dereferncing operator
T & operator * () { return *ptr; }

};

// Overloding arrow operator so that members of T can be accessed


// like a pointer (useful if T represents a class or struct or
// union type)
T * operator -> () { return ptr; }

int main()
{
SmartPtr<int> ptr(new int());
*ptr = 20;
cout << *ptr;
return 0;
}
Using smart pointers, we can make pointers to work in way that we dont need to explicitly call
delete.

Q- Templates?
Ans : Templates are the foundation of generic programming, which involves
writing code in a way that is independent of any particular type.
Function Template:
The general form of a template function definition is shown here:
template <class type>

ret-type func-name(parameter list)


{
// body of function
}

Example:
using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{

int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
}

Class Template:

The general form of a generic class declaration is shown here:


template <class type> class class-name {
.
.
.
}

Example:::::
template <class T>
class Stack {
private:
vector<T> elems;

// elements

public:
void push(T const&); // push element
void pop();
T top() const;

// pop element
// return top element

bool empty() const{

// return true if empty.

return elems.empty();
}
};

Q-

C++ References vs Pointers:

References are often confused with pointers but three major differences
between references and pointers are:

You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.

Once a reference is initialized to an object, it cannot be changed to refer to


another object. Pointers can be pointed to another object at any time.

A reference must be initialized when it is created. Pointers can be initialized at


any time.

You might also like