Você está na página 1de 70

C++ programming functions, blocks Aptitude

Questions and Answers


Here, you will find functions and blocks related aptitude questions and answers.

List of Functions and Blocks related C++ programming Aptitude Questions and
Answers

1) What will be the output of following program?


1
2 #include <iostream>
3 using namespace std;
4
void fun1(int x)
5 {
6 cout<<x<<endl;
7 }
8
9 int main()
10{
//function calling
11 fun1(10,20);
12 return 0;
13}
14

1. Run Time Error


2. Compile Time Error
3. 10
4. 10, 20

Answer
Correct Answer - 2

Compile Time Error


Since function declaration has only one integer argument while we are passing to arguments,
hence program will through compiler error.

2) What will be the output of following program?


1 #include <iostream>
2 using namespace std;
3
int main()
4 {
5 //function declaration
6 void fun(void);
7 //function calling
8 fun();
cout<<"::OK"<<endl;
9 return 0;
10}
11//function definition
12void fun(void)
13{ cout<<"Hello";
14}
15
16
17

1. Compile Time Error


2. Run Time Error
3. ::OK
4. Hello::OK

Answer
Correct Answer - 4

Hello::OK
We can declare any function within the main().

3) What will be the output of following program?


1
2 #include <iostream>
3 using namespace std;
4
5 //declaration and definition
void print_value(int x,int y=10)
6 {
7 cout<<"x:"<<x<<",y:"<<y<<endl;
8 }
9 int main()
10{
11 //function calling
12 print_value(100);
13 return 0;
14 }
15

1. x:100,y:10
2. x:100,y:100
3. x:100,y:Garbage
4. Error
Answer
Correct Answer - 1

x:100,y:10
In the function declaration, argument y is a default parameter and while calling we are not
passing second parameter hence 10 will be the value of second parameter y.

4) What will be the output of following program?


1
2 #include <iostream>
3 using namespace std;
4
5 //declaration and definition
6 void fun(const int x=10)
{
7 cout<<"x:"<<x<<endl;
8 }
9 int main()
10{
11 const int a=100;
cout<<"call 1:";
12 fun();
13 cout<<"call 2:";
14 fun(a);
15 return 0;
}
16
17

1. Call 1:10
Call 2:100
2. Call 1:10
Call 2:10
3. Call 1:100
Call 2:100
4. Error

Answer
Correct Answer - 1

Call 1:10
Call 2:100
In the first calling there is no parameter, hence default value 10 will be printed and in the second
calling 100 is passing as a parameter so 100 will be printed after second calling.

5) Which is the correct form to call function fun1()?


#include <iostream>
1 using namespace std;
2
3 namespace myfunctions
4 {
void fun1(void)
5 {
6 cout<<"Fun1"<<endl;
7 }
8 }
9 int
{
main()
10 .....
11 return 0;
12 }
13
14
15

1. fun1();
2. myfunctions.fun1();
3. myfunctions::fun1();
4. myfunctions->fun1();

Answer
Correct Answer - 3

myfunctions::fun1();
fun1() is declared and define within the namespace and we can access a function of a namespace
using Scope Resolution Operator (::).

6) What will be the output of following program?


1
#include <iostream>
2 using namespace std;
3
4 namespace myfunctions
5 {
6 void fun1(void)
{
7 cout<<"Fun1"<<endl;
8 }
9 void fun1(int a)
10 {
11 cout<<a<<endl;
}
12}
13int main()
14{
15 myfunctions::fun1(10.2f);
return 0;
16}
17
18
19

1. Error
2. 10
3. 10.200000
4. 10.2

Answer
Correct Answer - 2

10
In the namespace there are two functions with same name (it is called function overloading), we
are calling fun1 with value 10.2f and this value will convert into integer (implicit conversion)
hence second fun1 will be called.

Functions - C++ Questions and Answers


This is the c++ programming questions and answers section on "Functions" with explanation for various
interview, competitive examination and entrance test. Solved examples with detailed answer
description, explanation are given and it would be easy to understand.

1. Where does the execution of the program starts?

 A. user-defined function
 B. main function
 C. void function
 D. none of the mentioned

Answer & Explanation

Answer: Option B

Explanation:

Normally the execution of the program in c++ starts from main only.

2. What are mandatory parts in function declaration?

 A. return type,function name


 B. return type,function name,parameters
 C. both a and b
 D. none of the mentioned
Answer & Explanation

Answer: Option A

Explanation:

In a function, return type and function name are mandatory all else are just used as a choice.

3. which of the following is used to terminate the function declaration?

 A. :
 B. )
 C. ;
 D. none of the mentioned

Answer & Explanation

Answer: Option C

Explanation:

4. How many max number of arguments can present in function in c99 compiler?

 A. 99
 B. 90
 C. 102
 D. 127

Answer & Explanation

Answer: Option D

Explanation:

127

5. Which is more effective while calling the functions?

 A. call by value
 B. call by reference
 C. call by pointer
 D. none of the mentioned
Answer & Explanation

Answer: Option B

Explanation:

In the call by reference, it will just copy the address of the variable to access it, so it will reduce
the memory in accessing it.

6.

What is the output of this program?

#include < iostream >

using namespace std;

void mani()

void mani()

cout << "hai";

int main()

main();

return 0;

 A. hai
 B. haihai
 C. compile time error
 D. none of the mentioned

 View Answer
 Workspace
 Report
 Discuss
Answer & Explanation

Answer: Option C

Explanation:

We have to use the semicolon to declare the function in line 3. If we did means, the program will
execute.

7.

What is the output of this program?

#include < iostream >

using namespace std;

void fun(int x, int y)

x = 20;

y = 10;

int main()

int x = 10;

fun(x, x);

cout << x;

return 0;

 A. 10
 B. 20
 C. compile time error
 D. none of the mentioned
Answer & Explanation

Answer: Option A

Explanation:

In this program, we called by value so the value will not be changed, So the output is 10

8. What is the scope of the variable declared in the user definied function?

 A. whole program
 B. only inside the {} block
 C. both a and b
 D. none of the mentioned

Answer & Explanation

Answer: Option B

Explanation:

The variable is valid only in the function block as in other.

9. How many minimum number of functions are need to be presented in c++?

 A. 0
 B. 1
 C. 2
 D. 3

Answer & Explanation

Answer: Option B

Explanation:

The main function is the mandatory part, it is needed for the execution of the program to start.

10. How many ways of passing a parameter are there in c++?

 A. 1
 B. 2
 C. 3
 D. 4
Answer & Explanation

Answer: Option C

Explanation:

There are three ways of passing a parameter. They are pass by value,pass by reference and pass
by pointer.

11. Which is used to keep the call by reference value as intact?

 A. static
 B. const
 C. absolute
 D. none of the mentioned

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option B

Explanation:

Because const will not change the value of the variables during the execution.

12. By default how the value are passed in c++?

 A. call by value
 B. call by reference
 C. call by pointer
 D. none of the mentioned

Answer & Explanation

Answer: Option A

Explanation:

call by value
13. What will happen when we use void in argument passing?

 A. It will not return value to its caller


 B. It will return value to its caller
 C. both a & b are correct
 D. none of the mentioned

Answer & Explanation

Answer: Option A

Explanation:

As void is not having any return value, it will not return the value to the caller.

