0% found this document useful (0 votes)
132 views23 pages

Oops Short Answer Questions

The document describes the structure of a C++ program and various tokens used in C++. It discusses: 1. The typical sections of a C++ program include header files, global declarations, class declarations, the main function, and method definitions. 2. Tokens in C++ include identifiers, keywords, constants, operators, and strings. Common tokens are variables, structures, functions, reserved words, mathematical/logical operators, and character sequences. 3. Constants in C++ include integer, floating-point, Boolean, character, and string literals. Constants are declared using the const keyword and their values cannot change.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views23 pages

Oops Short Answer Questions

The document describes the structure of a C++ program and various tokens used in C++. It discusses: 1. The typical sections of a C++ program include header files, global declarations, class declarations, the main function, and method definitions. 2. Tokens in C++ include identifiers, keywords, constants, operators, and strings. Common tokens are variables, structures, functions, reserved words, mathematical/logical operators, and character sequences. 3. Constants in C++ include integer, floating-point, Boolean, character, and string literals. Constants are declared using the const keyword and their values cannot change.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 1

Short answer

1. describe about the structure of C++.

Basically C++ program involves the following sections :

Fig: Structure of C++ Program

Section 1 : Header File Declaration Section

Header files used in the program are listed here.

1. Header File provides Prototype declaration for different library functions.


2. We can also include user define header file.
3. Basically all preprocessor directives are written in this section.

Section 2 : Global Declaration Section

1. Global Variables are declared here.


2. Global Declaration may include –
o Declaring Structure
o Declaring Class
o Declaring Variable

Section 3 : Class Declaration Section

1. Actually this section can be considered as sub section for the global declaration
section.
2. Class declaration and all methods of that class are defined here.
Section 4 : Main Function

1. Each and every C++ program always starts with main function.
2. This is entry point for all the function. Each and every method is called indirectly
through main.
3. We can create class objects in the main.
4. Operating system call this function automatically.

Section 5 : Method Definition Section

This is optional section . Generally this method was used in C Programming.

2. write about various tokens in C++

Each individual word and punctuation is referred to as a token in C++. Tokens are the
smallest building block or smallest unit of a C++ program.
These following tokens are available in C++:

 Identifiers

 Keywords

 Constants

 Operators

 Strings

Identifiers: Identifiers are names given to different entries such as variables,


structures, and functions. Also, identifier names should have to be unique because these
entities are used in the execution of the program.
Keywords: Keywords is reserved words which have fixed meaning and its meaning
cannot be changed. The meaning and working of these keywords are already known to
the compiler. C++ has more numbers of keyword than C and those extra ones have
special working capabilities.
Operators: C++ operator is a symbol that is used to perform mathematical or logical
manipulations.
Constants: Constants are lik a variable, except that their value never changes during
execution once defined.
Strings: Strings are objects that signify sequences of characters.
3. write about Constants / Literals in C++
Constants are the items whose value cannot be changed during the program execution.
Constants are also called as Literals.

C++ supports five types of constants

C++
constants

Floating
Integer Boolean Character String
Point

Declaring Constants:

To declare a constant we need to use a keyword ‘const’.

Syntax: const type constant_name;

Example: int const SIDE = 50;

Integer literals:
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned
and long, respectively. The suffix can be uppercase or lowercase and can be in any
order.

Following are other examples of various types of Integer literals:

30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.

Here are some examples of floating-point literals:

3.14159 // Legal
314159E-5L // Legal
Boolean literals:
There are two Boolean literals and they are part of standard C++ keywords:

 A value of true representing true.


 A value of false representing false.

You should not consider the value of true equal to 1 and value of false equal to 0.

