What are containers in C++ and in Object Oriented Programming ? Which objects are available as containers ?
A container is an object that can store other objects as its elements. However all the objects stored in a container should be of the
same data type. E.g. array is a container as it allows you to store multiple objects. However there are a few problems with arrays like
an array can’t allow you to store an element anywhere in the middle of the array, an array cannot grow dynamically to append new
elements at the end of the array. A sequence container is the one which allows storing elements of the same type in a linear fashion.
There are three objects which are sequence containers: 1. Vector: an array like container that allows storing elements of the same
type and provides random access to these elements. Insertions and deletions at the end of the vector are efficient.2. List: provides
efficient insertions and deletions at any position within a list.3. dequeue: double ended queue with constant time insertions and
deletions both at the end and the beginning of the queue.
===================
Explain the Concept of Data Abstraction and Data Encapsulation in Object Oriented Programming (OOPS)
Data encapsulation: the wrapping up of data and functions that act upon that data in a single unit is termed as data encapsulation. It
binds together both the data and code and thus keeps both safe from the outside world. The data and the code to manipulate the data
are combined in such a way that a black box is created which is self contained and modular. This box is termed as a class in object
oriented terminology. Within a class the code or the data can be private or public. If it is private then these cannot be accessed by the
outside world whereas public means that the code and the data is accessible to everyone. Typically the data is private and the
methods are an interface to the private elements of the object. Data abstraction: The term data abstraction is similar to data
encapsulation. All the data and the methods that make sense to the objects of a class that is been designed need to be a part of the
class. All unnecessary details should be left behind. E.g. when designing a class to represent a student we need data elements such
as student no, student name, marks, grade, etc. If we now design a class representing a cricket player we need details like no of
centuries, striking rate, no of matches played, etc. It will not make sense to add the player’s marks, grades which are applicable to a
student class to this player class. The classes designed in object oriented language are also termed as User defined data types
(UDT).
========================
What are classes ? How are they defined ?
A class in an object oriented language is a User defined data type (UDT). A class is made up of member variables (data) and
member functions (interface).
A class is created or declared using the class keyword. It defines a new type to represent a real life entity. This type is composed of
data that is private to the class and accessible through the public member functions of the class.
As an analogy consider a home. A home is like an object that has a state (whether lights are on, number of walls, temperature, etc)
and it provides services (like buttons to switch off the lights, a thermostat that controls the temperature). This blueprint for a home is a
class since it defines the characteristics of a group of such houses.
Syntactically a class structure is similar to a structure except that everything in a class by default is made private whereas everything
is public in a structure by default.
E.g. class student{ public: //public interface private://private implementation}
================================
What are objects ? What is common between all objects of a class ?
Objects are physical or conceptual things that are found in the universe. Objects are thought of having state associated with them.
E.g. state of an account would be the account balance; the state of a clock would be the time.
In object oriented terminology a class is just a plain structure and an object is an instance of a structure. A class is a blueprint that
does not take memory however when a class is instantiated by creating an object of that class then each such object takes up
memory space.
All objects of a class have identical structure however each object will have its own private data. E.g. a class student will have multiple
instances of students where each student instance will have distinct values for their attributes.
Each object will have its own memory with its data however all the objects of a class share the member functions of a class.
E.g. we will define a class called account and create two objects of this class.
class Account
{
private:
double account_balance;
int account_no;
public:
double calculateInterest();
void deposit(double);
double withdraw();
}
==============================
State all the class access modifiers and explain each one of them
C++ has three access modifiers namely public, private and protected.
Public: a public modifier means that the data or the functions of a class are accessible by any program. There are no restrictions in
accessing public members of a class. Ideally all the functions that allow manipulating or accessing the class data are made public.
Private: the private keyword means that the data and member functions that are private cannot be accessed by other programs. They
are accessible only within the class or struct in which they are declared. If one tries to access the private members of a class it results
in a compile time error. Encapsulation is possible due to the private access modifier.
Protected: this access modifier plays a key role in inheritance. This keyword gives a protected access to the member variables and
functions which means that these are accessible from within the class as well as any classes that are derived from the class that
declared this member. However the protected members are not accessible to the any other programs.
=====================
What are Vectors in C++(Object Oriented Programming) and how are they used ?
Vector is a part of the sequential container which holds an ordered collection of elements of one type. A vector holds all these
elements in a contiguous area of memory. Random access of elements is efficient however insertion of elements at any other position
other than the end of the vector is inefficient since each element to the right of the element to be inserted has to be shifted one by one
which leads to inefficiency. Similarly deletion of an element besides the last element is inefficient as well.
The vector is a part of the std namespace and one must include #include header in order to use a vector.
#include
using namespace std;
int main()
{
vector v1;
v1.push_back(1);
v1.push_back(2);
}
The function capacity () returns the total number of elements that the vector can hold and size () returns the number of elements that
are currently stored in the vector
=====================
What are Iterators in C++ and Object Oriented Programming ? Explain where we use them
Iterators allow the traversal of a container object. They provide a generic interface to navigate a container without having to know the
actual type of its elements. Several member functions of containers like begin () and end () return a pointer to iterators. Begin ()
returns a pointer to the beginning of a container and end returns a pointer one position past the last valid element of a container. This
element past the last element marks the end of the container like a \0 is used to mark the end of strings.
The functions begin () and end () come in two flavors: const and non const. The non cons version returns non const iterator that
enables a user to modify the value of its container while const iterators cannot modify its container.
e.g. vector v1;
vector ::iterator p = v.begin ();
====================
What are the Algorithms namespace used for ?
Algorithms are an important part of STL. These are generic algorithms that can be applied to containers. The algorithms are divided
into three categories:
1. Non-modifying sequence operations: these algorithms do not directly modify the object they work on. These are basically the
search algorithms, checking for equality and counting. E.g. find () algorithm is used to locate an element within a sequence.
2. Mutations sequence operations: these algorithms modify the object that they operate on. These are operations such as copy,
fill, replace and transform. E.g. copy () algorithm is used to copy a sequence of objects to a target object.
3. sorting algorithms: these algorithms provide sorting and merging sequences and they operate on sorted sequences. E.g. sort
(), partial_sort (), binary_search (), etc.
==============================
What are Enumerations in C++ and Object Oriented Programming ? Explain with an example ?
An enumeration is a type that can hold a set of constant values that are defined by the user. Once you define an enumeration you can
use it like integer types.E.g. enum {OFF, ON};The enum defines two integer constants called enumerators and these constants are
assigned values by default. The value assigned to OFF = 0 and ON = 1. The above is an unnamed enumeration, however an enum
can be named. E.g. enum STATE {OFF, ON};Each enumeration is a distinct type and the type of the enumeration is the enumerator.
For example OFF is of type STATE. An enumerator can optionally be initialized by a constant expression of integral type. E.g. enum
{WHITE = 3, BLACK = 5}; A value of an integral type can be converter to an enumeration type. This needs to be done explicitly. The
results are undefined unless the value is within the range of the enumeration.E.g. enum COLORS {RED = 1; BLUE = 3, WHITE =
7};COLORS c1 = COLORS (5); All enumerators are converted to integral type for any arithmetic operation.
==============================
What are References in C++ and OOPS ? How are they used ?
A reference means an alias. It is an alternative name to an object. An object can have multiple references. However the most
important use of references is to pass arguments to function and return values for functions as well as for overloaded operators. E.g.
consider a reference for a variable x created as x1.int x = 10;int &x1 = x; To make sure that the reference denotes an object it has to
be initialized. Once initialized the value of a reference cannot be changed. In order to get a pointer to the object denoted by the
reference x1 we can write it as &x1; One of the important uses of reference is to pass an object to a function as a reference so that
the function can change the value of that object. e.g. void swap (int &a, int &b){ int tmp = a; a = b; b = a;}void main (){ int x =
10, y = 12; swap (x, y );} Since x and y are passed by reference to the function swap their values get actually swapped.
============================
Explain the Rules for using Default Arguments with an example in C++.
A default argument is used by functions to free the programmer from specifying values which can be set to default by the function.
E.g. consider a function for printing an integer. A user can be given an option to decide of what base the integer should be printed
however in most cases it will be decimal. E.g. void print (int value, int base = 10); //here the base is set to 10 by defaultThe above
function can be called as: print (10); //here default base will be taken as 10 print (10, 8); a function can specify a default argument
for one or more of its parameters at the initialization time within the parameter list. A function that has a default parameter can be
invoked with or without that parameter. If it gets invoked without the parameter then the default value applies to that parameter.
Arguments to the call are resolved by position and hence the default arguments can be specified as trailing arguments only.e.g. void
display (int a, int b = 0, int c = 9); // correct void display (int a = 0, int b, int c = 9); //wrong void display (int a = 0, int b = 9, int c);
//wrong The default arguments are specified in the function declaration and not in the function definition.
==================================
What do you mean by “Pointers to Function”? What are Function Pointers ?
We can use a function in two ways: one is to invoke a function and the second is to obtain the address of a function. This address that
is obtained is called as pointer to the function and is used to invoke the function.E.g. we have a function named display and we will
invoke this function using a pointer to this function as follow:void display (string s) /* … */void (*ptr)(string); //pointer to a function ptr =
&display; //assign the address of the function ptr (“hello”); // call the function In the above example the compiler will discover that ptr is
a pointer to the function display and calls the function. The dereferencing of a pointer to a function using a * is optional. Similarly it is
not necessary to use & to get the address to the pointer. As pointers to functions have argument types declared just like the functions
themselves, therefore in pointer assignments the complete function type must exactly match. A function name does not constitute its
type. A function type is determined by its return type and its parameter list
======================
What are NameSpaces in C++ ? How do we use namespaces in C++ ?
The purpose of namespaces is to reduce the name clashes that occur with multiple independently developed libraries. It is used to
package names, improve program readability and reduce the name clashes in the global namespace.
e.g. namespace mynamespace{ class Stack { }}The class Stack has to be referred as mynamespace::Stack.
In this way namespace facilitate building large systems by partitioning names into logical groups. Java has a similar concept called
packages. One can access the names within the namespace in the following ways: a. Use the scope resolution operator to prefix
the object declared in the namespace with the name of the namespace. e.g. mynamespace::Stack *s = new
mynamespace::Stack (); b. Using directive E.g. using namespace Stack; Stack *s = new Stack ();
===============
What is the Exception Handling mechanism in C++ ? What is Try and Catch in C++ ?
The ability to gracefully handle an error or an exception is known as exception handling. C++ has built exception handling techniques
which allows the program to handle and exceptions and deal with them.
- try block: the code that is likely to throw an exception should be enclosed in a try lock. This allows the function to recover from
this exception. If a code called from a try block cannot throw an exception then there is no need for the try block.
- Catch block: the exception that is thrown in the try block has to be caught in the catch block. There can be multiple catch blocks
for a try block however there cannot be any code between try and catch block. Once an exception is caught and if the function can
recover from that error then it can either continue normal processing or restart the try block by putting the try block in a loop. If
required the catch block can also propagate the exception to the calling function either by throwing the same exception object or
throwing a different exception object.
e.g.
try { File x (filename); } catch (BadFileName& e) { cout << " second(): " << e.what() << ": Partial recovery\n"; throw; } catch
(AccessViolation& e) { cout << " second(): " << e.what() << ": Full recovery\n"; }
* Login or register to post comments
Re: What is the Exception Handling mechanism in C++ ? What is Tr
Submitted by Anonymous on Wed, 2007-07-11 16:19.
Exception handling in C++ is complex and subtle. It is not as trivial as the above would make you believe.
If you are interested in learning, go and read Meyers, Sutter/GOTW et al.
For a proper treatment, you need to discuss (at a bare minimum):
- What happens to x when an exception is thrown.
- What happens if the destructor of File throws.
- Why you want to catch by reference.
- What can throw (answer: a lot more than you think).
- RAII.
===================================
What is Operator Overloading in C++ ?
The ability to overload operators is one of the most powerful features of C++. The operators are overloaded so that they can perform
special operations on the user defined classes. Say for example you create a class representing complex number. We can overload
the + operator to add two complex numbers. When an operator is overloaded it original meaning is not lost in fact the type of objects
that the operator can operate expands. Operators are overloaded by creating operator functions. It is created using the keyword
operator. These functions can either be member of a class or then they have to be friend functions. Syntax: returntype classname::
operator#(arg-list) { } E.g. class Complex { private: float real; float imaginary; public: Complex operator+ (Complex); };
//overloaded + operator for class Complex Complex Complex::operator+ (Complex c) { Complex tmp; tmp.real = this.real + c.real;
tmp.imaginary = this.imaginary + c.imaginary; return temp; } The only C++ operators that cannot be overloaded are dot (.), .*, ?:,
sizeof, typeid and scope resolution operator (::).
========================
What are Friend Functions and Friend Classes in C++ ?
A friend can be a function, another class or individual member function of a class. With the help of a friend function it is possible to
grant a non member function access to the private members of a class using a friend. A friend function has all access to all the
private and protected members of the class for which it is the friend. To declare a friend function includes the function prototype within
the class preceding it with the keyword friend. When a friend function is called it need to be qualified by the object name as it is not a
member function of the class. E.g. class Complex { private: float real; float imaginary; public: friend Complex operator+ (Complex,
Complex); };//overloaded + operator for class Complex Complex operator+ (Complex c, Complex d) { Complex tmp; tmp.real = d.real
+ c.real; tmp.imaginary = d.imaginary + c.imaginary; return temp; } To call the function: int main (){ Complex a, b, c; a = b + c; //this
will be called as operator+(b, c)} Friend classes are used when two or more classes are designed to work together and need access
to each other’s implementation. E.g. a class DataBaseCursor may want more privileges to the class Database. E.g. class
DatabaseCursor; class Database { //member variable and function declarations friend DatabaseCursor; };
=============================
What are Constructors and Destructors in C++ ?
A constructor constructs an object i.e. it initializes the objects internal data members as well as it may allocate resource (memory,
files, sockets, etc). The constructor has the same name as the class name and cannot have a return type not even void. A constructor
can take multiple arguments as its parameters. A class can have multiple constructors i.e. a constructor can be overloaded.
Whenever an object of a class is created it calls a constructor by default which is responsible for initializing the object. By default
every class has a default constructor which is a constructor with no arguments. However once you provide a constructor to a class
then the default constructor does not exist. e.g. class Stack{ int size;int top; int arr []; Stack(int a) //constructor of the class { size = a;
arr = new int[size]; }}; The destructor is the last member function called in the lifetime of a class object. Its job is to free the resources
that an object is holding. A class can have no more than a single destructor. The name of the destructor is ~ classname (). Like a
constructor, a destructor cannot have a void return type. e.g. ~Stack () //destructor { delete [] arr; }
======================
What is Inheritance ? How is a Class Inherited in C++ ?
Inheritance is one of the most important principles of object oriented language. Using inheritance one can create a class that can
have traits common to a set of related items. This class is then inherited by other classes each adding things are specific to them.
The class that is inherited is called the base class and the class that inherits from it is called as the derived class. When a class
inherits a base class, then all the members of the base class become members of the derived class. E.g. class derived-class-name::
access base-class-name{ //body of class}; The access of the members in the base class by derived class depends on the access
parameter. The access specifier must either be private, public or protected. If one doesn’t provide an access specifier then it is taken
as private by default. When access specifier is private then these members remain private to base class and the derived class cannot
access them. When access specifier is public then all the public members of a base class become public members of the derived
class and all the protected members of the base class become protected in the derived class. On using a protected access specifier
all public and protected members of the base class become protected members of the derived class.
================================
What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example.
A function that is defined in a base class but overridden by the derived class is called a virtual function. To create virtual functions
precede the function declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited the
derived class overrides the virtual function with its own definition. Virtual functions are like member functions however what makes
them different is the capability to support run time polymorphism when accessed via a pointer. A base class pointer can point to an
object of a derived class. When a base class pointer points to an object of a derived class that contains a virtual function, C++
determines which function version to call based on the type of object pointed by the base class pointer. This is runtime polymorphism
as it can be determined at run time. In this way when different objects are pointed to then different versions of virtual functions are
executed. Whenever a virtual function is defined all aspects of its prototype should match. Also virtual functions should be non static
members of the class and they cannot be friend functions too. E.g. class base { public: virtual void display (); }; class derived: public{
public: virtual void display ();};base *p, b;derived d1, d2;p = &b;p->display (); //calls base class functionp = &d1;p->display (); //calls
derived class function
======================
What are Templates in C++ ? How are Templates declared and used ?
Many data structures and algorithms can be defined independently of the type of data they manipulate. A template allows the
separation of the type dependent part from the type independent part. This results in a significant amount of code reusability.
Templates can be class templates or function templates. A class template is used for creating a class in which one more values are
parameterized. The syntax of a class template is:
template class class-name{ ...};
A class template can also have multiple parameters.
template class class-name{ ...};
Example -
template class Array{ private: T *arr []; public: Array (int size = 10); };template Array::Array(int
size){ arr = new T[size];}
Create an Array object as: Array a; The function template is also written using the keyword template.
E.g. template class void push (T &element) { arr[top] = elemen
========================
What is Polymorphism ? How is Polymorphism achieved in C++ ?
Polymorphism is one of the most important principle of object oriented language. Polymorphism means many forms i.e. one interface
multiple methods. The specific method to call depends on the nature of the situation. No matter what type of car it is the driving
mechanism is the same. For example, you might have a program that defines three different types of stacks. One stack is used for
integer values, one for character values, and one for floating-point values. Because of polymorphism, you can define one set of
names, push() and pop() , that can be used for all three stacks. In your program you will create three specific versions of these
functions, one for each type of stack, but names of the functions will be the same. The compiler will automatically select the right
function based upon the data being stored. Thus, the interface to a stack—the functions push() and pop() —are the same no matter
which type of stack is being used. C++ supports both run time and compile time polymorphism. Function overloading is a form of
compile time polymorphism while dynamic binding is a form of runtime polymorphism.
===============
What are the Standard Exceptions in C++ ?
C++ defined a hierarchy of standard exceptions that are thrown at runtime whenever an abnormal condition takes place. These
exceptions are derived from std::exception class defined in the header. Since there is a common base class of all these exceptions it
enables the application to catch these exceptions in a single catch statement. E.g. catch (std::exception &e){//code to handle the
exception} Some of the standard exceptions that are built in the language are: - std::bad_alloc: thrown by operator new -
std::bad_cast: as a result of dynamic_cast - std::bad_typeid: as a result of operator typeid - std::bad_exception: Whenever you want
to catch all exceptions then the exception parameter in the catch block should be an ellipsis. E.g. catch (…){ //this block will catch all
exceptions}
==============
What is Multiple Inheritance in C++ ? Explain with an example
It is possible for a derived class to inherit more than a single base class. This is referred as multiple inheritance. The class inherits
from multiple base classes where these classes are comma separated. Each listed base class must specify its own access level.
E.g.
class base1
{}
;
class base2
{}
;
class derived: public base1, public base2
{
};
The base class constructors are invoked in the declaration order within the class derivation list. In the above example the constructor
for base1 will be called first followed by the base2 constructor. Similarly the order of destructor is reverse of the constructor order.
If a class inherits from one or more base classes which themselves inherit from a common base class then it can lead to problems. In
such case one should use virtual inheritance. Under virtual inheritance only a single shared base class object is inherited regardless
of how many times the base class occurs in the derivation hierarchy.
E.g.
class derived: public virtual base1, public virtual base2
{}
;
==================
What is a Copy Constructor in C++ ? Give an example
Copy constructor is a type of constructor which constructs an object by copying the state from another object of the same class.
Whenever an object is copied, another object is created and in this process the copy constructor gets called. If the class of the object
being copied is x, the copy constructor’s signature is usually x::x (const x&).
Let’s take an example to illustrate this:
class Complex
{ int real, img;
public:
Complex (int, int);
Complex (const Complex& source); //copy constructor
};Complex:: Complex (const Complex& source)
{ this.real =
source.real;
this.img = source.img;
}
main ()
{
Complex a (2, 3);
Complex b = a; // this invokes the copy constructor
}
A copy constructor is called whenever an object is passed by value, returned by value or explicitly copied.
==================================
What is Function Overloading in C++ ?
Function overloading is the process of using the same name for two or more functions. However each function will be different in
terms of either different types of parameters or a different number of parameters. It is only through these differences that the compiler
knows which function to call in any given situation. Even if the number of parameters are same and types are same but they are
written in a different order then these functions will still be considered different. The return type parameter does not hold any
relevance to make two functions distinct. E.g. void display (int a);void display (string str); Both the above functions have the same
name but different parameters. So when a function display (2) is called the compiler calls the first function and when the argument
passed to display is a string then the second version is invoked.E.g. int display (int a );void display (int a); In the above example the
compiler will generate a compile time error as the return types are insufficient to overload functions
====================================
What are Pointers in C++ (Object Oriented Programming) ?
Pointers are used to store memory address values of objects. C++ defines a special address-of operator that when applied to an
object returns that object’s address value. E.g. int *pint; //this defines a pointer variableIn order store the address of the variable ‘j’ into
pint one should assign the address of j into pint variable as follows:pint = &j; // assigning the address of variable j into pointer pint In
order to access the actual object pint addresses we must first dereference pint using the dereference operator (*). *pint = *pint + 1; //
this statement will increment the value pint points to by 1 The type of the pointer variable should be the same as the variable whose
address it is used to hold. E.g. you cannot define a pointer variable of type float and use it to assign the address of a variable of type
integer
========================
What are volatile variables ? Explain Volatile variables
A variable is declared as volatile if its value can possibly be changed in ways outside either the control or detection of the compiler.
For example a variable that is updated by the system clock. Certain optimizations ordinarily performed by a compiler should therefore
not be applied to objects the programmer specifies as volatile. The volatile qualifier is used in much the same way as is the const
qualifier as an additional modifier to a type.E.g. volatile int count_value; The purpose of defining a variable as volatile is to inform the
compiler that the variable can change in ways undetectable by the compiler and hence the compiler should not perform any kind of
optimizations on these variables.
============================
What is the Difference between Overloaded Functions and Overridden Functions ?
In C++, overloading is simply the use of the same function identifier for different functions declared in the same scope.
E.g. void display (int);void display (string);
The above two functions are clearly overloaded. The compiler will distinguish among them by the actual argument used in the call to
display.
Overriding can occur only in the presence of a base class virtual function. Overriding has nothing whatsoever to do with overloading.
A nonvirtual base class function cannot be overridden, only hidden. In overriding the function prototype in the derived class has to be
exactly the same as the one in the base class
=============================
What are Inline Functions ? When are Inline Functions used ?
The idea behind inline functions is to insert the code of a called function at the point where the function is called. It is useful to
distinguish between "inline," a keyword qualifier that is simply a request to the compiler, and "inlined," which refers to actual inline
expansion of the function. A function can be decorated with the inline keyword either in the class definition or in its own definition if the
definition physically occurs before the function is invoked. The compiler does not promise that an inline function will be inlined, and the
details of when/when not are compiler-dependent. On the other hand, any function that is defined within the class body will be treated
implicitly as an inline function with or without the explicit inline keyword. Inline code is faster than a function call for two reasons. First,
a CALL instruction takes time to execute. Second, if there are arguments to pass, these have to be placed on the stack, which also
takes time
============================
What are Mutable and Const in C++ ?
Class member functions may be declared as const, which causes them to be treated as a const pointer. Thus, that function cannot
modify the object that invokes it. Also, a const object may not invoke a non-const member function. However, a const member
function can be called by either const or non-const objects. Sometimes there will be one or more members of a class that you want a
const function to be able to modify even though you don't want the function to be able to modify any of its other members. You can
accomplish this through the use of mutable. It overrides constness. That is, a mutable member can be modified by a const member
function. E.g. class MyClass{ int i; mutable int j; Public: void setValues const () { i = 10; //wrong j = 15; //correct }};
===========================
What is ‘this’ Pointer (object) in C++
When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (that is, the
object on which the function is called).This pointer is called this.Within a member function, the members of a class can be accessed
directly, withoutany object or class qualification. The this pointer points to the object that invoked the member function. Also the this
pointer is automatically passed to all member functions. Another thing to note is that the friend functions are not members of a class
and, therefore, are not passed a this pointer. Second, static member functions do not have a this pointer. e.g. class Stack { int top; int
size; Stack (int top, int size) { this.top = top; this.size = size; }};
========================
What is Scope Resolution Operator in C++?
There are two used of the scope resolution operator in C++. The first use being that a scope resolution operator is used to unhide the
global variable that might have got hidden by the local variables. Hence in order to access the hidden global variable one needs to
prefix the variable name with the scope resolution operator (::). e.g. int i = 10; int main () { int i = 20; Cout << i; // this prints the value
20 Cout << ::i; // in order to use the global i one needs to prefix it with the scope //resolution operator. } The second use of the
operator is used to access the members declared in class scope. Whenever a scope resolution operator is used the name of the
member that follows the operator is looked up in the scope of the class with the name that appears before the operator.
==================================
What is Scope Resolution Operator in C++?
There are two used of the scope resolution operator in C++. The first use being that a scope resolution operator is used to unhide the
global variable that might have got hidden by the local variables. Hence in order to access the hidden global variable one needs to
prefix the variable name with the scope resolution operator (::). e.g. int i = 10; int main () { int i = 20; Cout << i; // this prints the value
20 Cout << ::i; // in order to use the global i one needs to prefix it with the scope //resolution operator. } The second use of the
operator is used to access the members declared in class scope. Whenever a scope resolution operator is used the name of the
member that follows the operator is looked up in the scope of the class with the name that appears before the operator.
===================
What are Const Member Functions in C++ ?
There can be two cases in which a member function can be declared as a const function: whenever the member function wants to
guarantee that it won't make any changes to its this object or whenever a caller needs to invoke the member function via a referenceto-
const or pointer-to-const. The compiler wont allow a const member function to change *this or to invoke a non-const member
function for this object. E.g. int getCount() const;int getCount () const{ //function definition}
===========================
Explain Composition in C++ with an example
Composition allows software to be developed by assembling existing components rather than creating new ones. Composition is also
sometimes called as aggregation and defines the process of putting an object inside another object. It models the has-a relationship.
E.g. a class employee can contain an object of type salary which itself is another type of object. e.g.
class Salary{ private: double DA; double HRA; double travelAllowance; double basic salary; public: //member functions};Class
Employee{ private: int empno; Salary salary; //composition: salary object is contained inside employee public: //member functions};
==================
What do you mean by ‘Return by Reference’ in C++ ?
A function can be declared to return a pointer or a reference. When the function is returning a reference, the calling function receives
the lvalue for the variable. The calling function can then modify the variable or take its address.
If the return value is a large class object, using a reference (or pointer) return type is more efficient than returning the class object by
value. In some cases, the compiler can automatically transform a return by value to a return by reference.
E.g.
Complex& compute (Complex c)
{
Complex *tmp = new Complex ();
// …
return tmp;
}However care should be exercised when returning a reference to a local object. The lifetime of the local object terminates with the
termination of the function. The reference is left aliasing undefined memory after the function terminates.
====================
What are static Data and Static Member Functions in C++ ?
Static data members are data and functions that are associated with the class itself, rather than with the objects of the class. For
example a count is needed of how many objects of a particular class type have been created at any one point in the program. A static
data member acts as a global object that belongs to its class type. Unlike other data members where each class object has its own
copy, there is only one copy of a static data member per class type. A static data member is a single, shared object accessible to all
objects of its class type. A data member is made static by prefixing the data member declaration within the class body with the
keyword static or prefixing the function declaration with the keyword static. A static function cannot access any other member
variables of the object. One does not need to create a class object for accessing a static member or a static function; a static function
can be invoked using the class name as class_name::static_member_function. e.g. class ShoppingCart{ private: static int totalItems;
//static data member public: static int getTotalItems (); //static member function};
===========================
What is a Pure Virtual Member Function ?
Whenever a virtual function in a base class is not redefined by the derived class then the version defined in the base class will be
used. However in many cases it may so happen that there can be no meaningful definition of a virtual function within the base class.
Or you may want to ensure that all derived classes override a virtual function. To handle both these cases the solution is a pure virtual
function.
A pure virtual function is a function that has no definition in the base class. The definition of such a function is equal to 0.E.g. void
draw () = 0; // this is a pure virtual function
If a class contains at least one virtual function then that class is called an abstract class and one cannot create an instance of an
abstract class. Also if a class inherits from a class that contains a pure virtual function then the derived class has to provide a
definition for the pure virtual function. Failure to do so will result in an abstract derived class.
==============================
What are Preprocessor Directives ?
The preprocessor directives are instructions to the compiler. All these preprocessor lines begin with a pound (#). They are executed
before the compilation of the code begins. These directives can only span a single line and does not need to end in a semicolon.
The preprocessor contains the following directives:
- #define: this defines an identifier and some value to this identifier. This value can be any character sequence and will be substituted
in the code file for each instance of the corresponding identifier.
e.g. #define MIN 0
- #include: it tells the compiler to link to another source file. The name of the source file can be in angle brackets or double quotes.
e.g. #include
- #error: tells the compiler to stop compilation. Used primarily for debugging purposes.
- #if:
- #elif
- #endif
- #else: The above four directives are conditional directives. They allow you to conditionally include portions of code based on
outcome of a constant expression.
E.g. #if OPTION == 1
//do something
#else
//do something else
#endif
- #ifndef
- #undef: the above indicates conditional compilation dependinf upon if a variable is defined or not defined.
======================================