14. How many types of returning values are present in c++?

 A. 1
 B. 2
 C. 3
 D. 4

Answer & Explanation

Answer: Option C

Explanation:

The three types of returning values are return by value, return by reference and return by address.

15. What will you use if you are not intended to get a return value?

 A. static
 B. const
 C. volatile
 D. void

Answer & Explanation

Answer: Option D

Explanation:

Void is used to not to return anything.


16. Where does the return statement returns the execution of the program?

 A. main function
 B. caller function
 C. same function
 D. none of the mentioned

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option B

Explanation:

caller function

17. When will we use the function overloading?

 A. same function name but different number of arguments


 B. different function name but same number of arguments
 C. same function name but same number of arguments
 D. different function name but different number of arguments

Answer & Explanation

Answer: Option A

Explanation:

In function overloading, we can use any number of arguments but same function name.

18. Overloaded functions are

 A. Very long functions that can hardly run


 B. One function containing another one or more functions inside it.
 C. Two or more functions with the same name but different number of parameters or type.
 D. none of the mentioned

Answer & Explanation

Answer: Option C
Explanation:

Two or more functions with the same name but different number of parameters or type.

19. What will happen while using pass by reference

 A. The values of those variables are passed to the function so that it can manipulate them
 B. The location of variable in memory is passed to the function so that it can use the same
memory area for its processing
 C. The function declaration should contain ampersand (& in its type declaration)
 D. All of the mentioned

Answer & Explanation

Answer: Option B

Explanation:

In pass by reference, we can use the function to access the variable and it can modify it.
Therefore we are using pass by reference.

20. When our function doesn’t need to return anything means what we will as parameter in function?

 A. void
 B. blank space
 C. both a & b
 D. none of the mentioned

Answer & Explanation

Answer: Option B

Explanation:

blank space

21. What are the advantages of passing arguments by reference?

 A. Changes to parameter values within the function also affect the original arguments.
 B. There is need to copy parameter values (i.e. less memory used)
 C. There is no need to call constructors for parameters (i.e. faster)
 D. All of the mentioned

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option D

Explanation:

All of the mentioned

22. To which does the function pointer point to?

 A. variable
 B. constants
 C. function
 D. absolute variables

Answer & Explanation

Answer: Option C

Explanation:

function

23. What we will not do with function pointers?

 A. allocation of memory
 B. de-allocation of memory
 C. both a & b
 D. none of the mentioned

Answer & Explanation

Answer: Option C

Explanation:

As it is used to execute a block of code, So we will not allocate or deallocate memory.

24. What is the default calling convention for a compiler in c++?


 A. __cdecl
 B. __stdcall
 C. __pascal
 D. __fastcall

Answer & Explanation

Answer: Option A

Explanation:

__cdecl

25. What are the mandatory part to present in function pointers?

 A. &
 B. retrun values
 C. data types
 D. none of the mentioned

Answer & Explanation

Answer: Option C

Explanation:

The data types are mandatory for declaring the variables in the function pointers.

26. which of the following can be passed in function pointers?

 A. variables
 B. data types
 C. functions
 D. none of the mentioned

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option C
Explanation:

functions

27. What is meaning of following declaration? int(*ptr[5])();

 A. ptr is pointer to function.


 B. ptr is array of pointer to function.
 C. ptr is pointer to such function which return type is array.
 D. ptr is pointer to array of function.

Answer & Explanation

Answer: Option B

Explanation:

In this expression, ptr is array not pointer.

28. If the user didn’t supply the user value means, then what value will it take?

 A. default value
 B. rise an error
 C. both a & b
 D. none of the mentioned

Answer & Explanation

Answer: Option A

Explanation:

If the user didn’t supply the value means, the compiler will take the given value in the argument
list.

29. Where does the default parameter can be placed by the user?

 A. leftmost
 B. rightmost
 C. both a & b
 D. none of the mentioned

Answer & Explanation

Answer: Option B
Explanation:

rightmost

30. Which value will it take when both user and default values are given?

 A. user value
 B. default value
 C. custom value
 D. none of the mentioned

 Answer: Option A
 Explanation:
 The default value will be used when the user value is not given, So in this case, the user
value will be taken.

31. What we can’t place followed by the non-default arguments?

 A. trailing arguments
 B. default arguments
 C. both a & b
 D. none of the mentioned

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option B

Explanation:

default arguments

32. If we start our function call with default arguments means, what will be proceeding arguments?

 A. user argument
 B. empty arguments
 C. default arguments
 D. none of the mentioned
Answer & Explanation

Answer: Option C

Explanation:

As a rule, the default argument must be followed by default arguments only.

33. What is the default return type of a function ?

 A. int
 B. void
 C. float
 D. char

Answer & Explanation

Answer: Option B

Explanation:

void

34. Which header file is used to pass unknown number of arguments to function?

 A. stdlib.h
 B. string.h
 C. stdarg.h
 D. none of the mentioned
 Answer: Option C
 Explanation:
 Because the cstdarg defines this header file to process the unknown number of
arguments.

35. How can you access the arguments that are manipulated in the function?

 A. va_list
 B. arg_list
 C. both a & b
 D. none of the mentioned

 Answer: Option A
 Explanation:
 va_list
36. What is the maximum number of arguments or parameters that can be present in one function call?

 A. 64
 B. 256
 C. 255
 D. 16

 View Answer
 Workspace
 Report
 Discuss

Answer & Explanation

Answer: Option B

Explanation:

256

37. Which header file should you include if you are to develop a function that can accept variable
number of arguments?

 A. varag.h
 B. stdlib.h
 C. stdio.h
 D. stdarg.h

 Answer: Option D
 Explanation:
 stdarg.h

38. What will initialize the list of arguments in stdarg.h header file?

 A. va_list
 B. va_start
 C. va_arg
 D. none of the mentioned

 Answer: Option B
 Explanation:
 va_start
C++ Programming Questions and Answers –
Structures
This section on C++ interview questions and answers focuses on “Structures”. One shall practice these
interview questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other competitive
exams. These questions can be attempted by anyone focusing on learning C++ programming language.
They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our C++
interview questions come with detailed explanation of the answers which helps in better understanding
of C++ concepts.

Here is a listing of C++ interview questions on “Structures” along with answers, explanations
and/or solutions:

1. The data elements in structure are also known as what?


a) objects
b) members
c) datas
d) none of the mentioned
View Answer

Answer:b
Explanation:None.

2. What will be used when terminating a structure?


a) :
b) }
c) ;
d) ;;
View Answer

Answer:c
Explanation:While terminating a structure, a semi colon is used to end this up.

3. What will happen when the structure is declared?


a) it will not allocate any memory
b) it will allocate the memory
c) it will be declared and initialized
d) none of the mentioned
View Answer

Answer:a
Explantion:While the structure is declared, it will not be initialized, So it will not allocate any memory.
4. The declaration of structure is also called as?
a) sructure creator
b) structure signifier
c) structure specifier
d) none of the mentioned
View Answer

Answer:c
Explanation:The structure declaration with open and close braces and with a semicolon is also called
structure specifier.

5. What is the output of this program?