Character literals:
Character literals are enclosed in single quotes. If the literal begins with L (uppercase
only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of
variable . Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a
simple variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').

String literals:
String literals are enclosed in double quotes. A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.

4. write various identifiers used in c++

Various data items with symbolic names in C++ is called as Identifiers. Following data
items are called as Identifier in C++ –

1. Names of functions
2. Names of arrays
3. Names of variables
4. Names of classes

The rules of naming identifiers in C++ :

1. C++ is case-sensitive so that Uppercase Letters and Lower Case letters are
different
2. The name of identifier cannot begin with a digit. However, Underscore can be
used as first character while declaring the identifier.
3. Only alphabetic characters, digits and underscore (_) are permitted in C++
language for declaring identifier.
4. Other special characters are not allowed for naming a variable / identifier
5. Keywords cannot be used as Identifier.

 Some valid examples:- sum, a1, a2, _1, _a, average, a_b, x123y...
 Some invalid examples:- 1a, a-b, float
5. What is string in C++ ? How to define it in c++
In C programming, the collection of characters is stored in the form of arrays, this is
also supported in C++ programming. Hence it's called C-strings.

C-strings are arrays of type char terminated with null character, that is, \0 (ASCII


value of null character is 0).

Defining a C-string?
char str[] = "C++";

In the above code, str is a string and it holds 4 characters.

Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.

Alternative ways of defining a string


char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};
Like arrays, it is not necessary to use all the space allocated for the string. For
example:
char str[100] = "C++";

6. what is function? Give the brief description about it.

Functions are used to provide modularity to a program. Creating an application


using function makes it easier to understand, edit, check errors etc.
Syntax of Function
return-type function-name (parameters)
{
// function-body
}

return-type : suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions which does not return
anything, they are mentioned with void.

Function Name : is the name of the function, using the function name it is called.

Parameters : are variables to hold values of arguments passed while function is


called. A function may or may not contain parameter list.
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}
int main()
{
int a = 10;
int b = 20;
sum (a, b);
}

Here, a and b are sent as arguments, and x and y are parameters which will hold


values of a and b to perform required operation inside function.

Function body : is he part where the code statements are written.

7. Write the importance of main function in C++

main() function is the entry point of any C++ program. It is the point at which execution of

program is started. When a C++ program is executed, the execution control goes directly to

the main() function. Every C++ program have a main() function.

Syntax
void main()
{
............
............
}

In above syntax;

 void: is a keyword in C++ language, void means nothing, whenever we use


void as a function return type then that function nothing return. here main()
function no return any value.
 In place of void we can also use int return type of main() function, at that time
main() return integer type value.
 main: is a name of function which is predefined function in C++ library.

8. what is function call? write in how many ways the function call can be initiated.

Function call statement calls the function by matching its name and arguments. A
function call can be made by using function name and providing the required
parameters.

Syntax for function call


function_name ([actual arguments]);

For example,
display(a);
s = sum(x,y);
A function can be called by two ways. They are:

 Call by value
 Call by reference
9. What are called as Inline Functions? write its syntax
Inline functions are actual functions, which are copied everywhere during compilation,
like preprocessor macro, so the overhead of function calling is reduced. All the functions
defined inside class definition are by default inline, but you can also make any non-class
function inline by using keyword inline with them.
For an inline function, declaration and definition must be done together. For example,
inline void fun(int a)
{
return a++;
}
Some Important points about Inline Functions

1. We must keep inline functions small, small inline functions have better efficiency.
2. Inline functions do increase efficiency, but we should not make all the functions
inline. Because if we make large functions inline, it may lead to code bloat, and
might affect the speed too.
3. Hence, it is adviced to define large functions outside the class definition using
scope resolution  :: operator, because if we define such functions inside class
definition, then they become inline automatically.
4. Inline functions are kept in the Symbol Table by the compiler, and all the call for
such functions is taken care at compile time.

10. what is friend function?

If a function is defined as a friend function in C++ then the protected and private data of
a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the
body of a class starting with the keyword friend.

Declaration of friend function in C++


class class_name  
{  
    friend data_type function_name(argument/s);  
};  

Unit 2

Short Answer

1. What is class ? How to define a class in C++?

A class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows etc. Based on these descriptions we build the
house. House is the object.

As, many houses can be made from the same description, we can create many
objects from a class.

defining a class in C++?

A class is defined in C++ using keyword class followed by the name of class.


The body of class is defined inside the curly brackets and terminated by a semicolon
at the end.