1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. int main()
5. {
6. struct student {
7. int num;
8. char name[25];
9. };
10. student stu;
11. stu.num = 123;
12. strcpy(stu.name, "John");
13. cout << stu.num << endl;
14. cout << stu.name << endl;
15. return 0;
16. }
advertisements

a) 123
john
b) john
john
c) compile time error
d) none of the mentioned
View Answer

Answer:a
Explanation:We are coping the value john to the name and then we are printing the values that are in
the program.
Output:
$ g++ stu.cpp
$ a.out
123
john

6. What is the output of this program?


1. #include <iostream>
2. using namespace std;
3. struct Time {
4. int hours;
5. int minutes;
6. int seconds;
7. };
8. int toSeconds(Time now);
9. int main()
10. {
11. Time t;
12. t.hours = 5;
13. t.minutes = 30;
14. t.seconds = 45;
15. cout << "Total seconds: " << toSeconds(t) << endl;
16. return 0;
17. }
18. int toSeconds(Time now)
19. {
20. return 3600 * now.hours + 60 * now.minutes + now.seconds;
21. }

a) 19845
b) 20000
c) 15000
d) 19844
View Answer

Answer:a
Explanation:In this program, we are just converting the given hours and minutes into seconds.
Output:
$ g++ stu1.cpp
$ a.out
Total seconds:19845

7. What will be the output of this program?

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. struct ShoeType {
6. string style;
7. double price;
8. };
9. ShoeType shoe1, shoe2;
10. shoe1.style = "Adidas";
11. shoe1.price = 9.99;
12. cout << shoe1.style << " $ "<< shoe1.price;
13. shoe2 = shoe1;
14. shoe2.price = shoe2.price / 9;
15. cout << shoe2.style << " $ "<< shoe2.price;
16. return 0;
17. }

a) Adidas $ 9.99
Adidas $ 1.11
b) Adidas $ 9.99
Adidas $ 9.11
c) Adidas $ 9.99
Adidas $ 11.11
d) none of the mentioned
View Answer

Answer:a
Explanation:We copied the value of shoe1 into shoe2 and divide the shoe2 value by 9, So this is the
output.
Output:
$ g++ stu2.cpp
$ a.out
Adidas $ 9.99
Adidas $ 1.11

8. What is the output of this program?

1. #include <iostream>
2. using namespace std;
3. struct sec {
4. int a;
5. char b;
6. };
7. int main()
8. {
9. struct sec s ={25,50};
10. struct sec *ps =(struct sec *)&s;
11. cout << ps->a << ps->b;
12. return 0;
13. }
advertisements

a) 252
b) 253
c) 254
d) 262
View Answer

Answer:a
Explanation:In this program, We are dividing the values of a and b, printing it.
Output:
$ g++ stu5.cpp
$ a.out
252
9. Which of the following is a properly defined structure?
a) struct {int a;}
b) struct a_struct {int a;}
c) struct a_struct int a;
d) struct a_struct {int a;};
View Answer

Answer:d
Explantion:The a_struct is declared as structure name and its data element is a.

10. Which of the following accesses a variable in structure *b?


a) b->var;
b) b.var;
c) b-var;
d) b>var;
View Answer

Answer:a
Explanation:Because in a structure pointer, the data element is declared as above only.

HCL C++ Interview questions and answers


Posted by Stephen thangaraj at 02:20

Define structured programming.

Structured programming techniques use functions or subroutines to organize the programming


code. The programming purpose is broken into smaller pieces and organized together using
function. This technique provides cleaner code and simplifies maintaining the program. Each
function has its own identity and isolated from other, thus change in one function doesn’t affect
other.

Explain Object oriented programming.


Object oriented programming uses objects to design applications. This technique is designed
toisolate data. The data and the functions that operate on the data are combined into single unit.
This unit is called an object. Each object can have properties and member functions. You can call
member function to access data of an object. It is based on several techniques like encapsulation,
modularity, polymorphism, and inheritance.
List down elements of an object oriented language.

Class

A class is a user defined data type. It serves as a template of the objects. You can definestructure
and behavior of an object using class. It includes data and the member functions thatoperate on
data.

Inheritance

Inheritance enables a new class to reuse the state and behavior of old class. The new class
inherits properties and methods from the old class and is called as derived class and the old class
is called as base class. The methods thus inherited can be extended using overriding facility of
C++.

Encapsulation

The wrapping up of data and member function into an object is called encapsulation. The data is
not accessible to the outside world and only those functions which are wrapped into the object
can access it. An encapsulated objects act as a "black box" for other parts of the program which
interact with it. They provide a service, but the calling objects do not need to know the details
how the service is accomplished.

Polymorphism

Polymorphism enables one common interface for many implementations that allows objects to
act differently under different circumstances. You can also achieve polymorphism in C++ by
function overloading, operator overloading and implementation inheritance.

What is function prototype in C++?


A function prototype is a declaration of a function that omits the function body. It specifies the
function’s name, argument types and return type. E.g. int add(int,int)

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

/* */ is used for commenting a block of code.

// is used for single line comments.


Define Structure in C++.

The C++ programming technique allows defining user defined datatypes through structure. The

syntax to declare structure is as follows:


struct student

char name[100]

char address[250]

};
Explain typecasting.

Typecasting enables data type conversion. C++ supports implicit conversions and explicit
conversion. Implicit conversions automatically performed when a value is copied to a compatible
type. If there is an operation between an int and a float, the int is promoted to float before
performing operation automatically by the compiler.

You can cast explicitly as follows.

int i, j, k;

k = i * long(j);

Define void pointer using C++.

In C++, void represents the absence of type, so void pointers are pointers that point to a value
that has no type. The void pointers can point to any data type.

You can declare void pointer as follows.

void *p;

When do you use :: Operator in C++?


:: is the scope resolution operator. When local variable and global variable are having same
name, local variable gets the priority. C++ allows flexibility of accessing both the variables
through a scope resolution operator.

Define reference variable in C++.


A reference variable is just like pointer with few differences. It is declared using & operator. A
reference variable must always be initialized. The reference variable once defined to refer to a
variable can’t be changed to point to other variable. You can’t create an array of references the
way it is possible with pointer.
What is const qualifier?
const qualifier is used to specify the variable that can’t be change throughout the program.
Variables with const qualifier are often named in uppercase.

When do you use bool data type?


The bool data type can take only two values true or false.

What is function overloading in C++?

You can have multiple functions with same name using function overloading facility of C++.
You can use same name for multiple functions when all these functions are doing same thing.

What is operator overloading in C++?


With this facility in C++, you can give additional meaning to operators.

Define Inline Function.

When the function is defined Inline, the C++ compiler puts the function body inside the calling
function. You can define function as Inline when the function body is small and need to be
called many times, thus reduces the overhead in calling a function like passing values, passing
control,returning values, returning control.

Define class using C++.


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

Explain constructors and destructors.

Constructors are the member functions of the class that executes automatically whenever
anobject is created. Constructors have the same name as the class. Constructors initialize the
class. Constructors can’t have return type. Destructors are called when the objects are destroyed.

Destructors are usually used to deallocate memory and do other cleanup for a class object and its
class members when the object is destroyed. A destructor is called for a class object when
that object passes out of scope or is explicitly deleted. A destructor takes no arguments and has
no return type.

When do you use this pointer?


’this pointer’ is used as a pointer to the class object instance by the member function. The
address of the class instance is passed as an implicit parameter to the member functions.

What is new and delete operator?

In C++, when you want dynamic memory, you can use operator new. It returns a pointer to the
beginning of the new block of memory allocated. It returns a pointer to the beginning of the new
block of memory allocated. When memory allocated by new operator is no longer required, it is
freed using operator delete.

Explain the difference between structures and classes.


Syntactically and functionally, both structures and classes are identical. By default, members of
structures have public accessibility and public inheritance from their parent(s), while members of
classes are private and inherit privately from their parent(s).

Define local class in C++.

Local class is define within the scope of a function and nested within a function.

E.g.

int func1()

class localclass1

};

Explain container class and its types in C++.


A container stores many entities and provide sequential or direct access to them. List, vector and
strings are such containers in standard template library. The string class is a container that holds
chars. All container classes access the contained elements safely and efficiently by using
iterators. Container class is a class that hold group of same or mixed objects in memory. It can be
heterogeneous and homogeneous. Heterogeneous container class can hold mixed objects in
memory whereas when it is holding same objects, it is called as homogeneous container class.
Define an Iterator class.

A container class hold group of objects and iterator class is used to traverse through the objects
maintained by a container class. The iterator class provides access to the classes inside a
container. They are objects that point to other objects. Iterator points to one element in a range,
and then it is possible to increment it so that it points to the next element.

There are several different types of iterators:

input_iterator

output_iterator

forward_iterator

bidirectional_iterator

random_iterator

reverse_iterator

Define storage classes in C++.

Storage class defined for a variable determines the accessibility and longevity of the variable.
The accessibility of the variable relates to the portion of the program that has access to the
variable. The longevity of the variable refers to the length of time the variable exists within the
program.

Auto

Automatic variable, also called as local variable and it has scope only within the function block
where it is defined.

External

External variable are defined outside any function and memory is set aside for this type of
variable once it is declared and remained until the end of the program. These variables are also
called global variables.

Static

The static automatic variables, as with local variables, are accessible only within the function in
which it is defined. Static automatic variables exist until the program ends in the same manner as
external variables. In order to maintain value between function calls, the static variable takes its
presence.

Define namespace in C++.


Namespaces groups together entities like classes, objects and functions under a name.
Namespaces provide a way to avoid name collisions of variables, types, classes or functions.
Namespaces reduces the use of nested class thus reduces the inconvenience of handling nested
class.

Define access privileges in C++.

You have access privileges in C++ such as public, protected and private that helps in
encapsulation of data at various level.

Private

If data are declared as private in a class then it is accessible by the member functions of the class
where they are declared. The private member functions can be accessed only by the members of

the class. By default, any member of the class is considered as private by the C++ compiler, if no
specifier is declared for the member.

Public

The member functions with public access specifier can be accessed outside of the class. This
kind of members is accessed by creating instance of the class.

Protected

Protected members are accessible by the class itself and it’s sub-classes. The members with
protected specifier act exactly like private as long as they are referenced within the class or from

the instance of the class. This specifier specially used when you need to use inheritance facility
of C++. The protected members become private of a child class in case of private inheritance,
public in case of public inheritance, and stay protected in case of protected inheritance.

What is the default access level?


The access privileges in C++ are private, public and protected. The default access level assigned
to members of a class is private. Private members of a class are accessible only within the class
and by friends of the class. Protected members are accessible by the class itself and its
subclasses. Public members of a class can be accessed by anyone.
Explain friend class in C++.
When a class declares another class as its friend, it is giving complete access to all its data and
methods including private and protected data and methods to the friend class member methods.
Friendship is one way only, which means if A declares B as its friend it does NOT mean that A
can access private data of B. It only means that B can access all data of A.

What is virtual function?


Virtual function is the member function of a class that can be overriden in its derived class. It is
declared with virtual keyword. Virtual function call is resolved at run-time (dynamic binding)
whereas the non virtual member functions are resolved at compile time (static binding).

What are pure virtual functions?

Pure virtual function is the function in the base class with no body. Since no body, you have to
add the notation =0 for declaration of the pure virtual function in the base class.

The base class with pure virtual function can’t be instantiated since there is no definition of the
function in the base class. It is necessary for the derived class to override pure virtual function.

This type of class with one or more pure virtual function is called abstract class which can’t be
instantiated, it can only be inherited.

class shape

public: virtual void draw() = 0;

};

Define default constructor.

Default constructor is the constructor with no arguments or all the arguments has default values.
Define abstraction. The process of hiding unnecessary data and exposing essential features is
called abstraction. Abstraction is separating the logical properties from implementation details.

What is overriding?
Defining a function in the derived class with same name as in the parent class is called
overriding. In C++, the base class member can be overridden by the derived class function with
the same signature as the base class function. Method overriding is used to provide different
implementations of a function so that a more specific behavior can be realized.
What is copy constructor?

A copy constructor is a special type of constructor that is used to create an object as a copy of an
existing object. It takes an argument which is a reference to the object to be copied.

TCS

1. List the implicit member functions of a class?

 Copy constructor
 Move constructor
 Move assignment operator
 Default constructor
 Destructor
 Copy assignment operator

2. Define token?

Various tokens are available in C++ program. They are either a constant, a keyword, a symbol,
an identifier or a string literal.

3. What are the storage qualifiers in C++ programming?

 Volatile
 Const
 Mutable

4. Define block scope variable in C++?

A scope of the variable which is only applicable within a block is said to be block scope variable.

5. Differentiate C and C++?

C language

 Structural programming language.


 Top down approach is followed in program design.
 Polymorphism, inheritance, operator overloading concepts are not possible.

C++ language

 Object oriented language


 Polymorphism, inheritance, operator overloading concepts are possible here.
 Bottom, up approach is followed.
6. Define friend function?

A friend function can access the members of the class, even it is not a member of the class. To
make it possible we have to declare it following the keyword within the class.

7. List the object oriented programming language defining traits?

 Polymorphism
 Encapsulation
 Inheritance

8. What are the Advantages of Inheritance?

 Allows code reusability.


 Thus, it reduces program development time.
 Allows reuse of proven.
 Also reduces the cost of application.

9. What are the storage classes in C++?

 Static
 Register
 Auto
 Extern
 Mutable

10. Define scope resolution operator?

If the function is defined outside the class, this one is used to associate function definition to the
class. It is also used to resolve the scope of global variables.

11. Define inline function?

Before the function definition, with the keyword inline, a function is prefixed it is said to be an
inline function.

12. List the different ways of passing parameters to the functions?

 Call by reference
 Call by value
 Call by address

13. List out the acess specifiers in c++?

There are three types fo acess specifiers,


 Private
 Public
 Protected

Get the videos on C++ interview questions here below,

HCL

1. What is C++?

Released in 1985, C++ is an object-oriented programming language created by Bjarne


Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory
management and adding several features - including a new datatype known as a class (you will
learn more about these later) - to allow object-oriented programming. C++ maintains the features
of C which allowed for low-level memory access but also gives the programmer new tools to
simplify memory management.
C++ used for:
C++ is a powerful general-purpose programming language. It can be used to create small
programs or large applications. It can be used to make CGI scripts or console-only DOS
programs. C++ allows you to create programs to do almost anything you need to do. The creator
of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.

2. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes
at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet
the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