class className
{
// some data
// some functions
};

2. What is an object in C++? How to define

Class is mere a blueprint or a template. No storage is assigned when we define a


class. Objects are instances of class, which holds the data variables declared in class
and the member functions work on these class objects.
Each object has different data variables. Objects are initialised using special class
functions called Constructors. 

Syntax to Define Object in C++


className objectVariableName;

You can create objects of Test class (defined in above example) as follows:

class Test
{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
int main()
{
Test o1, o2;
}

Here, two objects o1 and o2 of Test class are created.

In the above class Test, data1 and data2 are data members


and function1() and function2() are member functions.

3. What are Member Functions ?


Member functions are the functions, which have their declaration inside the class
definition and works on the data members of the class. The definition of member
functions can be inside or outside the definition of class.
If the member function is defined inside the class definition it can be defined
directly, but if its defined outside the class, then we have to use the scope
resolution  ::  operator along with class name along with function name.

// defining member function


class Cube
{
public:
int side;
int getVolume(); // Declaring function getVolume with no argument and return
type int.
};
If we define the function inside class then we don't not need to declare it first, we
can directly define the function.

4. Write a note on Local Classes.

Local class is a class defined inside a function. Following are some of the rules for using
these classes.
 Global variables declared above the function can be used with the scope operator
"::".
 Static variables declared inside the function can also be used.
 Automatic local variables cannot be used.
 It cannot have static data member objects.
 Member functions must be defined inside the local classes.
 Enclosing functions cannot access the private member objects of a local class.

5. Write a short note on constructors and destructors.


C++ provides a special member function called the constructor which enables an object
to initialize itself at the time of its creation. This is known as automatic initialization of
objects. This concept of C++ also provides another member function called destructor
which is used to destroy the objects when they are no longer required.

 A constructor is a method that has the same name as its class.


 A destructor is a method that has as its name the class name prefixed by a tilde,
~.
 Neither constructors nor destructors return values. They have no return type
specified.
 Constructors can have arguments.
 Constructors can be overloaded.
 If any constructor is written for the class, the compiler will not generate a default
constructor.
 The default constructor is a constructor with no arguments, or a constructor that
provides defaults for all arguments.
 The container classes such as vector require default constructors to be available
for the classes they hold. Dynamically allocated class arrays also require a default
constructor. If any constructors are defined, you should always define a default
constructor as well.
 Destructors have no arguments and thus cannot be overloaded.

6. Explain the types of constructors

Constructors are of three types :

1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor

Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no
parameter.

Parameterised Constructors
These are the constructors with parameter. Using this Constructor you can provide
different values to data members of different objects, by passing the appropriate values
as argument.

COPY Constructor

Copy Constructor is a type of constructor which is used to create a copy of an already


existing object of a class type. It is usually of the form X (X&), where X is the class
name.he compiler provides a default Copy Constructor to all the classes.
7. What is copy constructor? explain the syntax

Copy Constructor is a type of constructor which is used to create a copy of an already


existing object of a class type. It is usually of the form X (X&), where X is the class
name.he compiler provides a default Copy Constructor to all the classes.
Syntax of Copy Constructor
class-name (class-name &)
{
....
}
As it is used to create an object, hence it is called a constructor. And, it creates a new
object, which is exact copy of the existing copy, hence it is called copy constructor.

8. What is operator overloading?

Operator overloading is an important concept in C++. It is a type of polymorphism in


which an operator is overloaded to give user defined meaning to it. Overloaded
operator is used to perform operation on user-defined data type. For example '+'
operator can be overloaded to perform addition on various data types, like for Integer,
String(concatenation) etc.
Almost any operator can be overloaded in C++. However there are few operator which
can not be overloaded.Operator that are not overloaded are follows