3. What is the difference between realloc() and free()?


The free subroutine frees a block of memory previously allocated by the malloc subroutine.
Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is
a null value, no action will occur. The realloc subroutine changes the size of the block of
memory pointed to by the Pointer parameter to the number of bytes specified by the Size
parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter
must have been created with the malloc, calloc, or realloc subroutines and not been deallocated
with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a
valid pointer.
4. Base class has some virtual method and derived class has a method with the same name.
If we initialize the base class pointer with derived object, calling of that virtual method will
result in which method being called?

a. Base method
b. Derived method
Ans. B

5. What is function overloading and operator overloading?


Function overloading: C++ enables several functions of the same name to be defined, as long as
these functions have different sets of parameters (at least as far as their types are concerned).
This capability is called function overloading. When an overloaded function is called, the C++
compiler selects the proper function by examining the number, types and order of the arguments
in the call. Function overloading is commonly used to create several functions of the same name
that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects
of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls.
They form a pleasant facade that doesn't add anything fundamental to the language (but they can
improve understandability and reduce maintenance costs).

6. What are the advantages of inheritance?


It permits code reusability. Reusability saves time in program development. It encourages the
reuse of proven and debugged high-quality software, thus reducing problem after a system
becomes functional.

7.What is the difference between declaration and definition?


The declaration tells the compiler that at some later point we plan to present the definition of this
declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout << endl;
}

8. How do you write a function that can reverse a linked-list?


void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}

curnext->next = cur;
}
}

9. What do you mean by inline function?


The idea behind inline functions is to insert the code of a called function at the point where the
function is called. If done carefully, this can improve the application's performance in exchange
for increased compile time and possibly (but not always) an increase in the size of the generated
binary executables.

10. Write a program that ask for user input from 5 to 9 then calculate the average

#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i<MAX; i++) {
cout << "Please enter your input between 5 and 9: ";
cin >> numb;
while ( numb<5 || numb>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " << average << "\n";
return 0;
}

11. Write a short code using C++ to print out all odd number from 1 to 100 using a for loop

for( unsigned int i = 1; i < = 100; i++ )


if( i & 0x00000001 )
cout << i << \",\";

12. What is public, protected, private?


Public, protected and private are three access specifier in C++.
Public data members and member functions are accessible outside the class.
Protected data members and member functions are only available to derived classes.
Private data members and member functions can’t be accessed outside the class. However there
is an exception can be using friend classes.

13. Tell how to check whether a linked list is circular.


Create two pointers, each set to the start of the list. Update each as follows: while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}
OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the item just before
pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.
14. What is virtual constructors/destructors?
Virtual destructors:If an object (with a non-virtual destructor) is destroyed explicitly by applying
the delete operator to a base-class pointer to the object, the base-class destructor function
(matching the pointer type) is called on the object.
There is a simple solution to this problem declare a virtual base-class destructor. This makes all
derived-class destructors virtual even though they don’t have the same name as the base-class
destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete
operator to a base-class pointer to a derived-class object, the destructor for the appropriate class
is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual
function is a syntax error.
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying
the delete operator to a base-class pointer to the object, the base-class destructor function
(matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all
derived-class destructors virtual even though they don’t have the same name as the base-class
destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete
operator to a base-class pointer to a derived-class object, the destructor for the appropriate class
is called.
Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function
is a syntax error.

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


Yes.

16. What are the advantages of inheritance?


• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem
after a system becomes functional.

17. What is the difference between declaration and definition?


The declaration tells the compiler that at some later point we plan to present the definition of this
declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”;
cout<<endl;
}
18. What is the difference between an array and a list?

Array is collection of homogeneous elements. List is collection of heterogeneous elements.


For Array memory allocated is static and continuous. For List memory allocated is dynamic and
Random.
Array: User need not have to keep in track of next memory allocation.
List: User has to keep in Track of next location where memory is allocated.
Array uses direct access of stored members, list uses sequencial access for members.
/With Array you have direct access to memory position 5
Object x = a[5]; // x takes directly a reference to 5th element of array
//With the list you have to cross all previous nodes in order to get the 5th node:
list mylist;
list::iterator it;
for( it = list.begin() ; it != list.end() ; it++ )
{
if( i==5)
{
x = *it;
break;
}
i++;
}

19. What is a template?


Templates allow to create generic functions that admit any data type as parameters and return
value without having to overload the function with all the possible data types. Until certain point
they fulfill the functionality of a macro. Its prototype is any of the two following ones:
template <class indetifier> function_declaration; template <typename indetifier>
function_declaration;
The only difference between both prototypes is the use of keyword class or typename, its use is
indistinct since both expressions have exactly the same meaning and behave exactly the same
way.

20. Define a constructor - What it is and how it might be called (2 methods).


Constructor is a member function of the class, with the name of the function being the same as
the class name. It also specifies how the object should be initialized.
Ways of calling constructor:
1) Implicitly: automatically by complier when an object is created.
2) Calling the constructors explicitly is possible, but it makes the code unverifiable.
class Point2D{
int x; int y;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
main(){
Point2D MyPoint; // Implicit Constructor call. In order to allocate memory on stack, the default
constructor is implicitly called.
Point2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocate memory on
HEAP we call the default constructor.
You have two pairs: new() and delete() and another pair : alloc() and free().

21. Explain differences between eg. new() and malloc()


1.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dont use
brackets will calling new or delete].
2.) no need of allocate the memory while using “new” but in “malloc()” we have to use
“sizeof()”.
3.) “new” will initlize the new memory to 0 but “malloc()” gives random value in the new alloted
memory location [better to use calloc()]
new() allocates continous space for the object instace malloc() allocates distributed space.
new() is castless, meaning that allocates memory for this specific type,
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.

22. What is the difference between class and structure?


Structure: Initially (in C) a structure was used to bundle different type of data types together to
perform a particular functionality. But C++ extended the structure to contain functions also. The
major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.

23. What is RTTI?


Runtime type identification (RTTI) lets you find the dynamic type of an object when you have
only a pointer or a reference to the base type. RTTI is the official way in standard C++ to
discover the type of an object and to convert the type of a pointer or reference (that is, dynamic
typing).

24.What is encapsulation?
Packaging an object’s variables within its methods is called encapsulation.

25.Explain term “Polymorphism” and give an example using eg. SHAPE object: If I have a
base class SHAPE, how would I define DRAW methods for two objects CIRCLE and
SQUARE“Polymorphism”: A phenomenon which enables an object to react differently to the
same function call. in C++ it is attained by using a keyword virtual
Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub classes must implement the
DRAW() method and SHAPE cannot be instatiated
public class CIRCLE::public SHAPE
{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}

now from the user class the calls would be like globally
SHAPE *newShape;
When user action is to draw
public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

public void MENU::OnClickDrawCircle(){


newShape = new SQUARE();
}

the when user actually draws


public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};
class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};
class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};
Each object is driven down from SHAPE implementing Draw() function in its own way.

26. What is an object?


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

27. How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell,
just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are
from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

28. What do you mean by inheritance?


Inheritance is the process of creating new classes, called derived classes, from existing classes or
base classes. The derived class inherits all the capabilities of the base class, but can add
embellishments and refinements of its own.

29.Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
Point2D MyPoint;
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR

On the other hand, you can assign and read the public data members:
MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them: MyPoint.pinned = true; //
Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem
30. What is namespace?
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To
say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and
functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the
general namespace. In order to access to these variables from outside the namespace we have to
use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global
object or function can have the same name than another one, causing a redefinition error.

31. What is a COPY CONSTRUCTOR and when is it called?


A copy constructor is a method that accepts an object of the same class and copies it’s data
members to the object on the left part of assignment:
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}

main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345

32. What is Boyce Codd Normal form?


A relation schema R is in BCNF with respect to a set F of functional dependencies if for all
functional dependencies in F+ of the form a-> , where a and b is a subset of R, at least one of the
following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R

33. What is virtual class and friend class?


Friend classes are used when two or more classes are designed to work together and need access
to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In
other words, they help keep private things private. For instance, it may be desirable for class
DatabaseCursor to have more privilege to the internals of class Database than main() has.

34. What is the word you will use when defining a function in base class to allow this
function to be a polimorphic function?

virtual

35. What do you mean by binding of data and functions?

Encapsulation.

36. What are 2 ways of exporting a function from a DLL?

1. Taking a reference to the function from the DLL instance.


2. Using the DLL ’s Type Library

37. What is the difference between an object and a class?

Classes and objects are separate but related concepts. Every object belongs to a class and every
class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and after the execution
of a program. The attributes of a class don't change.
- The class to which an object belongs is also (usually) static. If a particular object belongs to a
certain class at the time that it is created then it almost certainly will still belong to that class
right up until the time that it is destroyed.
- An Object on the other hand has a limited lifespan. Objects are created and eventually
destroyed. Also during that lifetime, the attributes of the object may undergo significant change.
38. What is a class?

Class is a user-defined data type in C++. It can be created to solve a particular kind of problem.
After creation the user need not know the specifics of the working of a class.

39. What is friend function?

As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access
its private and protected members. A friend function is not a member of the class. But it must be
listed in the class definition.

40. Which recursive sorting technique always makes recursive calls to sort subarrays that
are about half size of the original array?

Mergesort always makes recursive calls to sort subarrays that are about half size of the original
array, resulting in O(n log n) time.

41. What is abstraction?

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

42. What are virtual functions?

A virtual function allows derived classes to replace the implementation provided by the base
class. The compiler makes sure the replacement is always called whenever the object in question
is actually of the derived class, even if the object is accessed by a base pointer rather than a
derived pointer. This allows algorithms in the base class to be replaced in the derived class, even
if users don't know about the derived class.

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

An internal iterator is implemented with member functions of the class that has items to step
through. .An external iterator is implemented as a separate class that can be "attach" to the object
that has items to step through. .An external iterator has the advantage that many difference
iterators can be active simultaneously on the same object.

44. What is a scope resolution operator?


A scope resolution operator (::), can be used to define the member functions of a class outside
the class.

45. What do you mean by pure virtual functions?

A pure virtual member function is a member function that the base class forces derived classes to
provide. Normally these member functions have no implementation. Pure virtual functions are
equated to zero.
class Shape { public: virtual void draw() = 0; };

46. What is polymorphism? Explain with an example?

"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or
reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions. Another example can be a
plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings.

47.What’s the output of the following program? Why?

#include <stdio.h>
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;
printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}
Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)

48. Why arrays are usually processed with for loop?

The real power of arrays comes from their facility of using an index variable to traverse the
array, accessing each element with the same expression a[i]. All the is needed to make this work
is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length
-1. That is exactly what a loop does.

49. What is an HTML tag?

An HTML tag is a syntactical construct in the HTML language that abbreviates specific
instructions to be executed when the HTML script is loaded into a Web browser. It is like a
method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.

50.Explain which of the following declarations will compile and what will be constant - a
pointer or the value pointed at: * const char *
* char const *
* char * const

51. What problems might the following macro bring to the application?

#define sq(x) x*x

52. Anything wrong with this code?

T *p = new T[10];
delete p;
Everything is correct, Only the first element of the array will be deleted”, The entire array will be
deleted, but only the first element destructor will be called.
53. Anything wrong with this code?

T *p = 0;
delete p;
Yes, the program will crash in an attempt to delete a null pointer.

54. How do you decide which integer type to use?

It depends on our requirement. When we are required an integer to be stored in 1 byte (means
less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes we use long int.
A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or 4-byte
integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer.

55. What does extern mean in a function declaration?

Using extern in a function declaration we can make a function such that it can used outside the
file in which it is defined.
An extern variable, function definition, or declaration also makes the described variable or
function usable by the succeeding part of the current source file. This declaration does not
replace the definition. The declaration is used to describe the variable that is externally defined.
If a declaration for an identifier already exists at file scope, any extern declaration of the same
identifier found within a block refers to that same object. If no other declaration for the identifier
exists at file scope, the identifier has external linkage.

56. What can I safely assume about the initial values of variables which are not explicitly
initialized?

It depends on complier which may assign any garbage value to a variable if it is not initialized.

57. What is the difference between char a[] = “string”; and char *p = “string”;?

In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case
if *p is assigned to some other value the allocate memory can change.

58. What’s the auto keyword good for?


Not much. It declares an object with automatic storage duration. Which means the object will be
destroyed at the end of the objects scope. All variables in functions that are not declared as static
and not dynamically allocated have automatic storage duration by default.
For example
int main()
{
int a; //this is the same as writing “auto int a;”
}
Local variables occur within a scope; they are “local” to a function. They are often called
automatic variables because they automatically come into being when the scope is entered and
automatically go away when the scope closes. The keyword auto makes this explicit, but local
variables default to auto auto auto auto so it is never necessary to declare something as an auto
auto auto auto.

59. What is the difference between char a[] = “string”; and char *p = “string”; ?

a[] = “string”;
char *p = “string”;
The difference is this:
p is pointing to a constant string, you can never safely say
p[3]=’x';
however you can always say a[3]=’x';
char a[]=”string”; - character array initialization.
char *p=”string” ; - non-const pointer to a const-string.( this is permitted only in the case of char
pointer in C++ to preserve backward compatibility with C.)

60. How do I declare an array of N pointers to functions returning pointers to functions


returning pointers to characters?

If you want the code to be even slightly readable, you will use typedefs.
typedef char* (*functiontype_one)(void);
typedef functiontype_one (*functiontype_two)(void);
functiontype_two myarray[N]; //assuming N is a const integral

61. What does extern mean in a function declaration?


It tells the compiler that a variable or a function exists, even if the compiler hasn’t yet seen it in
the file currently being compiled. This variable or function may be defined in another file or
further down in the current file.

62. How do I initialize a pointer to a function?


This is the way to initialize a pointer to a function
void fun(int a)
{
}
void main()
{
void (*fp)(int);
fp=fun;
fp(1);
}

63. How do you link a C++ program to C functions?

By using the extern "C" linkage specification around the C function declarations.

64. Explain the scope resolution operator.

It permits a program to reference an identifier in the global scope that has been hidden by
another identifier with the same name in the local scope.

65. What are the differences between a C++ struct and C++ class?
The default member and base-class access specifier are different.

66. How many ways are there to initialize an int with a constant?

Two. There are two formats for initializers in C++ as shown in the example that follows. The
first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);