 scope operator -  ::
 sizeof
 member selector -  .
 member pointer selector -  *
 ternary operator -  ?:

Syntax:

9. write the rules for operator overloading

In C++, following are the general rules for operator overloading.


1) Only built-in operators can be overloaded. New operators can not be created.
2) Arity of the operators cannot be changed.
3) Precedence and associativity of the operators cannot be changed.
4) Overloaded operators cannot have default arguments except the function call
operator () which can have default arguments.
5) Operators cannot be overloaded for built in types only. At least one operand must be
used defined type.
6) Assignment (=), subscript ([]), function call (“()”), and member selection (->)
operators must be defined as member functions
7) Except the operators specified in point 6, all other operators can be either member
functions or a non member functions.
8 ) Some operators like (assignment)=, (address)& and comma (,) are by default
overloaded.
10. What is type casting in C++.
A cast is a special operator that forces one data type to be converted into another. As
an operator, a cast is unary and has the same precedence as any other unary operator.
Syntax: (type) expression
Where type is the desired data type. There are other casting operators supported by C+
+, they are listed below:

 const_cast<type> (expr): The const_cast operator is used to explicitly override


const and/or volatile in a cast. The target type must be the same as the source
type except for the alteration of its const or volatile attributes. This type of
casting manipulates the const attribute of the passed object, either to be set or
removed.

 dynamic_cast<type> (expr): The dynamic_cast performs a runtime cast that


verifies the validity of the cast. If the cast cannot be made, the cast fails and the
expression evaluates to null. A dynamic_cast performs casts on polymorphic
types and can cast a A* pointer into a B* pointer only if the object being pointed
to actually is a B object.

 reinterpret_cast<type> (expr): The reinterpret_cast operator changes a


pointer to any other type of pointer. It also allows casting from pointer to an
integer type and vice versa.

 static_cast<type> (expr): The static_cast operator performs a nonpolymorphic


cast. For example, it can be used to cast a base class pointer into a derived class
pointer.

Unit 3

Short answer

1. What is inheritance and explain it with syntax

The process of obtaining the data members and methods from one class to another
class is known as inheritance. It is one of the fundamental features of object-oriented
programming.

Important points

 In the inheritance the class which is give data members and methods is
known as base or super or parent class.
 The class which is taking the data members and methods is known as sub or
derived or child class.
Syntax
class subclass_name : superclass_name
{
// data members
// methods
}

2. What is Virtual base class?

ambiguity can arise when several paths exist to a class from the same base class.
This means that a child class could have duplicate sets of members inherited from a
single base class.
C++ solves this issue by introducing a virtual base class. When a class is made
virtual, necessary care is taken so that the duplication is avoided regardless of the
number of paths that exist to the child class.

When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those
objects by declaring the base class as virtual when it is being inherited. Such a base
class is known as virtual base class. This can be achieved by preceding the base class’
name with the word virtual.

3. Define Abstract Class?

Abstract Class is a class which contains atleast one Pure Virtual function in it.
Abstract classes are used to provide an Interface for its sub classes. Classes
inheriting an Abstract Class must provide definition to the pure virtual function,
otherwise they will also become abstract class.
Characteristics of Abstract Class

Abstract class cannot be instantiated, but pointers and refrences of Abstract class
type can be created.

Abstract class can have normal functions and variables along with a pure virtual
function.

Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface. Classes inheriting an Abstract Class must implement all pure virtual
functions, or else they will become Abstract too.

4. what are nested classes?


A nested class is a class which is declared in another enclosing class. A nested
class is a member and as such has the same access rights as any other member.
The members of an enclosing class have no special access to members of a nested
class; the usual access rules shall be obeyed.

5. What is virtual function?


A virtual function a member function which is declared within base class and is re-
defined (Overriden) by derived class.When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.
 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.

6. what are the rules for virtual functions?

Rules for Virtual Functions


1. They Must be declared in public section of class.
2. Virtual functions cannot be static and also cannot be a friend function of another
class.
3. Virtual functions should be accessed using pointer or reference of base class type
to achieve run time polymorphism.
4. The prototype of virtual functions should be same in base as well as derived
class.
5. They are always defined in base class and overridden in derived class. It is not
mandatory for derived class to override (or re-define the virtual function), in that
case base class version of function is used.
A class may have virtual destructor but it cannot have a virtual constructor

7. write a note on late binding.

In Late Binding function call is resolved at runtime. Hence, now compiler determines
the type of object at runtime, and then binds the function call. Late Binding is also
called Dynamic Binding or RuntimeBinding.
Mechanism of Late Binding

To accomplich late binding, Compiler creates VTABLEs, for each class with virtual
function. The address of virtual functions is inserted into these tables. Whenever an
object of such class is created the compiler secretly inserts a pointer called vpointer,
pointing to VTABLE for that object. Hence when function is called, compiler is able to
resovle the call by binding the correct function using the vpointer.

8. What is pure virtual functions

A virtual function whose declaration ends with =0 is called a pure virtual function.
For example,

class Weapon
{
public:
virtual void features() = 0;
};
Here, the pure virtual function is
virtual void features() = 0
And, the class Weapon is an abstract class.

9. write a note on virtual constructors and destructors.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a


virtual function is a syntax error.
Virtual Destructors
Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of
the Base class must be made virtual for proper destrucstion of the object when the
program exits.

10. What is stream class?


C++ streams are based on class and object theory. C++ has number of classes that
work with console and file operations. These classes are known as stream classes.
Figure shows the stream classes.

All these classes are declared in the header file iostream.h. The file iostream.h must
be included in the program, if we are using the functions of these classes.

Unit 4

Short answer

1. What is template? in how many ways it can be defined?


Templates are the foundation of generic programming, which involves writing code
in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function. The


library containers like iterators and algorithms are examples of generic
programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define
many different kinds of vectors for example, vector <int> or vector <string>.
The concept of templates can be used in two different ways:

 Function Templates
 Class Templates

2. what is Class Template ? how to define it.

Like function templates, you can also create class templates for generic class
operations.

Sometimes, you need a class implementation that is same for all classes, only the
data types used are different.

Normally, you would need to create a different class for each data type OR create
different member variables and functions within a single class.

This will unnecessarily bloat your code base and will be hard to maintain, as a
change is one class/function should be performed on all classes/functions.

However, class templates make it easy to reuse the same code for all data types.

How to declare a class template


template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};

3. How to create a class template object?

To create a class template object, you need to define the data type inside a < > when
creation.

className<dataType> classObject;
For example:

className<int> classObject;

className<float> classObject;

className<string> classObject;

4. What is function template? how to define it?

A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single
normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data,
you use function overloading to create two functions with the required function
declaration.

However, a better approach would be to use function templates because you can
perform the same task writing less and maintainable code.

How to declare a function template?

A function template starts with the keyword template followed by template


parameter/s inside  < > which is followed by function declaration.

template <class T>


T someFunction(T arg)
{
... .. ...
}

5. What is template instantiation


The compiler creates functions using function templates.

int i = 2, j = 3;
cout << max(i, j);
string a(''Hello''), b(''World'');
cout<< max(a, b);
In this case, the compiler creates two different max()functions using the function
template

template<typenameT> T max(constT& a, constT& b);

This is called template instantiation. The parameter T in the template definition is


called the formal parameteror formal argument.

6. What is exception?
An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.

Following are main advantages of exception handling over traditional error


handling.
Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling
becomes separate from the normal flow.

7. Why do we use exceptions

Following are main advantages of exception handling over traditional error


handling.
Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling
becomes separate from the normal flow.

Functions/Methods can handle any exceptions they choose: A function can throw
many exceptions, but may choose to handle some of them. The other exceptions
which are thrown, but not caught can be handled by caller. If the caller chooses not
to catch them, then the exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way .
Grouping of Error Types: In C++, both basic types and objects can be thrown as
exception. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes, categorize them according to types.

8. what are throw and catch exceptions

Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

9. Explain about different keywords to handle exceptions

throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

try: A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.

10, What is STL? Explain about it

The C++ STL (Standard Template Library) is a powerful set of C++ template classes
to provides general-purpose templatized classes and functions that implement
many popular and commonly used algorithms and data structures like vectors, lists,
queues, and stacks.

At the core of the C++ Standard Template Library are following three well-
structured components:

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.

You might also like