67. How does throwing and catching exceptions differ from using setjmp and longjmp?

The throw operation calls the destructors for automatic objects instantiated since entry to the try
block.
68. What is a default constructor?

Default constructor WITH arguments class B { public: B (int m = 0) : n (m) {} int n; }; int
main(int argc, char *argv[]) { B b; return 0; }

69. What is a conversion constructor?


A constructor that accepts one argument of a different type.

70. What is the difference between a copy constructor and an overloaded assignment
operator?

A copy constructor constructs a new object by using the content of the argument object. An
overloaded assignment operator assigns the contents of an existing object to another existing
object of the same class.

71. When should you use multiple inheritance?

There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot
be accurately modeled any other way."

72. Explain the ISA and HASA class relationships. How would you implement each in a
class design?

A specialized class "is" a specialization of another class and, therefore, has the ISA relationship
with the other class. An Employee ISA Person. This relationship is best implemented with
inheritance. Employee is derived from Person. A class may have an instance of another class. For
example, an employee "has" a salary, therefore the Employee class has the HASA relationship
with the Salary class. This relationship is best implemented by embedding an object of the Salary
class in the Employee class.

73. When is a template a better solution than a base class?

When you are designing a generic class to contain or otherwise manage objects of other types,
when the format and behavior of those other types are unimportant to their containment or
management, and particularly when those other types are unknown (thus, the generosity) to the
designer of the container or manager class.
74. What is a mutable member?

One that can be modified by the class even when the object of the class or the member function
doing the modification is const.

75. What is an explicit constructor?

A conversion constructor declared with the explicit keyword. The compiler does not use an
explicit constructor to implement an implied conversion of types. It’s purpose is reserved
explicitly for construction.

76. What is the Standard Template Library (STL)?

A library of container templates approved by the ANSI committee for inclusion in the standard
C++ specification. A programmer who then launches into a discussion of the generic
programming model, iterators, allocators, algorithms, and such, has a higher than average
understanding of the new technology that STL brings to C++ programming.

77. Describe run-time type identification.

The ability to determine at run time the type of an object by using the typeid operator or the
dynamic cast operator.

78. What problem does the namespace feature solve?

Multiple providers of libraries might use common global identifiers causing a name collision
when an application tries to link with two or more such libraries. The namespace feature
surrounds a library’s external declarations with a unique namespace that eliminates the potential
for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of
course.

79. Are there any new intrinsic (built-in) data types?


Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.

80. Will the following program execute?


void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}
It will throw an error, as arithmetic operations cannot be performed on void pointers.

81. For the following C program

#define AREA(x)(3.14*x*x)
main()
{
float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000

82. void main()

{
int d=5;
printf("%f",d);
}
Ans: Undefined

83. void main()


{
int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf("%d",i);break;
{
case 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}
Ans: 1,2,3,4

84.void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}
Ans: 6

85.void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(i<j)
printf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}
Ans: less</j)

86. void main()


{
float j;
j=1000*1000;
printf("%f",j);
}
1. 1000000
2. Overflow
3. Error
4. None
Ans: 4
87. How do you declare an array of N pointers to functions returning pointers to functions
returning pointers to characters?

Ans: The first part of this question can be answered in at least three ways:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */
3. Use the cdecl program, which turns English into C and vice versa:
cdecl> declare a as array of pointer to function returning pointer to function returning pointer to
char
char *(*(*a[])())()

88.What is a modifier?

A modifier, also called a modifying function is a member function that changes the value of at
least one data member. In other words, an operation that modifies the state of an object.
Modifiers are also known as ‘mutators’.

89.What is an accessor?

An accessor is a class operation that does not modify the state of an object. The accessor
functions need to be declared as const operations

90.Differentiate between a template class and class template.

Template class: A generic definition or a parameterized class not instantiated until the client
provides the needed information. It’s jargon for plain templates.

Class template: A class template specifies how individual classes can be constructed much like
the way class specifies how individual objects can be constructed. It’s jargon for plain classes

91.When does a name clash occur?


A name clash occurs when a name is defined in more than one place. For example., two different
class libraries could give two different classes the same name. If you try to use many class
libraries at the same time, there is a fair chance that you will be unable to compile or link the
program because of name clashes.

92.What is a dangling pointer?

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

93.Differentiate between the message and method.

Message:

Objects communicate by sending messages to each other.


A message is sent to invoke a method

Method:

Provides response to a message.


It is an implementation of an operation.

94.What is an adaptor class or Wrapper class?

A class that has no functionality of its own. Its member functions hide the use of a third party
software component or an object with the non-compatible interface or a non-object-oriented
implementation.

95.What is a Null object?

It is an object of some class whose purpose is to indicate that a real object of that class does not
exist. One common use for a null object is a return value from a member function that is
supposed to return an object with some specified properties but cannot find such an object.
96.What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a logical condition
to ensure the correct working of a class. Class invariants must hold when an object is created,
and they must be preserved under all operations of the class. In particular all class invariants are
both preconditions and post-conditions for all operations or member functions of the class.

97.What do you mean by Stack unwinding?

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

98.What are proxy objects?

Objects that stand for other objects are called proxy objects or surrogates.

99.Name some pure object oriented languages.

Smalltalk, Java, Eiffel, Sather.

100.What is an orthogonal base class?

If two base classes have no overlapping methods or data they are said to be independent of, or
orthogonal to each other. Orthogonal in the sense means that two classes operate in
different dimensions and do not interfere with each other in any way. The same derived class
may inherit such classes with no difficulty.

101.What is the difference between Mutex and Binary semaphore?

semaphore is used to synchronize processes. where as mutex is used to provide synchronization


between threads running in the same process

102.What is destructor?

Destructor usually deletes any extra resources allocated by the object.


103.What are C++ storage classes?

auto
register
static
extern
auto:the default. Variables are automatically created and initialized when they are defined and
are destroyed at the end of the block containing their definition. They are not visible outside that
block
register:a type of auto variable. a suggestion to the compiler to use a CPU register for
performance
static:a variable that is known only in the function that contains its definition but is never
destroyed and retains its value between calls to that function. It exists from the time the program
begins execution
extern:a static variable whose definition and placement is determined when all object and library
modules are combined (linked) to form the executable code file. It can be visible outside the file
where it is defined.

104.What is reference ?

reference is a name that acts as an alias, or alternative name, for a previously defined variable or
an object.prepending variable with "&" symbol makes it as reference.
for example:
int a;
int &b = a;

105.What are the defining traits of an object-oriented language?

The defining traits of an object-oriented langauge are:


encapsulation
inheritance
polymorphism

106.What is Quadratic Probing?

The Performance problem encountered by linear probing is caused by the cluster buildup That
occurs as a result of the probing sequence. Quadratic probing uses a different sequence to avoid
primary clustering.
107.What is the chaining?

The Chaining technique basically looks at the hash table as an array of pointers to linked lists.
Each slot in the hash table is either empty or simply consists of a pointer to a linked list. You
resolve collisions by adding the elements that hash to the same slot to the linked list to which that
slot points. At the same time, deletions are easy, You simply delete elements from the linked list.

108.What is the Hash Function?

The hash function is an important part of the hashing technique. This function is used to
transform the keys into table addresses. The hash function we choose should be easy to compute
and should be able to transform the keys into integers in the range 0 to TR-1. Because most of
the commonly used hash functions are based on arithmetic operations, We should convert the
keys to numbers on which arithmetic operations can be performed

109.What is an Visualizations?

The visualization is the basically a way of presentation ,Its just a fancy name for the diagrams,
pictures, screen shots, prototypes, and any other visual representations created to help through
and design the graphical user interface of your product.

110.What is virtual inheritance?

Inheritance is a basically can be private , public, or virtual. With virtual inheritance there is only
one copy of each object even if the object appears more than once in the hierarchy.

111.What is multithreading

Multithreading is defined as :It is the task of creating a new thread of execution within an
existing process rather than starting a new process to begin a function. It is the ability of an
operating system to concurrently run programs that have been divided into subcomponents, or
threads.

112.What is the use of using?


Using is bassically a namespace scope. Its directive used to declare the accessibility of identifiers
declared within a namespace scope.

113.What is the use of exception handling?

Exception handling is bassically used to detect exceptions becouse it can be taken a


corresponding action

114.What is EOF?

EOF bassically stands for End of File, It is used to check for the end of file when a file is being
read.

115.Define the parameterized macros?

Parameterized macros are use for the parameters . It is the one which consist of template with
insertion points for the addition of parameters.

116.What is overflow error?

Overflow error basically a type of arithmatic errors.It's caused by the result of an arithmetic
operation being greater than the actual space provided by the system.

117.What is a nested class? Why can it be useful?


Nested classes basically useful for organizing code and controlling access and dependencies.
Nested classes obey access rules just like other parts of a class do.and that class is a class
enclosed within the scope of another class.

118.What are the disadvantages of C++?

a)It's not pure object oriented programming language.

b)Its a Platform dependent


c)C++ does not give excellant graphics as compare to java.
d)Its Not case sensitive.
e)C++ have Less features as comapred to Java& C#.
f)Its Not applicable in web enviornment.
g)Does not provide very strong type-checking.
h)c++ code is easily prone to errors related to data types, their conversions.
i)Does not provide efficient means for garbage collection.
j)No built in support for threads

119.What is an iterator?

An iterator is a bassically a type of object that represents a stream of data. It is Unlike a


sequence, an iterator can only provide the next item. The for-in statement uses iterators to control
the loop, and iterators can also be used in many other contexts

120.What is the Auto Storage Class?

Auto Storage Class is bassically the default. Variables are automatically created and initialized,
When they are defined and are destroyed at the end of the block containing their definition. They
are not visible outside that block.

121.What is callback function?

Callback function is the type of pointer for a function

122.What is the use of tellg ()?

tellg () provides a information about the current position of input/get pointer.

123.What is the use of tellp ()?

tellp ()use for the poitner postion :Its provides the current position of output/put pointer

124.Define the generic programming?


Generic Programmng is type of method. The method in which generic types are used as
arguments in algorithms for different data types and data structures is called generic
programming.

125.What is the use of Microsoft foundation class library?

The Microsoft Foundation Class Library also called as A Microsoft Foundation Classes or MFC.
It is basically a library that wraps portions of the Windows API in C++ classes, and including
functionality that enables them to use a default application framework. Classes are defined for
many of the handle-managed Windows objects and also for predefined windows and common
controls. MFC library would help us reduce the code and development time.

1. Base class has some virtual method and derived class has a method with the same name. If we
initialize the base class pointer with derived
object,. calling of that virtual method will result in which method being called?Â
a. Base method
b. Derived method..
Ans. b
2. For the following C program
#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
       Area of the circle is 19.625000
3. What do the following statements indicate. Explain.
· int(*p)[10]
· int*f()
· int(*pf)()
· int*p[10]
Refer to:
-- Kernighan & Ritchie page no. 122
-- Schaum series page no. 323
4.
void main()
{
int d=5;
printf("%f",d);
}
Ans: Undefined

5.
void main()
{
int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf("%d",i);break;
{
case 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}
Ans: 1,2,3,4

6.
void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}
Ans: 6

7.
void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(i
printf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}
Ans: less

8.
void main()
{
float j;
j=1000*1000;
printf("%f",j);
}

1. 1000000
2. Overflow
3. Error
4. None
Ans: 4

9. How do you declare an array of N pointers to functions returning


    pointers to functions returning pointers to characters?

Ans: The first part of this question can be answered in at least


       three ways:
   1. char *(*(*a[N])())();

   2. Build the declaration up incrementally, using typedefs:

ÂÂÂÂÂÂÂ typedef char *pc;Â Â Â /* pointer to char */


ÂÂÂÂÂÂÂ typedef pc fpc();Â Â Â /* function returning pointer to char */
ÂÂÂÂÂÂÂ typedef fpc *pfpc;Â Â Â /* pointer to above */
ÂÂÂÂÂÂÂ typedef pfpc fpfpc();Â Â Â /* function returning... */
ÂÂÂÂÂÂÂ typedef fpfpc *pfpfpc;Â Â Â /* pointer to... */
ÂÂÂÂÂÂÂ pfpfpc a[N]; Â Â Â Â Â Â Â /* array of... */

   3. Use the cdecl program, which turns English into C and vice
   versa:

       cdecl> declare a as array of pointer to function returning


           pointer to function returning pointer to char
       char *(*(*a[])())()

ÂÂÂ cdecl can also explain complicated declarations, help with


ÂÂÂ casts, and indicate which set of parentheses the arguments
ÂÂÂ go in (for complicated function definitions, like the one
ÂÂÂ above).
ÂÂÂ Any good book on C should explain how to read these complicated
ÂÂÂ C declarations "inside out" to understand them ("declaration
ÂÂÂ mimics use").
ÂÂÂ The pointer-to-function declarations in the examples above have
ÂÂÂ not included parameter type information. When the parameters
ÂÂÂ have complicated types, declarations can *really* get messy.
ÂÂÂ (Modern versions of cdecl can help here, too.)

10. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to
intergers.
   Write the way to initialize the 2nd element to 10.

11. In the above question an array of pointers is declared.


   Write the statement to initialize the 3rd element of the 2 element to 10;

12.
int f()
void main()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf("%d %d %d",i,j,k);
}

What are the number of syntax errors in the above?

Ans: None.

13.
void main()
{
int i=7;
printf("%d",i++*i++);
}

Ans: 56

14.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");

Ans: "one is defined"

15.
void main()
{
int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20

16. There was question in c working only on unix machine with pattern matching.

14. what is alloca()


Ans : It allocates and frees memory after use/after getting out of scope

17.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}

Ans: 321

18.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}

Ans: anything is good.

19.
void main()
{
char *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}
Ans: "harma" (p->add(dharma) && (*p)->harma)
"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
20. Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf("%d,",i);
}
}
a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error
Ans. (d)
21. What is the ouptut in the following program
main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(c
printf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(i
printf("pass2");
else
printf("Fail2")
}
a) Pass1,Pass2
b) Pass1,Fail2
c) Fail1,Pass2
d) Fail1,Fail2
e) None of these
Ans. (c)
22. What will the following program do?
void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
23. In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}
a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT
Ans. (a)
24. What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
a) The string is : string
b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Ans. (b)
25. Find the output for the following C program
main()
{
char *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}

Você também pode gostar