Cracking The C++ Programming Skills - IT Job Interview Series

Download as pdf or txt
Download as pdf or txt
You are on page 1of 627

IK IT Job Interview Series

Cracking the
C++ Programming Skills
Dr Shriram K Vasudevan
Assistant Professor (Selection Grade)
Dept. of Computer Science and Engineering
Amrita School of Engineering, Amrita University
Coimbatore, Tamil Nadu, India

Sundaram RMD
Software Architect
Wipro Technologies
Bengaluru, India

Abhishek S Nagarajan
Dept. of Computer Science and Engineering
Amrita School of Engineering, Amrita University
Coimbatore, Tamil Nadu, India

Subashri V
Senior Developer
MNC, Coimbatore
Published by
I.K. International Publishing House Pvt. Ltd.
S-25, Green Park Extension
Uphaar Cinema Market
New Delhi–110 016 (India)
E-mail: [email protected]
Website: www.ikbooks.com

ISBN 978-93-85909-38-2

© 2017 I.K. International Publishing House Pvt. Ltd.

All rights reserved. No part of this publication may be


reproduced, stored in a retrieval system, or transmitted in any
form or any means: electronic, mechanical, photocopying,
recording, or otherwise, without the prior written permission
from the publisher.

Published by Krishan Makhijani for I.K. International


Publishing House Pvt. Ltd., S-25, Green Park Extension,
Uphaar Cinema Market, New Delhi–110 016 and Printed by
Rekha Printers Pvt. Ltd., Okhla Industrial Area, Phase II, New
Delhi–110 020.
Preface
Are You at Crossroads?
Are you tired of getting IT interviews but not offers? Are you
confused between preparing for the different competitive
exams? Are you dazed of the competition seen in the computer
market? Are you feeling fuzzy about the future in the
programming world? Are you desperate for a better software
job, but can’t figure out what that is or how to get there?
If you are under the awe of even any one of the above
questions then you have perhaps taken the right decision — of
buying this book and preparing for the technical interview! I
suggest that you consume the contents from the first chapter to
the end, sequentially, and not attempt to skip any section or
chapter unless you are confident of the topic that you would
want to skip. This is because, this book has been specifically
designed to orient you for the technical interview vis-à-vis the
C++ programming language. This book has been prepared
with a definite purpose. Please stay with the preface and read it
to the end to understand why. After reading the preface you
will most likely revise your prep strategy.
IT Job Landscape
You should take heart if you see the plethora of job openings,
and which is growing, in the IT and ITeS space. The scenario
looks like this: NASSCOM, the premier trade body for the IT-
BPM sector in India has given a press release that the Indian
IT-BPM sector continues to be one of the largest employers in
the country — directly employing nearly 3.5 million
professionals, adding over 2,30,000 employees. They have
also predicted that the future looks promising as the IT-BPM
industry is gearing itself well to next phase of challenges.
Digitization, disruptive technologies and innovation will fuel
growth with new opportunities in the years ahead. They have
also projected that the Indian IT industry would grow to about
$300 billion by 2020, and create different verticals that would
focus on specific areas such as the domestic IT market,
software products and e-commerce which tells us there are and
there will be more job openings in the IT sector.
Recruiter’s Perspective
As a potential job hunter, your chances of success increases
manifold if you understand what your recruiters are looking at.
According to a new career builder survey, overwhelming
majority of IT companies say soft skills such as a positive
attitude are just as important as hard skills. Positivity comes
from within when you are confident on your subjects. The top
10 traits employers seek out in candidates include
hardworking, dependable, positive, self-motivated, team-
oriented, organized, works well under pressure, effective
communication, flexible and confident. If all of these can boil
down into one thing, then it is subject matter expertise which
will help you attain rest of all the things.
Technical Interview Process
Recruitment refers to the process of attracting, selecting and
appointing suitable candidates for jobs within an organization.
From the organization perspective, this includes job analysis,
sourcing, screening and finally selection. Though every
company differs in its own way of selecting the candidates,
every company strives towards getting the “right” person for
the “right” job.
In a technical interview, applicants are likely to be asked
questions that:
• relate to specific skill set that is needed for the company’s
technical activities;
• relate to the basics on the subject matter to resolve complex
problems;
• for rookies, it will be related to the projects completed as
part of a degree course; and
• require candidates to solve actual technical problems that
they would be likely to face if employed.
One of the articles by Forbes, an American business
magazine, talks about four super-common interview questions
post-technical interview session which includes “tell me about
yourself”, “what is your greatest strengths”, “why should we
hire you” and “do you have any questions for us”. Though
these are very common questions, giving unexpected and most
relevant answers will make the interviewer sit up faster and
listen to you.
Your Personal SWOT
Now that you know your dream job is beckoning you (your
opportunity) that you need to outpace only X competitors
(your threats), what the recruiters would be looking at while
interviewing, make sure you list down your areas of strength,
and more importantly weakness. While you would have little
control over the opportunities and threats, you can fully devote
yourself to take your strengths to newer heights and work on
your weaknesses to prevail upon them. Use the SWOT grid
given below for planning your prep.

Why C++?
It has been seen that X% of all the technical interviews have
the C++ programming language at heart. C++ Programming
can be used to do tasks such as networking related, OS related,
embedded systems related, etc. It is used for developing
computer applications, embedded software network drivers,
data bases, simulators, etc. Moreover, it is believed that if you
are strong in a programming language like C++, you can be
easily trained on multiple different languages that are derived
based on object orientation. Knowledge of specific
technologies along with experience and knowledge of
methodologies is more important. Continuously practicing
C++ objective type questions will help you attain that state.
Why this Book?
As I have mentioned in the preface, this book has been
specifically designed to help you undertake a meticulous and
objective prep.
The contents have been carefully handpicked from our
experience and expertise developed by being either direct
witness to the recruitment process, mentoring students in our
colleges, myriad discussion with our peers who are placement
organizers in colleges, hours of studying discussions on the
topics in social media, blogs and dedicated websites, so that
the book is highly focused to the interview prep for the C++
language and almost nothing else. We have come to the
conclusion that for effective prep everything boils down to
multiple choice questions around coding problems along with
frequently asked technical, conceptual questions. Anyone
wishing to sharpen his skills on C++ programming language or
preparing for aptitude tests, competitive examinations should
thorough this book which will help them get the goals.
We have combined our technical expertise to develop
multiple choice questions that help you strengthen your
weaknesses. For this, we thought that the best way is to grade
the problems into level of difficulties (LODs). The complexity
of the questions have been incremented with more technical
challenge from L1 to L5. L1 has the minimal complexity
which would test the basics like syntaxes wherein L5 will test
your understanding of the logic and code in depth with
concepts. Each chapter has complexities distributed evenly
with focus being given at all levels of difficulty.
1. L1: Tests the basic syntactical knowhow of the
language.
2. L2: First level testing on the reader’s understanding of
the language is carried out in L2 questions. With basic
knowhow getting cleared one can attempt L2.
3. L3: Questions are aimed at testing the logical
perspective of the reader.
4. L4: It mostly points out of the point of occurrence of
errors and the exact error statements and its reasons.
5. L5: Tricky questions are added under this belt to test
your understanding.
What is this Book All About?
C++ programming questions and answers have been aimed
with a distinct purpose of assisting students and specialists
getting ready for several certification exams and job
interviews. This book provides a useful collection of sample
interview questions and multiple-choice questions and their
answers with appropriate explanations. Let’s get started with
the preface section! These C++ programming interview
questions and answers have been intended to get you familiar
with the nature of questions you may face during your C++
programming interview and written examinations.
This book was engraved with two groups of readers in mind.
One who is new to C++ and wants to learn the basics of it
through objective type questions, or the other group who
wanted to master their skills in cracking the interviews. We
hope that you will find what follows. LOD (levels of
difficulty) will enable the readers to move step-by-step testing
his understanding.
This book reflects the growing complexity with which
interviewing is being loomed and we have included the latest
topics and questions discussed in top companies today while
continuing to maintain the emphasis on basic problem solving
skills for both students preparing for exams and for
interviewees. We made this publication more student-friendly
by eradicating redundant words, materials, and dated models,
presenting detailed descriptions, providing fewer lists, and
using bold print to call attention to important terms.
Coverage of the Book
C++ is a considered an enhancement of C language. Chapter 1
is fully concerned about the differences between the C and
C++. It deals with the major changes in characteristics of the
language.
Object oriented programming is fully relied on classes.
Chapter 2 travels the nooks and corners of classes. It throws
light on various types of classes, the internal structure and
their usage. This chapter also explains the main concept of
OOP, ‘ENCAPSULATION’ in detail. This will make you
strong in appropriate usage of OOP.
Objects or instances are classes that have specific attributes.
Every time an object is created, all the members of the class
belonging to the object will be initialized. Also, when the
scope of the object is over it will be cleared and the memory
will be released. This internal task of allocating and de-
allocating the memory of an object is done by constructors and
destructors. Chapter 3 discusses the working of constructor
and destructor and their power of it. It discusses the various
forms and modes of usage in detail.
C++ has a special feature of changing the storage properties
of variables. This is done using storage classes. Chapter 4
introduces you the various storage classes and their usage. It
also explains the possibilities of using storage classes in class
members, thus educating you in linking storage classes with
OOP.
A good programmer must always be concerned about the
usage of resources. Mainly professionals should be concerned
about the amount of memory used in the program. There
should be any unused memory logs. So, Dynamic Memory
Allocation (DMA) is used. It helps in dynamically allocating,
reallocating and releasing the memory. Chapter 5 elaborates
the usage of DMA in programming thus enhancing your
professional skills.
An important and very powerful OOP feature is inheritance.
It is gaining features from base class to derived class. It is
powerful mainly because of its ability to reuse the code.
Chapter 6 describes their usage and various possibilities of
inheritance.
Polymorphism is yet another important concept of OOP. It
gives multiple forms to an attribute or functionality. Operator
overloading is adding new features to existing operators.
Chapter 7 shows the whole picture of operator overloading
screening its powers and abilities.
Giving multiple definitions to same function increases the
functionality. This is function overloading. Also if the new
definition is in inherited classes it is function overriding.
These two concepts will help in increasing the utility of the
code making it more professional. Chapter 8 drives across the
concepts of function overloading and overriding.
Private members of a class can be accessed only by its friend
class and friend functions. Chapter 9 carries you into the topics
of friend class and friend function thereby enhancing your
understanding in cracking related questions.
Ambiguity in a multi-user scenario is quite frequent. Often a
programmer encounters collision in memory making the
program inefficient. Namespace is a brilliant feature in C++
that avoids this ambiguity and increases efficiency of the
program. Chapter 10 is a unique introduction to namespace
where one can understand the scenarios where namespaces can
be used.
Yet another interesting and user-friendly feature of C++ is
templates. In a nutshell it is a program independent of data
types. Chapter 11 takes you across the usage of templates and
making you use the best of features available in C++.
Errors are always a backdrop in programming. It challenges
the programmer in continuing with execution. A way to handle
and by-pass the errors for further compilation is Exception
Handling. It helps in making the code more robust. Chapter 12
increases your professional skills by making you handle any
type of exception.
The coding techniques can be applied to external data in
files. Also, the output can be kept track using external files.
Chapter 13 introduces file usage and helps you to make use of
the feature increasing the robustness of the code.
Macros are defined expressions that increase readability of
code. Chapter 14 screens the magic performed by macros and
inspires you to use it in your code.
As a part of the interview process questioning are conceptual
and theoretical from OOP along with codes of C++. Chapter
15 is designed to make you strong in all the concepts
explained in the book.
BREAK UP OF QUESTIONS — CHAPTER WISE

NUMBER OF
CHAPTER DETAILS
QUESTIONS
1 C vs C++ 55

2 CLASSES 140

3 CONSTRUCTORS AND DESTRUCTORS 60

4 STORAGE CLASS 80

5 DYNAMIC MEMORY ALLOCATION 30

6 INHERITANCE 110

7 OPERATOR OVERLOADING 40

FUNCTION OVERLOADING AND


8 87
OVERRIDING

FRINED CLASS AND FRINED


9 14
FUNCTIONS

10 NAMESPACES 11

11 TEMPLATES 13

12 EXCEPTION HANDLING 40

13 FILES 35

14 MACROS AND INCLUDE DIRECTIVES 31

15 CONCEPTUAL THEORY 161

TOTAL 907

Success Story of C
There are quite a lot of programming languages available,
starting from the extremely high level language to the low
level power of assembly language, and a good variety of
specialized options in between them. C language stands out
among them. Whereas C++ stands above C. This is mainly
because of the abilities of OOP.
C++ programming language has a lot of advantages along
with most of the advantages of C. First, C++ has been around
for the past two decades with tons of source codes available
over the Internet which gives lot of information to learn and
use. It’s a great language for expressing ideas in a way that
most people can understand and where it can be compared
with real world environment. Moreover, other than OOP the
special features like namespace and templates makes the
program robust thus making the language preferable to the
target group.
Other Benefits of this Book
Though many books are available in the market on C++
programming language, most of them are theoretical in nature
or programming examples. There are not many books that
have a series of C++ problems that can be used to build the
programming skills. Many people understand the basics,
syntax and semantics but only an objective type book can help
hone the skills.
It’s quite frustrating that no book in print came even close to
adequately covering all different topics in C++ programming
language with so many possible objective questions and we
are happy that this book covers all aspects for a programmer to
succeed in interviews as well learn the nuances of
programming. Not only programming, but also all the
technical.
Who Else will Find this Book Useful?
Apart from technical interview prep, this book can be gainfully
used by developers, software engineers, and aspirants of other
competitive examinations like GATE, IES, etc.
A good software engineer should have a basic level of
comfort in coding and problem solving – that is, be able to
comprehend code and write something nontrivial – in these
languages:
• C++, for a good familiarity with systems programming and
how the whole software stack works.
• Object-oriented and common programming features, while
also providing facilities for low-level memory
manipulation.
A modern day programmer is expected to be proficient in
C++ programming language and is most wanted for the below:
• Consumer electronics and embedded systems industries
need programs to be implemented in C++, that include
kernel code, device drivers or other low level
programming.
• Even companies developing applications will require some
parts to be implemented in C++ for the purpose of
optimization and performance improvement.
• Firmware code is written using C++ for various
electronics, industrial and communications products which
use micro controllers as CPU.
• Also needed in companies that develops verification and
validation softwares, simulators, test code, etc., for various
kinds of applications.
• Since it produces code that runs as fast as an assembly
code, it is most preferred by companies developing
operating systems, network drivers, text editors, data bases
and in utilities.
Competitive examinations after graduation also require C++
programming if you are in the computer science and
information technology streams. This includes but not limited
to:
• GATE: To score a good rank, you must practise the full
syllabus as prescribed from year to year and C++
programming and problem solving skill carries more
weightage in it.
• IES – Indian Engineering Services also has questions from
C programming covering basics in C++;
• Now various PSU’s like: IOCL, NTPC, CONCOR, GAIL,
BPCL, HP, CL, BHEL, PGCIL, BEL, DDA, etc.,
companies consider GATE SCORE for recruitment. They
are also conducting their own written exams for
recruitment that includes questions from C++
programming.
• Many other competitive examinations conducted both
within and outside the country test the basic programming
skills if you are in the information technology domain.
With these words, we are signing off. Wish you all the best in
your career! Have a happy learning experience!
Dr Shriram K Vasudevan
Sundaram RMD
Abhishek S Nagarajan
Subashri V
Contents
Preface
1. C Versus C++
2. Classes
3. Constructors and Destructors
4. Storage Class
5. Dynamic Memory Allocation
6. Inheritance
7. Operator Overloading
8. Function Overloading and Overriding
9. Friend Class and Friend Functions
10. Namespaces
11. Templates
12. Exception Handling
13. Files
14. Macros and Include Directives
15. Conceptual Theory
1
C VERSUS C++
This chapter will cite the most important differences between
C and C++. It is also to be noted that ‘C’ language is top
down language whereas ‘C++’ is a bottom up one. At the end
of this chapter, you will be knowing the important and
elementary vicissitudes to be handled carefully while moving
into C++ from C language.

1. What is the output of the code? (L2)


#inlcude<iostream.h>
void main()
{ cout<< “hello world”;}
(a) hello world
(b) hello
(c) Unpredictable
(d) Compiler dependent
Answer: (d) ‘cout’ is the function used for printing output in
‘C++’. The operator ‘<<’ is called extraction operator. It is
used for extracting the value from the right side, and gives it to
the console. In ‘g++’ it gives errors. Whereas in other
compilers and some older versions it might give ‘hello world’.

2. What will be error thrown by the code? (L4)


#inlcude<iostream.h>
void main()
{ cout<< “hello world”;}
(a) Fatal error: iostream.h: no such file or directory
(b) ‘::main()’ must return ‘int’
(c) ‘cout’ was not declared in this scope
(d) All of the above
Answer: (a) A fatal error terminates compilation. Then no
other errors will be thrown. This is because ‘g++’ doesn’t
support this way of compilation.

3. What will be error thrown by the code? (L3)


#inlcude<iostream>
using namespace std;
void main()
{ cout<< “hello world”;}
(a) Fatal error: iostream.h: no such file or directory
(b) ‘::main()’ must return ‘int’
(c) ‘cout’ was not declared in this scope
(d) No error
Answer: (b) ‘using namespace std’ is for handling naming
collisions and adding external files and definition. This doesn’t
exist in ‘C’. It is used to prevent collisions while naming
memory spaces. Initially, it was used only on system with
multiple users and shared memory, but now it has been
adapted as a mandatory syntax in ‘G++’. Also in ‘G++’ the
default ‘main’ must be of ‘int’ type and not ‘void’. Thus, the
error. But it is also to be noted that the compiler doesn’t throw
any error or warning even if there is no return statement given
at the end of ‘main’.

4. What will be error thrown by the code? (L4)


#inlcude<iostream>
int main()
{ std::cout<< “hello world”;}
(a) hello world
(b) Error
(c) Unpredictable

(d) Fatal error


Answer: (a) This is an alternative way for ‘using namespace
std’. But it is not preferred for long codes.

5. What is the output of the code? (without header file and


‘using namespace std’) (L3)
int main()
{ cout<< “hello world”;}
(a) hello world
(b) Error
(c) Unpredictable
(d) Fatal error
Answer: (b) ‘cout’ was not declared in this scope. Unlike ‘C’
in ‘C++’ you cannot compile a code without the header file.

6. What will be the error thrown by the code? (without header


file) (L3)
using namespace std;
int main()
{ cout<< “hello world”;}
(a) ‘cout’ was not declared in this scope
(b) Fatal error: missing ‘main’
(c) Logical error: ‘std’ used without a file or directory
(d) None of the above
Answer: (a) ‘cout’ is defined inside the header file only so it
throws error.

7. What will be the error thrown by the code? (L2)


#include<iostream.h>
using namespace std;
int main()
{ cout<< “hello world”;}
(a) ‘cout’ was not declared in this scope
(b) Fatal error: iostrem.h: No such file or directory.
(c) Both ‘a’ and ‘b’
(d) No error
Answer: (b) The usage of ‘.h’ for ‘iostream’ is not
implemented in ‘G++’.

8. What is the output of the code? (L3)


#include<iostream>
#include<math.h>
using namespace std;
int main()
{ cout<< sqrt(9);}
(a) 3
(b) Error
(c) Unpredictable
(d) Fatal error
Answer: (a) for other header file ‘.h’. ‘sqrt’ is the inbuilt
function that returns the square root of the given number.

9. What is the output of the code? (L3)


#include<iostream>
#include<math>
using namespace std;
int main()
{ cout<< sqrt(9);}
(a) 3
(b) Error
(c) Unpredictable
(d) Fatal error
Answer: (d) math: No such file or directory.

10. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ std::cout<< “hi”;}
(a) hi
(b) Error
(c) Unpredictable
(d) Segmentation fault
Answer: (a) This works normally.

11. What is the output of the code? (L1)


#include<iostream>
using namespace std
int main()
{ cout<< “hi”;}
(a) hi
(b) Error
(c) Unpredictable
(d) Segmentation fault
Answer: (b) Expected ‘;’ before ‘int’. Like ‘C’‘;’ is
mandatory in every single statement.

12. What is the output of the code? (L2)


#include<iostream>
using namespace std
int main()
{ std::cout<< “hi”;}
(a) hi
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) The additional ‘std’ doesn’t take care of the
missing ‘;’ in declaration.

13. What is the output of the code? (L1)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<< “hi ”<<a; }
(a) hi 9
(b) hi
(c) Error
(d) None of the above
Answer: (a) ‘cout’ can print multiple values of different types
simultaneously.

14. What is the output of the code? (L1)


#include<iostream>
using namespace std;
int main()
{ cout<< “hi ”<<9; }
(a) hi 9
(b) hi
(c) Error
(d) None of the above
Answer: (a) This also works normally.

15. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<< “hi ”<< “%d”,a; }
(a) hi 9
(b) hi
(c) Error
(d) None of the above
Answer: (d) “%d” is treated as a string. So the output will be
“hi %d”. The concept of format specifiers are completely
dropped in C++. The default ‘cout’ operator can handle
variables and values of any data type.

16. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<< “hi ”<< (“%d”,a); }
(a) hi %d
(b) hi
(c) Error
(d) None of the above
Answer: (d) The output will be “hi 9”. Here, the ‘,’ in
between overwrites “%d” by ‘a’. This is same as in ‘C’.

17. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int main()
{ cout<< 9,8,7,6; }
(a) 9
(b) 9876
(c) 6
(d) Error
Answer: (a) For every single variable and value the extraction
operator is required. This is called cascading operators.

18. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<< a++<<a++<<a++; }
(a) 91011
(b) 11109
(c) 999
(d) 111111
Answer: (b) The associativity of the operator is from right to
left.

19. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<< ++a<<++a<<++a; }
(a) 111111
(b) 121212
(c) 11109
(d) 101011
Answer: (b) This result is because the prefix increment will
point to the value in the each usage. Whereas in postfix
increment the temporary value alone will be stored and not the
pointer to the value is used.

20. What is the output of the code? (L3)


#include<iostream>
#include<math.h>
using namespace std;
int main()
{ cout<< sqrt(9)<< “ ”<<sqrt(5); }
(a) 3 2.23607
(b) 3 2
(c) 3.000000 2.23607
(d) None of the above
Answer: (a) The cout handles each value according to its
value.

21. What is the output of the code? (assume the value given
for ‘a’ is 2) (L1)
#include<iostream>
using namespace std;
int main()
{ int a;
cin>>a;
cout<< a; }
(a) 2
(b) 2.000000
(c) Unpredictable
(d) None of the above
Answer: (a) ‘cin’ is the input stream operator. It gets the value
from the console and gives it to appropriate variables. The
“>>” is called insertion operator, that facilitates the flow of
data from the operator on the left to the operand on the right.

22. What is the output of the code? (assume the values given
are 2,3,4) (L2)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a>>b>>c;
cout<< a<< “ ”<< “ ”<<b<< “ ”<<c; }
(a) 2 3 4
(b) 4 3 2
(c) Unpredictable
(d) None of the above
Answer: (a) This is called cascading insertion operator. Here
also the associativity is from left to right only.

23. What is the output of the code? (assume the values given
are 2,3,4) (L2)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a>>b>>c;
cout<< a;
cout<< b;
cout<< c; }
(a) 234
(b) 2 3 4 (in consecutive lines)
(c) Unpredictable
(d) None of the above
Answer: (a) Unless new line is specified the output will not be
taken to the next line.

24. What is the output of the code? (assume the values given
are 2,3,4.34) (L2)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a>>b>>c;
cout<< a;
cout<< b;
cout<< c; }
(a) 234
(b) 230
(c) Unpredictable
(d) None of the above
Answer: (a) When data of different types is given, it internally
converts it into the required type and saves it.

25. What is the output of the code? (assume the values given
are 2.23,3,4.34) (L3)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a>>b>>c;
cout<< a;
cout<< b;
cout<< c; }
(a) 234
(b) 230
(c) Unpredictable
(d) None of the above
Answer: (d) 200 is the output. ‘cin’ stops reading the value
when it encounters a mismatch in type.
26. What is the output of the code? (assume the values given
are 2.23,3,4.34) (L3)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a;
cin>>b;
cin>>c;
cout<< a;
cout<< b;
cout<< c; }
(a) 200
(b) 234
(c) Unpredictable
(d) None of the above
Answer: (a) This also works in the same way. When one ‘cin’
fails all the others are skipped.

27. What is the output of the code? (assume the values given
are 2.23,3,4.34) (L3)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a;
cin>>b;
cin>>c;
cout<< int(a);
cout<< b;
cout<< int(c); }
(a) 200
(b) 234
(c) Unpredictable
(d) None of the above
Answer: (a) This also works the same as above. But the
conversion has no issues, it is all the same as ‘C’.

28. What is the output of the code? (assume the values given
are 2.23,3,4.34) (L4)
#include<iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>int(a);
cin>>b;
cin>>int(c);
cout<< a;
cout<< b;
cout<< c; }
(a) 200
(b) 234
(c) Unpredictable
(d) None of the above
Answer: (d) This gives error. “Ambiguous overload for
‘operator>>’”. It gives a long description of the internal
definition of the operator and the possible overloading of it.
Overloading is a concept of object oriented programing which
means giving multiple definitions for an operator based on
usage.
29. What is the output of the code? (L4)
#include<iostream>
using namespace std;
int main()
{ cin>>9;
cout<< 9; }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This gives the same error. “Ambiguous overload
for ‘operator>>’” along with the description. It just says that
the usage of the operand is wrong and also suggests the
various possible ways.

30. What is the output of the code? (assume the value given
for ‘a’ is 3) (L3)
#include<iostream>
using namespace std;
int main()
{ int a;
cin<<a;
cout<< a; }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This gives the error. “No match for ‘operator<<’
(operand types are ‘std::istream {aka
std::basic_istream<char>}’ and ‘int’)” along with a
description. This means, “<<” operator has no possible usages
with ‘cin’.

31. What is the output of the code? (L1)


#include<iostream>
using namespace std;
int main()
{ int a=9,b=0;
cout<< a<<endl<<b; }
(a) 90
(b) 9 0
(c) 9 0 (in consecutive lines)
(d) None of the above
Answer: (c) “endl” is used to specify new line in C++.

32. What is the output of the code? (L1)


#include<iostream>
using namespace std;
int main()
{ int a=9,b=0;
cout<< a<< “\n”<<b; }
(a) 9 0(in consecutive lines)
(b) 9\n0
(c) Error
(d) None of the above
Answer: (a) This works normally. But “endl” is a new syntax
introduced for C++.
33. What is the output of the code? (L3)
#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b=a;
cout<< a<< “ ”<<b; }
(a) 9 9
(b) 9 0
(c) Error
(d) None of the above
Answer: (a) The variable ‘&b’ is called reference variable,
which is specific to C++. It is a way similar to pointers. But
still has some major differences. So both reference variables
and pointers exist in C++. Here ‘b’ points to value of ‘a’.
Reference variable means giving multiple names for same
memory location.

34. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b=0;
cout<< a<< “ ”<<b; }
(a) 9 9
(b) 0 0
(c) Error
(d) None of the above
Answer: (c) Unlike pointers, reference variables cannot be
initialised to 0.

35. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b=0;
cout<< a<< “ ”<<b; }
(a) Mismatch of reference variable
(b) invalid initialization of reference type
(c) Reference type cannot be initialized to 0
(d) None of the above
Answer: (d) “Invalid initialization of non-const reference of
type ‘int&’ from an rvalue of type ‘int’.” It is also to be noted
that ‘rvalue’ is used in error statement which was not used in
‘C’.

36. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b=NULL;
cout<< a<< “ ”<<b; }
(a) 9 9
(b) 0 0
(c) Error
(d) None of the above
Answer: (c) Unlike pointers, reference variables cannot be
initialised to NULL.

37. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b;
&b=a;
cout<< a<< “ ”<<b; }
(a) 9 9
(b) 9 0
(c) Error
(d) None of the above
Answer: (c) Reference variables should be declared and
initialised in the same statement. They cannot be initialised
later.

38. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int& b;
&b=a;
cout<< a<< “ ”<<b; }
(a) ‘b’ declared as reference but not initialized
(b) Lvalue required as left operand of assignment
(c) Both ‘a)’ and ‘b)’
(d) None of the above
Answer: (c) Separate usage of reference operator is not legal
in C++.

39. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int b=a<<2;
cout<<b; }
(a) 2
(b) 162
(c) 36
(d) Error
Answer: (c) “<<” is shift left for numbers. ‘a<<n’ means shift
the bits of ‘a’ to left by n bits. This is equal to multiplication
by 2 power n. Hence, here it is 36 (9 × 4).

40. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
int b=a>>2;
cout<<b; }
(a) 2
(b) 2.5
(c) 2.25
(d) Error
Answer: (a) “>>” is shift right for numbers. ‘a>>n’ means
shift the bits of ‘a’ to right by n bits. This is equivalent to
division by 2 power n. Here, 9/2 = 4 and 4/2 gives 2 as the
final output.

41. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<<a<<2; }
(a) 92
(b) 36
(c) Error
(d) Unpredictable
Answer: (a) Here the ‘<<’ in between ‘a’ and 2 gets
associated with the ‘cout’. This shows that cout maintains
priority over ‘<<’.

42. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int a=9;
cout<<(a<<2); }
(a) 92
(b) 36
(c) Error
(d) Unpredictable
Answer: (b) The parenthesis changes the associativity.

43. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int a=3;
int main()
{ int a=9;
cout<<::a; }
(a) 3
(b) 9
(c) Error
(d) Unpredictable
Answer: (a) The operator ‘::’ is called scope resolution
operator. It is used to access the global variable even if there is
a local variable of the same name.

44. What is the output of the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<t.rate;
t.bonus(); }
(a) 9
(b) 9festival
(c) Error
(d) Unpredictable
Answer: (b) Unlike ‘C’ Structure in C++ can have functions.

45. What is the output of the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
float f;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<sizeof(t); }
(a) 4
(b) 8
(c) Error
(d) Unpredictable
Answer: (b) Functions do not consume any memory
allocation of structure and union is similar to ‘C’.

46. What is the output of the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
struct bun
{ int temp; };
}t;
int main()
{ t.rate=9;
struct bun b;
b.temp = 98;
cout<<b.temp; }
(a) 98
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) structures inside another structure do not get
global scope in C++.

47. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
struct bun
{ int temp; };
}t;
int main()
{ t.rate=9;
struct bun b;
b.temp = 98;
cout<<b.temp; }
(a) Incomplete type ‘struct bun’
(b) Unknown type ‘struct bun’
(c) Aggregate ‘main()::bun b’ has incomplete type and
cannot be defined
(d) None of the above
Answer: (c) Unlike ‘C’ it handles it differently.

48. What is the output of the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
struct bun
{ int temp; };
struct bun b;
}t;
int main()
{ t.rate=9;
b.temp = 98;
cout<<b.temp; }
(a) 98
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) The object of inner struct is treated as a member
of the outer struct.
49. What will be the error thrown by the code? (L3)
#include<iostream>
using namespace std;
struct tea
{ int rate;
struct bun
{ int temp; };
struct bun b;
}t;
int main()
{ t.rate=9;
b.temp = 98;
cout<<b.temp; }
(a) ‘b’ not declared
(b) Unknown type ‘b’
(c) ‘b’ has no member ‘temp’
(d) ‘b’ was not declared in this scope
Answer: (d) ‘b’ is member of ‘tea’

50. What is the output of the code? (L3)


#include<iostream>
using namespace std;
struct tea
{ int rate;
struct bun
{ int temp; };
struct bun b;
}t;
int main()
{ t.b.temp = 98;
cout<<t.b.temp; }
(a) 98
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) This is the most apt way of accessing members. It
is also to be noted that all these changes are applicable to the
‘union’ also in C++.

51. What is the output of the code? (L3)


#include<iostream>
using namespace std;
union tea
{ int rate;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<t.rate;
t.bonus(); }
(a) 9
(b) 9festival
(c) Error
(d) Unpredictable
Answer: (b) Unlike ‘C’ Union in C++ can have functions.
52. What is the output of the code? (L3)
#include<iostream>
using namespace std;
union tea
{ int rate;
float f;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<sizeof(t); }
(a) 4
(b) 8
(c) Error
(d) Unpredictable
Answer: (a) Memory allocation to union is similar to C++.

53. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class tea
{ int rate;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<t.rate;
t.bonus(); }
(a) 9
(b) 9festival
(c) Error
(d) Unpredictable
Answer: (c) ‘class’ is the most advantageous new concept of
‘C++’. This forms the basis for Object Oriented Programming.
But this gives errors because by default all the variables and
functions are treated as ‘private’ variables. These are access
specifiers associating data. This will be discussed elaborately
in the upcoming chapters.

54. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class tea
{ public:
int rate;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<t.rate;
t.bonus(); }
(a) 9
(b) 9festival
(c) Error
(d) Unpredictable
Answer: (b) This works normally. Only ‘public’ data will be
accessible by the objects.

55. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class tea
{ public:
int rate;
void bonus()
{ cout<<”festival”; }
}t;
int main()
{ t.rate=9;
cout<<sizeof(t); }
(a) 8
(b) 4
(c) 12
(d) Unpredictable
Answer: (a) This is similar to size of a structure. It will
consider all the variables under all the access specifiers.
2
CLASSES
This chapter takes you across the nooks and corners of
classes. This concept is the primary necessity for Object
Oriented Programming. After going through this chapter you
will be able to handle classes, objects and any related
concepts easily.

1. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ public:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9;
S.percent(); }
(a) 90
(b) 9
(c) Error
(d) Unpredictable
Answer: (a) ‘S’ is the object / instance of the class. It can
access the ‘public’ members of the class. ‘public’ is the access
specifier. Classes have two more specifiers ‘private’ and
‘protected’. The variables are called ‘data members’ and the
functions are called ‘member functions’.
2. What is the output of the code? (L1)
#include<iostream>
using namespace std;
class student
{ private:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9;
S.percent(); }
(a) 90
(b) 9
(c) Error
(d) Unpredictable
Answer: (c) ‘private’ access specifier means the data that is to
be hidden from other unrelated info and user. Trying to access
‘private’ data and methods throws errors. It is accessible only
by the members of the class and not even the objects.

3. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class student
{ private:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9; }
(a) ‘int student::marks’ is private
(b) within this context S.marks=9;
(c) ‘student::marks’ not defined
(d) Both ‘a’ and ‘b’
(e) Both ‘d’ and ‘b’
Answer: (d) The compiler knows that the member is private.

4. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ protected:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9;
S.percent(); }
(a) 90
(b) 9
(c) Error
(d) Unpredictable
Answer: (c) ‘protected’ access specifier means the data that is
to be hidden from other unrelated info. Trying to access
‘protected’ data and methods throws errors. It is accessible
only by the members of the class and inherited class (will be
dealt with in later chapter).

5. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class student
{ protected:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9; }
(a) ‘int student::marks’ is protected
(b) within this context S.marks=9;
(c) ‘student::marks’ not defined
(d) Both ‘a’ and ‘b’
(e) Both ‘d’ and ‘b’
Answer: (d) The compiler knows that the member is
protected.

6. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ public:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ S.marks=9;
cout<<sizeof(S); }
(a) 4
(b) 8
(c) 6
(d) None of the above
Answer: (a) Only member variables will be allocated
memory.
7. What is the output of the code? (L2)
#include<iostream>
using namespace std;
class student
{ public:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ cout<<sizeof(S); }
(a) 4
(b) 0
(c) Unpredictable
(d) None of the above
Answer: (a) Members need not be initialised, memory is
allocated once the variable is created.
8. What is the output of the code? (L2)
#include<iostream>
using namespace std;
class student
{ int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ cout<<sizeof(S); }
(a) 4
(b) 0
(c) Unpredictable
(d) None of the above
Answer: (a) Even though the members are not accessible by
the object, each object will have a specific value of the
variable. So it will be allocated.

9. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ protected:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ cout<<sizeof(S); }
(a) 4
(b) 0
(c) Unpredictable
(d) None of the above
Answer: (a) The same here.

10. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ char section;
public:
int marks;
void percent()
{ cout<< marks*10; }
}S;
int main()
{ cout<<sizeof(S); }
(a) 4
(b) 5
(c) Unpredictable
(d) None of the above
Answer: (b) This works normally.

11. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ public:
int marks;
char section;
}S;
int main()
{ S.marks=8;
S.section = ‘a’;
cout<<S.marks<< “ ”<<S.section; }
(a) 8 a
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Unnecessary blank lines within the ‘class’
doesn’t change the specifiers to default (‘private’).

12. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ public:
int marks;
private:
char section;
}S;
int main()
{ S.marks=8;
S.section = ‘a’;
cout<<S.marks<< “ ”<<S.section; }
(a) 8 a
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This works exactly as expected.

13. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int marks;
private:
int m;
public:
char section;
}S;
int main()
{ S.marks=8;
S.section = ‘a’;
cout<<S.marks<< “ ”<<S.section; }
(a) 8 a
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Same access specifier can be given multiple
times.

14. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ private:
int marks;
public:
int m;
private:
char section;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) This also works the same.

15. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ private:
public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) A specifier block can be empty.

16. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ private:
public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Having specifiers in continuous lines doesn’t
make them interdependent. By default it declares the first
block as empty.

17. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ private, public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not legal. But it is to be noted that still the
specifiers exist as keywords.
18. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class student
{ private, public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Expected ‘:’ before ‘,’ token in ‘private, public:’
(b) Expected unqualified-id before ‘,’ token
(c) ‘class student’ has no member named ‘m’
(d) All of the above
Answer: (d) It is to be noted that ‘c’ will be thrown twice
because it is accessed twice.
19. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class student
{ private / public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) The same happens here.

20. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ [private,public]:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) There is no way to specify multiple specifiers
together.

21. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ private:public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) This works normally as specified above.

22. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ public:
int m;
privte.int s;
}S;
int main()
{ S.s=8;
cout<<S.s; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not allowed. It gives the same error.

23. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not possible.

24. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) ‘m’ does not name a type
(b) Invalid declaration of class member ‘m’
(c) ‘class student’ has no member named ‘m’
(d) Both ‘a’ and ‘c’
(e) Both ‘b’ and ‘c’
Answer: (d) It doesn’t recognise the variable as member itself.
It treats ‘m’ as a type.

25. What is the output of the code? (L4)


#include<iostream>
using namespace std;
int m;
class student
{ public:
m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) The same repeats.

26. What is the output of the code? (L4)


#include<iostream>
using namespace std;
int m;
class student
{ public:
::m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) Global variables cannot be brought into class like
this using scope resolution operator.

27. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
int m;
class student
{ public:
::m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Using-declaration for non-member at class scope
(b) Invalid usage of ‘::’ operator
(c) ‘class student’ has no member named ‘m’
(d) Both ‘b’ and ‘c’
(e) Both ‘a’ and ‘c’
Answer: (e) Here ‘m’ is not a member of a class. So it cannot
be declared again inside the class using ‘::’ operator.

28. What will be the error thrown the code? (L4)


#include<iostream>
using namespace std;
int m;
class student
{ public:
int m;
}S;
int main()
{ S.m=8;
m=0;
cout<<S.m<< “ ”<<m; }
(a) Using-declaration for non-member at class scope
(b) Redeclaration of variable ‘m’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (d) It throws no error. It is allowed in classes. The
output will be ‘8 0’.

29. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}m;
int main()
{ m.m=8;
cout<<m.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Class object can be same as a member variable.

30. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ int m;
public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not allowed as the members will collide.

31. What will be a part of the error thrown by the code? (L3)
#include<iostream>
using namespace std;
class student
{ int m;
public:
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Redeclaration of ‘int student::m’
(b) ‘int student::m’ is private
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) Before declaring ‘m’ as public it is declared as
private.

32. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
int m;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Redeclaration of ‘int student::m’
(b) ‘int student::m’ is declared as public only
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) Redeclaration of variable inside the class is not
possible.

33. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
int ;
}S;
int main()
{ cout<<sizeof(S); }
(a) 8
(b) 4
(c) Error
(d) None of the above
Answer: (c) Type cannot be given separately inside class for
declaration.

34. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
int ;
}S;
int main()
{ cout<<sizeof(S); }
(a) Invalid declaration [-rpermissive]
(b) Declaration does not declare anything [-fpermissive]
(c) Expected expression before ‘;’
(d) None of the above
Answer: (b) Type cannot be given separately inside class for
declaration.

35. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ }S;
int student::m;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) unpredictable
(d) None of the above
Answer: (b) This declaration of members is not possible.

36. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ }S;
int student::m;
int main()
{ S.m=8;
cout<<S.m; }
(a) ‘int student::m’ is not a static member of ‘class student’
(b) ‘class student’ has no member named ‘m’
(c) Class member declared as non-static
(d) Both ‘a’ and ‘b’
(e) Both ‘b’ and ‘c’
Answer: (d) This is not allowed. This has a different meaning.
It is related with ‘static’ members of class. This will be
discussed in later chapters.

37. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
S.m;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) 0
(d) None of the above
Answer: (b) The statement ‘S.m;’ has issues.

38. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
S.m;
int main()
{ S.m=8;
cout<<S.m; }
(a) Invalid type ‘S’
(b) Useless declaration
(c) ‘S’ does not name a type
(d) None of the above
Answer: (c) Compiler treats it as a new variable declaration,
and throws errors.

39. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
int m;
int main()
{ m=0;
S.m=8;
cout<<S.m<< “ ”<<m; }
(a) 8 0
(b) Error
(c) 0 0
(d) None of the above
Answer: (a) Declaring variables after the class with member
names doesn’t affect the declaration. Only variables that are
defined outside and later declared inside class gives errors.

40. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m=9;
}S;
int main()
{ cout<<S.m; }
(a) 9
(b) Error
(c) 0
(d) None of the above
Answer: (a) It gives a warning “non-static data member
initializers only available with -std=c++11 or -std=gnu++11
[enabled by default]”. Such initialisations can be done only to
static members (that to outside the class usually). But this is
available in the newer version compilers. So it is enabled by
default. The explanation of static variables will be done in
upcoming chapters.

41. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m=9;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) 9
(c) Error
(d) 0
Answer: (a) It works normally.
42. What is the output of the code? (L1)
#include<iostream>
using namespace std;
class student
{ public:
int m;
}S,S1;
int main()
{ S.m=8;
cout<<S.m<< “ ”<<S1.m; }
(a) 8 8
(b) 8 0
(c) Error
(d) Unpredictable
Answer: (b) This is a way of creating multiple objects.

43. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ public:
int m=9;
}S,S1;
int main()
{ S.m=8;
cout<<S.m<< “ ”<<S1.m; }
(a) 8 8
(b) 8 9
(c) Error
(d) Unpredictable
Answer: (b) The object that is not initialised gets default
value.

44. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ public:
int m; };
int main()
{ student S;
S.m=8;
cout<<S.m; }
(a) 8
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) This is a way of creating objects inside main.

45. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student;
class student
{ public:
int m; };
int main()
{ student S;
S.m=8;
cout<<S.m; }
(a) 8
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) The new statement ‘class student;’ is called
forward declaration of the class. This is used to inform the
compiler that such a class will be defined later. This is useful
when declaring multiple classes and communicating amongst
them. But it is mandatory that all the classes should be defined
before ‘main()’. Else it will throw errors of incomplete type.

46. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
int main()
{ student S;
S.m=8;
cout<<S.m; }
(a) 8
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) Actually the object ‘S’ inside main is local
variable. And the object after the class declaration is global.

47. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
student S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) 0
(c) Error
(d) Unpredictable
Answer: (c) Now the scope clashes and throws error.

48. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
}S;
student S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Redefinition of ‘student S’
(b) Redeclaration of ‘student S’
(c) Redefinition of instance ‘student S’
(d) Redeclaration of instance ‘student S’
Answer: (a) It is called object definition.

49. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
student S;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) 0
(c) Error
(d) Unpredictable
Answer: (c) The object cannot be inside the class itself, as it is
not completely defined.

50. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
student S;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Undefined type ‘student’
(b) Field ‘S’ has incomplete type
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (b) The compiler knows ‘student’ is a class and is
not complete till now.

51. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }
S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) It works normally. Even though ‘S;’ is given in
next line, it will be considered as continuity.

52. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }
student S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) This is not legal.

53. What will be a part of the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class student
{ public:
int m; }
student S;
int main()
{ S.m=8;
cout<<S.m; }
(a) Expected initializer before ‘S’
(b) Expected ‘;’ before ‘student’
(c) Invalid instance declaration
(d) None of the above
Answer: (a) This is all because of the confusion of declaration
of instance.

54. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }
(student) S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) The same happens here.

55. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade;
}sb;
}S;
int main()
{ S.m=8;
cout<<S.m; }
(a) 8
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) A class can be inside another class.

56. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade;
}sb;
}S;
int main()
{ sb.grade= ‘A’;
cout<<sb.grade; }
(a) A
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Here the object is inside the outer class, so it
cannot be accessed without the outer object.

57. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade;
}sb;
}S;
int main()
{ sb.grade= ‘A’;
cout<<sb.grade; }
(a) ‘sb’ not declared
(b) ‘sb’ was not declared in this scope
(c) Unknown variable ‘sb’
(d) ‘sb’ has no member ‘grade’
Answer: (b) This is because ‘sb’ is considered a member of
‘class student’.

58. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade;
}sb;
}S;
int main()
{ S.sb.grade= ‘A’;
cout<<S.sb.grade; }
(a) A
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) This works right as ‘sb’ is treated as an object of
‘class student’.

59. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade; };
}S;
int main()
{ subject sb;
sb.grade= ‘A’;
cout<<sb.grade; }
(a) A
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) The class defined inside another class is not
accessible by other classes.

60. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade; };
}S;
int main()
{ subject sb;
sb.grade= ‘A’;
cout<<sb.grade; }
(a) ‘subject’ was not declared in this scope
(b) Expected ‘;’ before ‘sb’
(c) ‘sb’ was not declared in this scope
(d) All of the above
Answer: (d) ‘subject’ is not accessible by outside.

61. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade; };
}S;
int main()
{ S.subject sb;
sb.grade= ‘A’;
cout<<sb.grade; }
(a) A
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not a legal way of creating objects for
class that is inside other classes.
62. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class student
{ public:
int m;
class subject
{ public:
char grade; };
}S;
int main()
{ S.subject sb;
sb.grade= ‘A’;
cout<<sb.grade; }
(a) ‘sb’ was not declared in this scope
(b) Expected ‘;’ before ‘sb’
(c) Invalid use of ‘class student::subject’
(d) Both ‘a’ and ‘b’
(e) ‘a’, ‘b’ and ‘c’
Answer: (e) Objects for classes defined inside other classes
cannot be created outside the outer class.

63. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
class student
{ public:
char grade; }sb;
}S;
int main()
{ S.m=9;
cout<<S.m; }
(a) Redeclaration of ‘class student’
(b) ‘class student’ incomplete
(c) Invalid use of constructor
(d) ‘student::student’ has the same name as the class in
which it is declared
(e) No error
Answer: (d) class inside a class with same name is not
possible.

64. What will be a part of the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
class student
{ public:
char grade; }sb;
int main()
{ S.m=9;
cout<<S.m; }
(a) Redeclaration of ‘class student’
(b) Redefinition of ‘class student’
(c) Both ‘a’ and ‘b’
(d) No error will be thrown
Answer: (b) Here ‘class student’ is defined twice. This throws
further errors in declaration of object of the duplicate classes
and its accesses.

65. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
class student
{ public:
int m; }sb;
int main()
{ S.m=9;
cout<<S.m; }
(a) 9
(b) 0
(c) Error
(d) Unpredictable
Answer: (c) Even though both the definitions are completely
identical, it is considered a new definition and the same errors
will be thrown.

66. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
class subject
{ public:
int g; }S;
int main()
{ S.m=9;
cout<<S.m; }
(a) 9
(b) 0
(c) Error
(d) Unpredictable
Answer: (c) Multiple classes cannot have same object name.

67. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
class subject
{ public:
int g; }S;
int main()
{ S.m=9;
cout<<S.m; }
(a) Redeclaration of ‘student S’ as ‘subject S’
(b) Redefinition of ‘student S’ as ‘subject S’
(c) Conflicting declaration ‘subject S’, ‘S’ has a previous
declaration as ‘student S’
(d) None of the above
Answer: (c) The compiler points the conflict.

68. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
int main()
{ class subject
{ public:
int g; }sb;
sb.g=9;
cout<<sb.g; }
(a) 9
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) This is a local class declaration. It is accessible
only inside main.

69. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
int main()
{ class student
{ public:
int g; }sb;
sb.g=9;
cout<<sb.g; }
(a) 9
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) The local ‘class’ doesn’t clash with the global
class.

70. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
int main()
{ class student
{ public:
int m; }S;
S.m=9;
cout<<S.m; }
(a) 9
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) Even now the scope plays the separating role.

71. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
int main()
{ class student
{ public:
int m; }S;
S.m=9;
cout<<S.m<< “ ”<<::S.m; }
(a) 9 0
(b) 0 9
(c) Error
(d) None of the above
Answer: (a) ‘::’ is used to access the global scope object.

72. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
int main()
{ class student
{ public:
int m; }Sb;
Sb.m=9;
cout<<Sb.m<< “ ”<<::S.m; }
(a) 9 0
(b) 0 9
(c) Error
(d) None of the above
Answer: (a) Even if the name is not clashing, ‘::’ can be used
to point to global scope variable.

73. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;} }S;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (a) This is a way of creating member functions.

74. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class student
{ void fun()
{ cout<<m;}
public:
int m; }S;
int main()
{ S.m=9;}
(a) Prints nothing
(b) Unpredictable symbols
(c) Error
(d) None of the above
Answer: (a) Member functions can also be private.

75. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun(); }S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (a) This is the way of declaring functions inside the
class and defining them outside. Defining inside is called
inline definition.
76. What is the output of the code? (L2)
#include<iostream>
using namespace std;
class student
{ void fun();
public:
int m; }S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;}
(a) Prints nothing
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Even private functions can be defined like this.

77. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun(); }S;
student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (c) When the return type of the definition is not
specified, it will be treated as ‘int’. As the definition and
declaration is not the same, it throws some errors.
78. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun(); }S;
student::void fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (c) This is not the legal way of defining functions
outside.

79. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun(); }S;
student::void fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) Expected function name before ‘void’
(b) Qualified-id ‘void’ for ‘function’
(c) Expected unqualified-id before ‘void’
(d) None of the above
Answer: (c) ‘void’ is treated as function name.

80. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void student::fun()
{ cout<<m;}
class student
{ public:
int m;
void fun(); }S;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (c) As student is not defined before the function
definition, it gives errors.

81. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
void student::fun()
{ cout<<m;}
class student
{ public:
int m;
void fun(); }S;
int main()
{ S.m=9;
S.fun();}
(a) ‘student’ has not been declared
(b) Unknown type ‘student’
(c) ‘m’ was not declared in this scope
(d) Both ‘a’ and ‘c’
(e) Both ‘b’ and ‘c’
Answer: (d) ‘student’ cannot be accessed before it is defined.

82. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ cout<<m;}
class student
{ public:
int m;
void fun(); }S;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (c) Global functions and member functions with
same name doesn’t map together. The class member ‘fun’ is
not mapped to definition of global ‘fun’.

83. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
void fun()
{ cout<<m;}
class student
{ public:
int m;
void fun(); }S;
int main()
{ S.m=9;
S.fun();}
(a) Invalid overwriting of ‘student::fun’
(b) Undefined reference to ‘student::fun()’
(c) Invalid overriding of ‘student::fun’
(d) None of the above
Answer: (b) The member function ‘fun’ is not defined.

84. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<< “hai”;}
}S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) hai
(c) hai9
(d) Error
Answer: (d) One member should be defined only once.

85. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<< “hai”;}
}S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) ‘fun’ redefined
(b) Redefinition of ‘void fun’
(c) Redefinition of ‘void student::fun()’
(d) None of the above
Answer: (c) member will be identified with the class name
only.

86. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<< “hai”;}
}S;
void student::fun();
int main()
{ S.m=9;
S.fun();}
(a) Redeclaration of ‘void student::fun()’
(b) Redeclaration of class member ‘void fun’
(c) Declaration of ‘void student::fun()’ outside of class is
not definition
(d) No error
Answer: (c) Member function cannot be declared outside.

87. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) This doesn’t make ‘fun’ as a member of
‘student’.

88. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) No ‘void student::fun()’ member function declared in
class ‘student’
(b) ‘class student’ has no member named ‘fun’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) Definition has an error and the function call gives
the second error.

89. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
void student::fun();
fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) Even this has the same issue.

90. What is a part of the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
void student::fun();
fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) Invalid declaration of ‘fun’
(b) ISO C++ forbids declaration of ‘fun’ with no type [-
fpremissive]
(c) Declaration of ‘::fun’ with no type
(d) None of the above
Answer: (b) Return type of a function is must in C++.

91. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m; }S;
void student::fun();
void student::fun()
{ cout<<m;}
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) Even this doesn’t work. There is no way to add a
member after declaration of class.

92. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int student::m;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) It says “‘int student::m’ is not a static member of
‘class student’”. Only static data members can be given like
this. ‘static’ members will be explained in detail in a later
chapter.

93. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int main()
{ student s;
S.m=9;
s.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (c) Data member’s values are closed to the object.
Undefined data members give some garbage values. Unlike
‘C’ here the undefined values are not initiated to 0.

94. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int main()
{ student s=S;
S.m=9;
s.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (b) ‘S’ gets the value 9 only after equating to ‘s’. So
‘s’ gets 0. Object can be equated to other objects.
95. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int main()
{ student s;
S.m=9;
s=S;
s.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) This works as expected.

96. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int main()
{ S.m=9;
student s(S);
s.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) This is another way of creating object from
another object. Its working is explained in a later chapter.

97. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
int m;
void fun()
{ cout<<m;}
}S;
int main()
{ S.m=9;
student s(S);
s.m=7;
S.fun();}
(a) 9
(b) 7
(c) Unpredictable
(d) Error
Answer: (a) Change in new objet doesn’t reflect on the
referenced object value.

98. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ protected:
int m;
public:
void fun()
{ m=9;
cout<<m;}
}S;
int main()
{ S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) A class member can access ‘protected’ members.

99. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class student
{ private:
int m;
public:
void fun()
{ m=9;
cout<<m;}
}S;
int main()
{ S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) A class member can access ‘private’ members.
100. What is the output of the code? (L2)
#include<iostream>
using namespace std;
class student
{ void game()
{ m=8; }
private:
int m;
public:
void fun()
{
game();
cout<<m;}
}S;
int main()
{ S.fun();}
(a) 8
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) A member function can call any member
function. A function can access any data member. So it works
as expected.

101. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ protected:
int m;
public:
void fun()
{ game();
cout<<m;}
}S;
void game()
{ cout<< “game ”; }
int main()
{ S.m=8;
S.fun();}
(a) game 8
(b) game
(c) Unpredictable
(d) Error
Answer: (d) A member function cannot call a non-member
function.
102. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class student
{ public:
class sub
{ void fun()
{ cout<< “sub-class”;}
}D;
}S;
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Nested class functions are accessible from main.
But here the inner class has the function ‘fun()’ in private
scope.

103. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
class sub
{ public:
void fun()
{ cout<< “sub-class”;}
}D;
}S;
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) Now the function can be accessed.

104. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
class sub
{ public:
void fun()
{ cout<< “sub-class”;}
}D;
}S;
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) Now the function can be accessed.
105. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class student
{ class sub
{ public:
void fun()
{ cout<< “sub-class”;}
};
public: sub D;
}S;
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) This is also correct. Even though the class is
defined in private scope, the object of the class is in public
scope. So it can access it easily.

106. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ class sub
{ public:
void fun();
};
public:
void sub::fun()
{ cout<< “sub-class”;}
sub D;
}S;
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) “cannot define member function
‘student::sub::fun’ within student using ‘::’ operator.

107. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ class sub
{ public:
void fun();
};
public:
sub D;
}S;
void student::sub::fun()
{ cout<< “sub-class”;}
int main()
{ S.D.fun();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) This is a proper definition. As the class is
confined to scope of inner class, while explicit definition of
the function, it requires the whole hierarchy.

108. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ class sub
{ public:
void fun()
{ cout<< “sub-class”;}
};
public:
sub D;
}S;
int main()
{ S.fun();}
(a) Unknown member ‘fun()’
(b) Class student has no member named ‘fun’
(c) ‘fun’ doesn’t belong to the scope of class student
(d) ‘student::sub::fun’ cannot be accessed from class
student
Answer: (b) The compiler doesn’t care about the existence of
the function. It just checks if the function called is available in
the current scope.

109. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ class sub
{ public:
void fun();
};
public:
sub D;
viod game
{ D.fun(); }
}S;
void student::sub::fun()
{ cout<< “sub-class”;}
int main()
{ S.game();}
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) A function of the outer class can access the
variable declared in the class. Here the object of the inner class
is treated as any member of the class.

110. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
class sub
{ public:
void fun()
{ cout<< “sub-class”; }
};
void game()
{ sub d;
d.fun(); }
}S;
int main()
{ S.game(); }
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) Here, the object ‘d’ created inside ‘student::fun’
is temporary. It will be deleted once the function has
completed execution.

111. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
class sub
{ public:
void fun()
{ cout<< “sub-class”; }
};
void fun()
{ sub d;
d.fun(); }
}S;
int main()
{ S.fun(); }
(a) sub-class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) Even this works normally.

112. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int c;
int *f;
}S;
int main()
{ S.c = 3;
S.f = &(S.c);
cout<<*(S.f); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) class members can also be pointers.

113. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int *f;
}S;
int main()
{ int c = 3;
S.f = &c;
cout<<*(S.f); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) Pointer members can also point to non-members.

114. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int c;
int *f;
}S;
int main()
{ S.c = 3;
S.f = &S.c;
cout<<*S.f; }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) ‘.’ Operator has more precedence over ‘*’ and
‘&’ operators. So it still works right.

115. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
int *f;
int fun()
{ return 3;}
}S;
int main()
{ S.f = &(S.fun());
cout<<*(S.f); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) No pointer can point to a function. This is mainly
because it indirectly points a constant which is not possible.
116. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class student
{ public:
int *f;
int fun()
{ return 3;}
}S;
int main()
{ S.f = &(S.fun());
cout<<*(S.f); }
(a) Invalid access for address ‘&’ of a constant
(b) Lvalue required as unary ‘&’ operand
(c) Invalid operand for unary operator ‘&’
(d) None of the above
Answer: (b) Compiler expects only lvalues and expressions.

117. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ Stud *C;
C = &S;
*C.f = 3;
*C.fun(); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Objects can have pointers, but it should not be
used like this for accessing.

118. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ Stud *C;
C = &S;
*C.f = 3;
*C.fun(); }
(a) Expected ‘(‘ before ‘C’ in ‘*C.f = 3’
(b) Invalid lvalue for ‘*’ operand
(c) Invalid use of ‘.’ For pointer of class ‘stud’
(d) None of the above
Answer: (d) It throws “request for member ‘f’ in ‘C’, which is
of pointer type ‘stud*’ (maybe you meant to use ‘->’ ?)”. It is
the syntax for pointer of object.

119. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ Stud *C;
C = &S;
C->f = 3;
C->fun(); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) The ‘->’ is called arrow operator. This must be
used for pointers of class objects.

120. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ Stud *C;
C = &S;
C->f = 3;
C->fun(); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) All data members and member functions should
be accessed only with ‘->’ operator.

121. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<((stud *)this)->f;}
}S;
int main()
{ S.f = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) The usage is called ‘this pointer’. It points to the
class specified in parenthesis. Instead of directly calling the
member this is preferred to avoid confusion in advanced
concepts like inheritance.

122. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<this.f;}
}S;
int main()
{ S.f = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) This is not an appropriate usage of ‘this’ pointer.

123. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<this.f;}
}S;
int main()
{ S.f = 2;
S.fun(); }
(a) Invalid use of ‘this’ pointer
(b) Expected -> before ‘f’ in ‘this.f’
(c) No class defined to be pointed by ‘this’
(d) None of the above
Answer: (d) It throws “request for member ‘f’ in ‘this’, which
is of pointer type ‘stud* const’ (maybe you meant to use ‘->’
?)”. The syntax of ‘this’ is fixed.

124. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ S.f = 2;
((stud *)this)->fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) ‘this’ pointer can be used only inside a class.

125. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f;}
}S;
int main()
{ S.f = 2;
((stud *)this)->fun(); }
(a) Invalid use of ‘this’ in non-member function
(b) ‘this’ used in a non-member
(c) ‘this’ usage doesn’t map to a class
(d) None of the above
Answer: (a) ‘this’ usage must be inside a member function
only.
126. What is the output of the code? (L5)
#include<iostream>
using namespace std;
class stud
{ public:
int f;
}S;
class blo
{ public:
void fun()
{ cout<<((stud *)this)->f;}
}D;
int main()
{ cout<< “this in different class”; }
(a) This is different class
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) ‘this’ pointer can also be used in a different and
unrelated class.

127. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
}S;
class blo
{ public:
void fun()
{ cout<<((stud *)this)->f;}
}D;
int main()
{ S.f = 2;
D.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (d) It prints ‘0’. This is because, ‘2’ is given to
specific object ‘S’. But ‘this’ pointer calls the general function
and not the specific to ‘S’.

128. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
static int f;
}S;
int stud::f = 3;
class blo
{ public:
void fun()
{ cout<<((stud *)this)->f;}
}D;
int main()
{ D.fun(); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (a) ‘static’ variable is common for the class so gives
the value. The details and usage of ‘static’ variable is
discussed in upcoming chapters.

129. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f; }
}S;
class blo
{ public:
void fun()
{ ((stud *)this)->fun();}
}D;
int main()
{ D.fun(); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (c) When an object is specifically declared and
generally called, the variable gets garbage value.

130. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f; }
}S;
class blo
{ public:
void fun(int a)
{ if(a%2 == 0)
((stud *)this)->fun();
else
cout<<((stud *)this)->fun(); }
}D;
int main()
{ D.fun(7); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) It tries to get a value from a ‘void’ function and
print it.
131. What is the output of the code? (L5)
#include<iostream>
using namespace std;
class stud
{ public:
int f;
void fun()
{ cout<<f; }
}S;
class blo
{ public:
void fun(int a)
{ if(a%2 == 0)
((stud *)this)->fun();
else
cout<<((stud *)this)->fun(); }
}D;
int main()
{ D.fun(6); }
(a) 3
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Even though it doesn’t access the value, it has a
block that accesses it. So again throws the same errors.

132. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
int f;
int fun()
{ cout<<f; }
}S;
class blo
{ public:
void fun(int a)
{ if(a%2 == 0)
((stud *)this)->fun();
else
cout<<((stud *)this)->fun(); }
}D;
int main()
{ D.fun(7); }
(a) 1 garbage value
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (d) It gives ‘0 garbage value’. The same as in ‘C’,
here also when an ‘int’ function doesn’t explicitly return a
value, the compiler automatically returns 0 on success.

133. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
blo *s;
}D;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
int main()
{ S.b = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) ‘blo’ is defined only after ‘stud’. So the compiler
doesn’t know ‘blo’.

134. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class stud
{ public:
blo *s;
}D;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
int main()
{ S.b = 2;
S.fun(); }
(a) Unknown type ‘blo’
(b) ‘blo’ doesn’t name a type
(c) Invalid pointer type ‘blo’
(d) None of the above
Answer: (b) A declaration expects a type only.

135. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
class stud
{ public:
blo *s;
}D;
int main()
{ S.b = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Here usage of ‘stud’ causes the error as it is not
yet defined.

136. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}B;
class stud
{ public:
blo *s;
}D;
int main()
{ S.b = 2;
S.fun(); }
(a) Expected ‘)’ before ‘this’ in ‘((stud *)this’
(b) Expected primary-expression before ‘)’ token in ‘((stud
*)’
(c) ‘stud’ was not declared in this scope
(d) None of the above
Answer: (d) It throws all the three. This is because the
compiler treats ‘stud’ as an undefined variable and not a
function.

137. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class stud;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
class stud
{ public:
blo *s;
}D;
int main()
{ S.b = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (b) Even though ‘stud’ has been declared earlier it is
not yet defined. ‘blo’ cannot access a member of ‘stud’ even
before it is defined.

138. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class stud;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
class stud
{ public:
blo *s;
}D;
int main()
{ S.b = 2;
S.fun(); }
(a) Invalid use of incomplete type ‘class stud’
(b) Forward declaration of ‘class stud’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) Actually, there is no error in the forward
declaration, still as the error is in incomplete definition of the
class declared the compiler throws an error with the forward
declaration.

139. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class blo;
class stud
{ public:
blo *s;
}D;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
int main()
{ S.b = 2;
S.fun(); }
(a) 2
(b) Error
(c) Unpredictable
(d) None of the above
Answer: (d) Segmentation fault occurs. This is because the
pointer to object ‘blo *s’ is not initialised to any object. So
trying to access the uninitialized address dumps the core.

140. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class blo;
class stud
{ public:
blo *s;
}D;
class blo
{ public:
int b;
void fun(int a)
{ cout<<((stud *)this)->s->b; }
}S;
int main()
{ D.s = &S;
S.b = 2;
S.fun(); }
(a) 2
(b) error
(c) Unpredictable
(d) None of the above
Answer: (d) Even now Segmentation fault occurs. The
initialization ‘D.s = &S’ is specific to object ‘D’. So when
called generally the pointer is still initialized. This will work if
the pointer ‘stud *s’ is ‘static’ and assigned with ‘&D’ outside.
The initialization statement will be “blo* stud::s = &S” outside
main
3
CONSTRUCTORS AND
DESTRUCTORS
This chapter lightens the concept of special functions of a
class — the constructors and destructors. At the end of this
chapter you will be clear on the various types of usage and
the do’s and don’ts with constructors and destructors.

1. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ m=9; }
}S;
int main()
{ cout<< “S.m”;}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) The function ‘cons()’ is a special function called
‘constructor’. A constructor has the same name as the class
and should be in public scope. It doesn’t have any return type.
It will be called every time when an object of the class is
created at any scope. This is a simple constructor.
2. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class cons
{ cons()
{ m=9; }
public:
int m;
}S;
int main()
{ cout<< “S.m”;}
(a) Constructor is defied ‘private’
(b) ‘cons::cons()’ is private
(c) Invalid constructor in private
(d) No error
Answer: (b) Constructor must not be in private scope.

3. What will be the error thrown by the code? (L2)


#include<iostream>
using namespace std;
class cons
{ protected:
cons()
{ m=9; }
public:
int m;
}S;
int main()
{ cout<< “S.m”;}
(a) Constructor is defied ‘protected’
(b) ‘cons::cons()’ is protected
(c) Invalid constructor in protected
(d) No error
Answer: (b) Constructor must be in ‘public’ scope only.

4. What will be the error thrown by the code? (L2)


#include<iostream>
using namespace std;
class cons
{ protected:
cons()
{ m=9; }
public:
cons()
{ m=9; }
int m;
}S;
int main()
{ cout<< “S.m”;}
(a) ‘cons::cons()’ is protected
(b) ‘cons::cons()’ cannot be overloaded
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) Overloading will be dealt with in detail in the
lateral chapters.

5. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void cons()
{ m=9; }
}S;
int main()
{ cout<< “S.m”;}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) Here the function ‘fun()’ is treated as a normal
member function as the function has a return type. The
compiler finds that it is a constructor with return type and
throws “return type specification for constructor ‘void cons’”.

6. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ m=9; }
cons()
{ m=11; }
}S;
int main()
{ cout<< “S.m”;}
(a) 9
(b) 11
(c) Unpredictable
(d) Error
Answer: (d) “‘cons::cons()’ cannot be overloaded”.

7. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons();
}S;
cons::cons()
{ m=11; }
int main()
{ cout<< “S.m”;}
(a) 0
(b) 11
(c) Unpredictable
(d) Error
Answer: (b) Such a definition of constructor is allowed.
8. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
}S;
cons::cons()
{ m=11; }
int main()
{ cout<< “S.m”;}
(a) 0
(b) 11
(c) Unpredictable
(d) Error
Answer: (d) In the previous question there was a declaration
of the constructor. It just indicates the compiler that the
constructor is going to be defined later or outside. So the
definition outside maps to it appropriately. Here the
declaration is removed. So definition of the constructor outside
clashes with predefined constructor.

9. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
}S;
cons::cons()
{ m=11; }
int main()
{ cout<< “S.m”;}
(a) ‘cons::cons()’ cannot be overloaded
(b) Encountered definition for implicit function ‘cons’
(c) Definition of implicitly-declared ‘cons::cons()’
(d) None of the above
Answer: (c) It means that the compiler treats ‘cons()’ as an
implicit function, but its definition is specified outside.

10. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “constructor”; }
};
int main()
{ cons S;
S.cons(); }
(a) constructor
(b) constructor constructor
(c) Unpredictable
(d) Error
Answer: (d) Constructors cannot be called explicitly by the
object.

11. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “constructor”; }
};
int main()
{ cons S;
S.cons(); }
(a) Invalid use of constructor
(b) Invalid use of ‘cons::cons()’
(c) Class ‘cons’ has no member named ‘cons()’
(d) None of the above
Answer: (b) Constructors accessed by any object gives this
error.

12. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void cons()
{ cout<< “constructor”; }
};
int main()
{ cons S;
S.cons(); }
(a) constructor
(b) constructor constructor
(c) Unpredictable
(d) Error
Answer: (d) Constructors cannot have return type.

13. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void init()
{ m=80; }
cons()
{ init(); }
};
int main()
{ cons S;
cout<<S.m; }
(a) 80
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) Constructors can call other member functions of
the class.

14. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ init(); }
};
void init()
{ cout<<class initiated”; }
int main()
{ cons S; }
(a) class initiated
(b) No output
(c) Unpredictable
(d) Error
Answer: (d) Constructors cannot call non-member functions,
unlike other class member functions.

15. What will be the error thrown by the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ init(); }
};
void init()
{ cout<<class initiated”; }
int main()
{ cons S; }
(a) Class ‘cons’ has no member named ‘init()’
(b) ‘init’ was not declared in this scope
(c) Definition of ‘cons::init’ missing
(d) None of the above
Answer: (b) Constructors have constraints over their scope of
accessibility.

16. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ void init()
{ cout<<class initiated”; }
init(); }
};
int main()
{ cons S; }
(a) class initiated
(b) No output
(c) Unpredictable
(d) Error
Answer: (d) It says “a function-definition is not allowed here”
inside the constructor.

17. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ void init();
init(); }
};
void cons::init()
{ cout<<class initiated”; }
int main()
{ cons S; }
(a) No ‘void cons::init()’ member function declared in
class cons’
(b) Invalid member function declaration
(c) Invalid function declaration in the wrong scope
(d) None of the above
Answer: (a) member functions cannot be declared or defined
inside constructor.
18. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
void init();
cons()
{ void init();
init(); }
};
void cons::init()
{ cout<<class initiated”; }
int main()
{ cons S; }
(a) No ‘void cons::init()’ member function declared in
class cons’
(b) Invalid member function declaration
(c) Invalid function declaration in the wrong scope
(d) None of the above
Answer: (d) In function ‘cons::cons()’ undefined reference to
‘init()’.

19. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void init();
cons()
{ init(); }
};
void cons::init()
{ cout<<class initiated”; }
int main()
{ cons S; }
(a) Class in lower case
(b) No output
(c) Unpredictable
(d) None of the above
Answer: (a) Constructors can call a member function easily.

20. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
class sub
{ void init()
{ cout<<class initiated”; }
}d;
int m;
cons()
{ d.init(); }
};
int main()
{ cons S; }
(a) class initiated
(b) No output
(c) Unpredictable
(d) Error
Answer: (a) Constructors can call a member functions of local
classes also.

21. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “class initiated”;
cons(); }
};
int main()
{ cons S; }
(a) Prints ‘class initiated’ continuously till stack overflows
(b) Prints ‘class initiated’ once
(c) Prints nothing
(d) Error
Answer: (a) Constructors can be recursed.
22. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “class initiated”; }
void init()
{ cons(); }
};
int main()
{ cons S;
S.init(); }
(a) Prints ‘class initiated’ twice
(b) Prints ‘class initiated’ once
(c) Prints nothing
(d) Error
Answer: (a) Constructors can be called from other member
function of the same class.

23. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “class initiated”;
main(); }
};
int main()
{ cons S; }
(a) Prints ‘class initiated’ repeatedly till stack overflows
(b) Prints ‘class initiated’ once
(c) Prints nothing
(d) Error
Answer: (d) Constructor cannot call function that are out of
scope. So it cannot call ‘main’. Throws “‘main’ was not
declared in this scope”.

24. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ int d=8; }
};
int main()
{ cons S;
cout<< S.d; }
(a) 8
(b) 0
(c) Prints nothing
(d) Error
Answer: (d) ‘d’ has the scope of the constructor. It is deleted
after the execution of the constructor. So it is not accessible
from the object.

25. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons()
{ cout<< “basic constructor”; }
cons(int d)
{ cout<< “constructor with parameters”; }
};
int main()
{ cons S(3); }
(a) constructor with parameters
(b) basic constructor
(c) Prints nothing
(d) Error
Answer: (a) This is a form of overloaded constructor. It
accepts objects with parameters.

26. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< “constructor with parameters”; }
};
int main()
{ cons S(3); }
(a) constructor with parameters
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) As the object requires only a constructor with an
argument, skipping basic constructor doesn’t matter.

27. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< “constructor with parameters”; }
};
int main()
{ cons S; }
(a) constructor with parameters
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) Here the object is a basic object. It searches for
basic constructor. As there is an overloaded constructor, it
doesn’t map to the implicitly defined constructor. Thus, it
throws error regarding missing constructors.

28. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< “constructor with parameters”; }
};
int main()
{ cons S; }
(a) No matching function call to ‘cons::cons()’
(b) In function ‘cons::cons()’ candidate expects 1
argument but provided 0 argument
(c) No matching constructor to call ‘cons::cons()’
(d) Both ‘a’ and ‘b’
(e) Both ‘b’ and ‘c’
Answer: (a) Option ‘b’ is thrown as an additional note along
with some more notes.

29. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(float d)
{ cout<< d<< “ ”; }
};
int main()
{ cons S(3.34);
cons S(3); }
(a) 3.34
(b) 3
(c) Unpredictable
(d) Error
Answer: (d) The value 3.34 is considered double and throws
errors of mismatching constructor arguments.

30. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(float d)
{ cout<< d<< “ ”; }
};
int main()
{ cons S(3.34);
cons S(3); }
(a) No matching function call to ‘cons::cons(double)’
(b) Call to overloaded ‘cons(double)’ is ambiguous
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (b) The compiler tries to match the function call with
either of the two function definitions. But it is ambiguous to
choose among the two. Hence throws the error. The issue is
‘3.34’ is of type double and not float.

31. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(double d)
{ cout<< d<< “ ”; }
};
int main()
{ cons S(3.34);
cons S(3); }
(a) 3.34
(b) 3
(c) Unpredictable
(d) Error
Answer: (a) Now this is correct. The arguments matches to
the appropriate definitions and gets called appropriately.

32. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
};
int main()
{ cons S(3.34);
cons S(3); }
(a) 3.34
(b) 3
(c) Unpredictable
(d) Error
Answer: (b) As there is only one overloaded definition of the
constructor, various data types gets mapped to it internally and
type cast takes place. Here, no ambiguity is present as only
one definition is available.

33. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(int f)
{ cout<< f<< “ ”; }
};
int main()
{ cons S(3); }
(a) 3 3
(b) 3
(c) Unpredictable
(d) Error
Answer: (d) Changing the variable name of the parameter
doesn’t change the two definitions. Internally, both the
definitions are considered same and the error “
‘cons::cons(int)’ cannot be overload”.

34. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(void f)
{ cout<< “basic constructor”; }
};
int main()
{ cons S; }
(a) basic constructor
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) A variable cannot have ‘void’ type. So it throws
a set of errors in consequence of this.

35. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(void f)
{ cout<< “basic constructor”; }
};
int main()
{ cons S; }
(a) ‘f’ has incomplete type
(b) No matching function for call to ‘cons::cons()’
(c) Invalid use of ‘void’
(d) Both ‘a’ and ‘b’
(e) All of the above
Answer: (e) ‘void’ is treated as incomplete variable and hence
causes errors in the particular constructor definition.

36. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons(void)
{ cout<< “basic constructor”; }
};
int main()
{ cons S(void); }
(a) basic constructor
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) Here both the object creation and the constructor
are treated as basic definitions and ‘void’ means nothing. So it
acts as any common constructor.

37. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”;
cons(); }
cons( )
{ cout<< “basic constructor”; }
};
int main()
{ cons S(8); }
(a) 8 basic constructor
(b) 8
(c) Prints nothing
(d) Error
Answer: (a) Basic constructor can be called from overloaded
constructor.

38. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”;
cons(6); }
cons( )
{ cout<< “basic constructor”; }
};
int main()
{ cons S(8); }
(a) Prints “8 6”
(b) Prints “8 6 6 6….(till stack overflows) Segmentation
Fault”
(c) Prints nothing, compiler traps
(d) Error
Answer: (b) The call is correct, but the infinite recursion
causes this.

39. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons( )
{ cout<< “basic constructor ”;
cons(4); }
};
int main()
{ cons S; }
(a) basic constructor
(b) Prints nothing
(c) basic constructor 4
(d) Error
Answer: (c) It works normally as expected.

40. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(int d)
{ cout<< d<< “ ”; }
cons( )
{ cout<< “basic constructor ”;
cons(4); }
};
int main()
{ cons S(); }
(a) basic constructor
(b) Prints nothing
(c) basic constructor 4
(d) Error
Answer: (b) Here ‘S()’ in ‘main’ is not considered an object
even if the bracket is empty.

41. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(cons &d)
{ m=d.m;
cout<< d.m<< “ copy constructor ”; }
cons( )
{ m=9; }
};
int main()
{ cons S;
cons F(S); }
(a) 9 copy constructor
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) Copy constructor is creating an object with
reference of another object. It will be called when an object is
created with sending another object as parameter.

42. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(cons d)
{ m=d.m;
cout<< d.m<< “ copy constructor ”; }
cons( )
{ m=9; }
};
int main()
{ cons S;
cons F(S); }
(a) 9 copy constructor
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) While sending the object as reference, the values
cannot be directly used. The ‘&’ operator in definition plays
the role of mapping the value.

43. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(cons d)
{ m=d.m;
cout<< d.m<< “ copy constructor ”; }
cons( )
{ m=9; }
};
int main()
{ cons S;
cons F(S); }
(a) Expected ‘&’ before ‘d’ in ‘cons(cons d)’
(b) Missing function for call ‘cons::cons (&cons)’
(c) Invalid constructor
(d) None of the above
Answer: (c) It also shows a prediction of the expected
constructor.

44. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(cons &d)
{ cout<< d.m<< “ copy constructor ”; }
cons( )
{ m=9; }
};
int main()
{ cons S;
cons F(S); }
(a) 0 copy constructor
(b) Garbage value copy constructor
(c) Prints nothing
(d) Error
Answer: (b) Even though the object is sent in reference, the
value should be explicitly initiated for the new objects. Values
that are not initiated for an object get garbage values, and
doesn’t have 0.
45. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(cons &d)
{ cout<< d.m<< “ copy constructor ”;
cons(3); }
cons(int w)
{ cout<<w; }
cons( )
{ m=9; }
};
int main()
{ cons S;
cons F(S); }
(a) 9 copy constructor 3
(b) 9 copy constructor
(c) Unpredictable
(d) Error
Answer: (a) Any form of constructor can manually call any
other constructor easily.

46. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class sup
{ public:
int a;
sup()
{ a=8; }
};
class cons
{ public:
int m;
cons(sup &d)
{ m=d.a;
cout<< m; }
cons( )
{ m=9; }
};
int main()
{ sup S;
cons F(S); }
(a) 9
(b) 8
(c) Unpredictable
(d) Error
Answer: (b) Here the object is created in reference to object
of another class.

47. What overloaded form of constructor is used in the code?


(L4)
#include<iostream>
using namespace std;
class sup
{ public:
int a;
};
class cons
{ public:
int m;
cons(sup &d)
{ m=d.a;
cout<< m; }
};
int main()
{ sup S;
S.a=6;
cons F(S); }
(a) Copy constructor
(b) Constructor with parameters
(c) User defined data type constructor
Answer: (a) Constructors are only of three types. This is of
reference type as an object is sent as reference to another
object. If the object is not sent as reference, then it will be ‘b’.

48. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(sup &d)
{ m=d.a;
cout<< m; }
cons( )
{ m=9; }
};
class sup
{ public:
int a;
sup()
{ a=8; }
};
int main()
{ sup S;
cons F(S); }
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) Compiler organises all the classes before
executing the main. Here the class ‘sup’ is used in constructor
of ‘cons’ before definition of ‘sup’. So the compiler doesn’t
know it and throws errors.

49. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(sup &d)
{ m=d.a;
cout<< m; }
cons( )
{ m=9; }
};
class sup
{ public:
int a;
sup()
{ a=8; }
};
int main()
{ sup S;
cons F(S); }
(a) No matching function for call to ‘cons::cons(sup&)’
(b) Expected ‘)’ before ‘e’
(c) Unknown type ‘sup’
(d) Both ‘a’ and ‘b’
(e) Both ‘a’ and ‘c’
Answer: (d) As type ‘sup’ is unknown it is treated as a
variable and ‘)’ is expected after it. It is also to be noted that
the same errors come even on passing object of ‘sup’ without
reference.

50. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons(sup)
{ m=d.a;
cout<< m; }
cons( )
{ m=9; }
};
class sup
{ public:
int a;
sup()
{ a=8; }
};
int main()
{ sup S;
cons F(S); }
i. Expected ‘;’ at the end of member declaration
ii. Field ‘sup’ has incomplete type
iii. No matching function call to ‘cons::cons(sup&)’
(a) Only ‘iii’
(b) Both ‘i’ and ‘iii’
(c) Both ‘ii’ and ‘iii’

(d) All ‘i’, ‘ii’ and ‘iii’


Answer: (d) The argument ‘sup’ is incomplete. So it gives
such errors.
51. What is the output of the code? (L1)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
~cons( )
{ cout<< “destructor”; }
};
int main()
{ cons F; }
(a) destructor
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Destructor has the same name as the class with a
prefix ‘~’. It is a special function that is called automatically
when an object is deleted.

52. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
~cons( )
{ cout<< “destructor”; }
};
int main()
{ cons F;
F.~cons(); }
(a) destructor destructor
(b) destructor
(c) Prints destructor infinitely till stack overflows
(d) Error
Answer: (a) A destructor can be called explicitly by the object
from main. Even on calling it explicitly, it will be executed
automatically once more while the object is being deleted.

53. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void del()
{ cout<< “destructor”; }
~cons( )
{ del();}
};
int main()
{ cons F; }
(a) destructor
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) A destructor can call other member functions.
54. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class cons
{ public:
int m;
~cons( )
{ del();}
};
void del()
{ cout<< “destructor”; }
int main()
{ cons F; }
(a) destructor
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) A destructor cannot call functions defined
outside. It throws “‘del’ was not declared in this scope”.

55. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
void del()
{ ~cons(); }
~cons( )
{ cout<< “destructor”; }
};
int main()
{ cons F;
F.del(); }
(a) destructor destructor
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (d) ‘~’ is a special operator and cannot be used
elsewhere in normal C++ program. The compiler throws a
number of notes regarding the usage of the operator and halts
the compilation. So no output.

56. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
~cons( )
{ cout<< “destructor”; }
~cons(int d)
{ cout<< “destructor”; }
};
int main()
{ cons F; }
(a) destructor destructor
(b) Prints nothing
(c) destructor
(d) Error
Answer: (d) Destructor is of only one type.

57. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
~cons( )
{ cout<< “destructor”; }
~cons(int d)
{ cout<< “destructor”; }
};
int main()
{ cons F; }
(a) Destructors may not have parameters
(b) ‘cons::cons()’ cannot be overloaded
(c) Invalid destructor ‘cons::cons(int)’
(d) Both ‘a’ and ‘b’
(e) All ‘a’, ‘b’ and ‘c’
Answer: (d) Destructor overloading is not possible, only one
destructor can be present in a program.

58. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons( )
{ cout<< “constructor”; }
~cons( )
{ cout<< “destructor”;
cons(); }
};
int main()
{ cons F; }
(a) constructor destructor constructor
(b) constructor constructor destructor
(c) Error
(d) None of the above
Answer: (d) It prints “constructor destructor constructor
destructor…” infinitely till stack overflows. This is because,
every time a constructor is called an object’s memory is
allocated. So a destructor must be executed for every
constructor to free the allocated memory. Thus, the loop
continues and stops on overflow of stack.

59. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class cons
{ public:
int m;
cons( )
{ cout<< “constructor”; }
~cons( )
{ cout<< “destructor”;
S.~cons(); }
}S;
int main()
{ cons F; }
(a) constructor destructor destructor
(b) constructor constructor destructor destructor destructor
(c) Error
(d) None of the above
Answer: (c) It throws “‘S’ was not declared in this scope”.
Actually, the class doesn’t know what is ‘S’ as it is defined
only after the class definition.

60. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sup
{ public:
~sup()
{ cout<< “sup destructor”; } }S;
class cons
{ public:
~cons( )
{ cout<< “destructor”;
S.~sup(); }};
int main()
{ cons F; }
(a) sup destructor destructor
(b) Destructor sup destructor
(c) Error
(d) None of the above
Answer: (b) Here ‘S’ is a global object. So it works normally
as expected.
4
STORAGE CLASS
Storage characteristics of variables can be varied by
specifying storage class at the time of declaration. This
chapter throws light on the nooks and corners of usage and
properties of various storage classes.

1. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ auto int m=9;
cout<< m; }
int main()
{ fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) ‘auto’ is a storage class. It means the variable will
be automatically deleted after the block in which it is defined
is completed. All variables are by default ‘auto’. So there is no
explicit necessity of specifying it.

2. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
void fun()
{ auto int m=9;
cout<< m; }
int main()
{ fun();
cout<<m; }
(a) Unknown variable ‘m’
(b) ‘m’ was not declared in this scope
(c) ‘m’ is declared as auto, but accessed in main
(d) None of the above
Answer: (b) ‘main’ doesn’t know ‘m’.

3. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
auto int m;
}S;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) Class members cannot be declared ‘auto’.

4. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class student
{ public:
auto int m;
}S;
int main()
{ S.m=9;
S.fun();}
(a) Class member declared ‘auto’
(b) Storage class specified for ‘m’
(c) ‘m’ specified as ‘auto’
(d) None of the above
Answer: (b) Class members cannot have storage classes.

5. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ auto int n;
cout<<n; };
int main()
{ fun();}
(a) 0
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) ‘auto’ variables will be initiated to 0 by default. It
is only an upgraded version of compilers. In earlier compliers
it may give garbage values.

6. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ auto n;
cout<<n; };
int main()
{ fun();}
(a) 0
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) ‘auto’ is just a storage class, it doesn’t associate
with any data type.

7. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
void fun()
{ auto n;
cout<<n; };
int main()
{ fun();}
(a) ‘n’ does not name a type
(b) Unknown type ‘n’
(c) Expected expression before ‘n’
(d) None of the above
Answer: (a) The compiler expects a name of a type after the
storage class, but variable name is specified.

8. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ int s = 84;
auto int *n = &s;
cout<<*n; };
int main()
{ fun();}
(a) 84
(b) 0
(c) Error
(d) None of the above
Answer: (a) Even pointers can be auto.

9. What is the output of the code? (L2)


#include<iostream>
using namespace std;
void fun()
{ int s = 84;
auto int *n = NULL;
n = &s;
cout<<*n; };
int main()
{ fun();}
(a) 84
(b) Segmentation fault
(c) Error
(d) None of the above
Answer: (a) NULL pointers also work right.

10. What is the output of the code? (L2)


#include<iostream>
using namespace std;
void fun()
{ auto void *n = NULL;
cout<<*n; };
int main()
{ fun();}
(a) Prints nothing
(b) Segmentation fault
(c) Error
(d) None of the above
Answer: (a) Even void pointers work as normal pointers.

11. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ static int count;
cout<<count; };
int main()
{ fun();}
(a) 0
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) ‘static’ storage class means that the variable will
be stored in memory even after the block completes its
execution. The variable will be freed only after the execution
of the whole program. If next time the variable is called, it
retains the old value.

12. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ static int count;
cout<<count; };
int main()
{ fun();
cout<<count; }
(a) 0
(b) 1
(c) Error
(d) None of the above
Answer: (c) Even though ‘count’ is in memory, it will be
accessible only within its scope.

13. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun()
{ static int count;
cout<<count++<< “ ”; };
int main()
{ fun();
fun();
fun(); }
(a) 0 1 2
(b) 0 0 0
(c) Error
(d) None of the above
Answer: (a) As said previously, as ‘count’ is static it will
retain the old value.

14. What is the output of the code? (L4)


#include<iostream>
using namespace std;
void fun()
{ static int count = 0;
cout<<count++<< “ ”; };
int main()
{ fun();
fun();
fun(); }
(a) 0 1 2
(b) 0 0 0
(c) Error
(d) None of the above
Answer: (a) Repeated declaration of ‘static’ variable is
skipped, so the assignment is also skipped. It works normally.
15. What is the output of the code? (L3)
#include<iostream>
using namespace std;
void fun()
{ static int count;
count = 0;
cout<<count++<< “ ”; };
int main()
{ fun();
fun();
fun(); }
(a) 0 1 2
(b) 0 0 0
(c) Error
(d) None of the above
Answer: (b) Here the variable will be reinitialised on every
call.

16. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ int r=9;
while( r— > 5)
{ static int count;
cout<<count++; } }
(a) 0 1 2
(b) 0 1 2 3
(c) 0 0 0
(d) None of the above
Answer: (b) It works even in loops as explained. It will be
declared only on the first iteration.

17. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ static int count;
cout<<count++<< “ ”;
main(); }
(a) 0 1 2 3 ….. till stack overflows
(b) 0 0 0 ….till stack overflows
(c) Error
(d) None of the above
Answer: (a) Works as expected. It is a way to find the
maximum number of recursions possible.

18. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun(int c)
{ cout<<c; }
int main()
{ static int count = 9;
fun(count); }
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (a) A static value can be passed to a function. It just
takes the value without any issues. But the dummy variable
will no more be static.

19. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun(auto int c)
{ cout<<c; }
int main()
{ static int count = 9;
fun(count); }
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (a) Even this works. As the value is just copied there
is no issue of storage class clash.

20. What is the output of the code? (L3)


#include<iostream>
using namespace std;
void fun(auto int *c)
{ cout<<c; }
int main()
{ static int count = 9;
fun(&count); }
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (a) Passing the value by reference also doesn’t
consider the storage class of the variable.

21. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ static count = 9;
cout<<count; }
(a) 9
(b) 0
(c) Error
(d) None of the above
Answer: (c) “‘count’ does not name a type”. Storage classes
do not associate any type with the variable.

22. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int main()
{ static int c = 9;
cout<<sizeof(c); }
(a) 4
(b) 6
(c) Error
(d) None of the above
Answer: (a) ‘static’ storage class doesn’t affect the size of the
variable. It just changes the storage properties of the variable.

23. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
}S;
int main()
{ S.c = 8;
cout<<S.c; }
(a) 8
(b) 0
(c) Error
(d) None of the above
Answer: (c) ‘static’ member means, irrespective of the
number of objects the member will be only one. It retains
common value in a common memory. As it is not associated
with any object it cannot be initiated with an object. It should
be initiated only by using the class name with ‘::’ operator.

24. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class sto
{ public:
static int c = 8;
}S;
int main()
{ cout<<sto::c; }
(a) 8
(b) 0
(c) Error
(d) None of the above
Answer: (c) Even though the static variable is common to the
class, it cannot be initiated within the class.

25. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
}S;
int sto::c = 3;
int main()
{ cout<<sto::c; }
(a) 3
(b) 0
(c) Error
(d) None of the above
Answer: (a) This is the way of initialising static variable.

26. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
}S;
int sto::c = 6;
int main()
{ cout<<S.c; }
(a) 6
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Static variable can be read with separate objects
also.

27. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
}S;
sto::c = 6;
int main()
{ cout<<S.c; }
(a) 6
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) While initializing also type is required. It throws
“ ‘c’ in ‘class sto’ and does not name a type”.
28. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
class sto
{ public:
sto()
{ static int c = 4;
cout<<c; }
};
int main()
{ sto S; }
(a) ISO C++ forbids in-class initialization of member
‘sto::c’
(b) Undefined reference to ‘sto::c’
(c) ‘sto’ has no member named ‘c’
(d) No error
Answer: (d) Here the static variable goes into the function. So
it is not a class member. So it has no error.

29. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class student
{ public:
void fun()
{ cout<<m;}
}S;
int student::m;
int main()
{ S.m=9;
S.fun();}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) This doesn’t make the member ‘m’ as static.
Instead it throws the error “‘int student::m’ is not a static
member of ‘class student’”. Static members cannot be added
like this. They should be declared inside the class only.

30. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
static int b;
}S;
int sto::b = 6;
int sto::c = &(sto::b);
int main()
{ cout<<*(sto::c); }
(a) 6
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This type of usage is not possible. The ‘&’ and
‘*’ do not go well with static variables. So pointers cannot be
static members.

31. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
}S;
int sto::*c = NULL;
int main()
{ cout<<sizeof(sto::c); }
(a) ‘c’ was not declared in this scope
(b) Expected variable before ‘*’ in ‘int sto::*c = NULL’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (d) It throws no error. It is actually the right way of
using static pointers. The output will be ‘8’ as usual.

32. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
}S;
int sto::*c = NULL;
int main()
{ cout<<sizeof(sto::*c); }
(a) ISO C++ forbids pointer of static ‘sto::c’
(b) Expected variable before ‘*’ in ‘sto::*c’
(c) Expected unqualified id before ‘*’ token
(d) No error
Answer: (c) This usage inside main causes problem.

33. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
int b;
}S;
S.b = 6;
int sto::c = &(S.b);
int main()
{ cout<<sizeof(sto::*c); }
(a) 6
(b) 8
(c) Error
(d) Unpredictable
Answer: (c) Global object member cannot be defined globally.
It can be initialised only inside a particular scope.

34. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
static int b;
};
int sto::b = 6;
int* sto::c = &(sto::b);
int main()
{ cout<<*(sto::c); }
(a) 6
(b) 0
(c) Error
(d) Unpredictable
Answer: (a) This works properly.

35. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
static int b;
}S;
int main()
{ S.b = 9;
int* sto::c = &(S.b);
cout<<*(sto::c); }
(a) Invalid use of unqualified-name ‘sto::c’
(b) Undefined call ‘sto::c’ inside main
(c) Invalid use of qualified-name ‘sto::c’
(d) No error, gives output 9
Answer: (c) “usage of ‘class::member” is not possible inside
main.

36. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
static int b;
}S;
int* sto::c = &(S.b);
int main()
{ S.b = 9;
cout<<*(sto::c); }
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) This is the only way of assigning a static pointer
an address of a non-static member.

37. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
static int b;
}S;
char c = ‘l’;
int* sto::c = &c;
int main()
{ cout<<*(sto::c); }
(a) l
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) A static pointer member of a class can point only
to some member of a class. It cannot point to a non-member.

38. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
static int b;
}S;
char c = ‘l’;
int* sto::c = &c;
int main()
{ cout<<*(sto::c); }
(a) Invalid initialisation of ‘sto::c’
(b) Invalid use of qualified-name ‘sto::c’
(c) Cannot convert ‘int**’ to ‘int*’ in initialization
(d) None of the above
Answer: (c) Reference to character address is internally
treated as ‘int**’.

39. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
}S;
class bro
{ public:
char c ; }D;
int* sto::c = &(D.c);
int main()
{ D.c = ‘l’ ;
cout<<*(sto::c); }
(a) Cannot convert ‘char*’ to ‘int*’ in initialization
(b) Cannot convert ‘*bro’ to ‘*sto’ in initialization
(c) Cannot convert ‘int**’ to ‘int*’ in initialization
(d) No error
Answer: (a) Now as it is another class member it shows ‘char
*’.
40. What is the output of the code? (L5)
#include<iostream>
using namespace std;
class sto
{ public:
static int *c;
}S;
class bro
{ public:
int c ; }D;
int* sto::c = &(D.c);
int main()
{ D.c = ‘l’ ;
cout<<*(sto::c); }
(a) 108
(b) 0
(c) Prints nothing
(d) Error
Answer: (a) This works as expected in the right format. So
static pointers can point to non-static members of other classes
also.

41. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
static void fun()
{ cout<<sto::c; }
}S;
int sto::c = 4;
int main()
{ sto::fun(); }
(a) 4
(b) 0
(c) Prints nothing
(d) Error
Answer: (a) ‘static’ is the only storage class applicable for
functions. A static function is free of objects. It is called by
using the class name.

42. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
static void fun()
{ cout<<sto::c; }
}S;
int main()
{ sto::fun(); }
(a) 0
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) Static variable will be allocated memory only
when it is initiated as it is not associated with objects. So when
the value is not initialised, it gives error of missing variable.
“undefined reference to ‘sto::c’”.

43. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
int b;
static void fun()
{ cout<<b; }
}S;
int main()
{ sto::fun(); }
(a) 0
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) Static functions cannot access non-static
variables.

44. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
int b;
static void fun()
{ cout<<b; }
}S;
int main()
{ sto::fun(); }
(a) ‘sto::b’ inside ‘sto::fun’ is not static
(b) Invalid use of member ‘sto::b’ in static member
function
(c) Invalid use of non-static member ‘sto::b’ in static
member function ‘sto::fun’
(d) None of the above
Answer: (b) Usage of any variable other than static members
is not permitted.
45. What is the output of the code? (L3)
#include<iostream>
using namespace std;
int b = 9;
class sto
{ public:
static int c;
static void fun()
{ cout<<b; }
}S;
int main()
{ sto::fun(); }
(a) 9
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) static functions can access other global variables
without any issue.
46. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class sup
{ public:
static int b;
}
int sup::b = 8;
class sto
{ public:
static int c;
static void fun()
{ cout<<sup::b; }
}S;
int main()
{ sto::fun(); }
(a) 8
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) This also works right.

47. What is the output of the code? (L5)


#include<iostream>
using namespace std;
int b = 4;
class sto
{ public:
static int c;
int b;
static void fun()
{ cout<<b; }
}S;
int main()
{ sto::fun(); }
(a) 4
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) Class members have more precedence over
global members inside class functions.

48. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
int b;
static void fun()
{ cout<< “hai”; }
}S;
int main()
{ sto::fun(); }
(a) hai
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) Static functions need not necessarily use a static
member variable.

49. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
int b;
static void fun( sto f)
{ cout<<f.b; }
}S;
int main()
{ sto v;
v.b = 4;
sto::fun(v); }
(a) 4
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) A static function can take arguments of any type.

50. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class sto
{ public:
static int c;
static int fun( )
{ return c; }
}S;
int sto::c = 5;
int main()
{ int v = sto::fun();
cout<<v; }
(a) 5
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) static function can return the static value. It is to
be noted that the value can be stored to a non-static variable.

51. What is the output of the code? (L1)


#include<iostream>
using namespace std;
int b = 8;
int main()
{ extern int b;
cout<<b; }
(a) 8
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) Extern storage class means the variable refers to
some already defined variable in higher scope. It is mainly
useful is accessing variables from different files while
compiling together.

52. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int b = 8;
int main()
{ extern int b;
b = 7;
cout<<b; }
(a) 7
(b) 8
(c) Unpredictable
(d) Error
Answer: (a) The value can be changed normally.

53. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int b = 8;
int main()
{ extern int b = 7;
cout<<b; }
(a) 7
(b) 8
(c) Unpredictable
(d) Error
Answer: (d) Extern variables cannot be initialized on the same
declaration statement.
54. What will be the error thrown by the code? (L4)
#include<iostream>
using namespace std;
int b = 8;
int main()
{ extern int b = 7;
cout<<b; }
(a) Invalid use of ‘extern’ keyword
(b) Expected ‘;’ before ‘=’ operator
(c) ‘extern’ type variable ‘b’ initialized on declaration
(d) None of the above
Answer: (d) It throws “‘b’ has both ‘extern’ and initializer’ ”.
The compiler doesn’t accept both together.

55. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int b = 8;
void fun()
{ cout<<b; }
int main()
{ extern int b;
b = 7;
cout<<b<< “ ”;
fun(); }
(a) 7 7
(b) 7 8
(c) Unpredictable
(d) Error
Answer: (a) Changing value of extern variable changes the
original variable also.

56. What is the output of the code? (L3)


#include<iostream>
using namespace std;
int b = 8;
void fun()
{ cout<<b; }
int main()
{ b = 7;
cout<<b<< “ ”;
fun(); }
(a) 7 7
(b) 7 8
(c) Unpredictable
(d) Error
Answer: (a) Even when extern storage class is skipped the
same output comes. But this works only within the same file.
So when multiple files and variables are to be handled,
‘extern’ is the only go!

57. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int b = 6;
class sto
{ public:
extern int b;
void fun( )
{ cout<<b; }
}S;
int main()
{ S.fun(); }
(a) 6
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (d) Class members cannot have storage class except
‘static’.

58. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int b = 6;
class sto
{ public:
void fun( )
{ extern int b;
cout<<b; }
}S;
int main()
{ S.fun(); }
(a) 6
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) This is possible, as the variable is a local variable
and not a class member.

59. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
int b = 6;
class sto
{ public:
int b;
}S;
int main()
{ S.b = extern int b;
cout<<S.b; }
(a) Expected ‘;’ before ‘extern’
(b) Expected primary-expression before ‘extern’
(c) Both ‘a’ and ‘b’
(d) No error
Answer: (c) ‘extern int b’ is declaration. It should be done
separately and then ‘S.b’ should be initiated.

60. What is the output of the code? (L2)


#include<iostream>
using namespace std;
int main()
{ register int b = 9;
cout<<b; }
(a) 9
(b) Prints nothing
(c) Unpredictable
(d) Error
Answer: (a) ‘register’ storage class means the value is
requested to be stored in register instead of RAM. It doesn’t
have any effect on the behavior of the variable.

61. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int main ()
{
auto int p;
auto int q = 10;
cout <<”default value “ <<p <<”\n”;
cout <<”default value “ <<q <<”\n”;
getchar ();
return 0;
}
(a) Compiler dependent
(b) Garbage and 10
(c) 1 and 10
(d) Compilation fault
Answer: (a) The behavior of the code will be different for
different compilers. The modern-day compilers assign zero
and the concept of garbage is avoided at most of the places.
But, the traditional compilers and compilers like Dev C++ will
initialize p with garbage and q with 10. And hence, the answer
is compiler dependent.
62. What is the output of the code?
# include <iostream>
using namespace std;
int main ()
{
int p;
auto int q;
cout <<”default value “ <<p <<”\n”;
cout <<”default value “ <<q <<”\n”;
getchar ();
return 0;
}
(a) Compiler dependent
(b) Garbage and 0
(c) 1 and 0 0
(d) Compilation fault
Answer: (a) The behavior of the code will be different for
different compilers. The modern-day compilers assign zero
and the concept of garbage is ruled out. But, the traditional
compilers and compilers like Dev C++ will initialize with
garbage. Hence, the answer is compiler dependent.

63. What is the output of the below piece of code snippet,


assuming the compiler as Dev C++ or traditional one?
(L3)
# include <iostream>
using namespace std;
int main ()
{
int p;
auto int q;
static int r;
cout <<”default value “<<p <<”\n”;
cout <<”default value “<<q <<”\n”;
cout <<”default value “ <<q <<”\n”;
getchar ();
return 0;
}
(a) Garbage, Garbage, Garbage
(b) 0, Garbage, Garbage
(c) 0,0, Garbage
(d) None of the above
Answer: (a) Non-initialized integer (with/without) auto and
static variables will have garbage. This behavior might not be
observed in the modern-day compilers.

64. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int auto_verify ()
{
int sum = 0;
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
(a) 1,1,1,1,1
(b) 0,0,0,0,0
(c) 1,2,3,4,5
(d) None of the above
Answer: (a) The output is through the behavior of the auto.
The default storage qualifier is automatic and need not be
mentioned explicitly.

65. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int auto_verify ()
{
auto int sum = 0;
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
(a) 1,1,1,1,1
(b) 0,0,0,0,0
(c) 1,2,3,4,5
(d) None of the above
Answer: (a) The output is through the behavior of the auto.

66. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
static int variable;
int variable1;
int main (){
cout <<”\n” << “static “ << variable;
cout <<”\n” << “global “ << variable1;
getchar ();
return 0;
}
(a) 0 and 0
(b) 0 and Garbage
(c) Compilation fault
(d) None of the above
Answer: (a) Static is the default storage class for global
variables. 0 is stored by default for static variables. The above
code is written to prove this.
67. What is the output of the below code snippet? (L3)
# include <iostream>
using namespace std;
static int variable;
auto int variable1;
int main (){
cout <<”\n” << “static “ << variable;
cout <<”\n” << “global “ << variable1;
getchar ();
return 0;
}
(a) 0 and 0
(b) Garbage and Garbage
(c) Compilation error
(d) None of the above
Answer: (c) Global variables cannot be auto and they are to be
static. Hence, it would be an error.

68. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
int auto_verify ()
{
static int sum = 0;
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
(a) 1,1,1,1,1
(b) 0,0,0,0,0
(c) 1,2,3,4,5
(d) None of the above
Answer: (c) is the correct answer as static would remember
the values and would not re-initialize every time.

69. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
int sum = 0;
int auto_verify ()
{
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
(a) 1,1,1,1,1
(b) 0,0,0,0,0
(c) 1,2,3,4,5
(d) None of the above
Answer: (c) Global variables are by default static and here the
sum is static by rule. Hence, the behavior is very similar to the
previous code.

70. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
static int sum = 0;
int auto_verify ()
{
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
(a) 1,1,1,1,1
(b) 0,0,0,0,0
(c) 1,2,3,4,5
(d) None of the above
Answer: (c) If mentioned or not mentioned explicitly, global
variables remain static hence, the output will be c)

71. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
int i = 10;
int main (){
extern int i;
cout <<i <<”\n”;
getchar ();
return 0;
}
(a) 0
(b) 10
(c) Compilation error
(d) Machine dependent
Answer: (b) Extern permits variables to be initialized outside
the main and to use them inside main if needed.
72. What is the output of the below code snippet? (L3)
# include <iostream>
using namespace std;
int i = 10;
int main (){
extern int i;
::i=11;
cout <<i <<”\n”;
getchar ();
return 0;
}
(a) 11
(b) 10
(c) Compilation error
(d) Machine dependent
Answer: (a) If the programmer has to re-initialize a value
which was earlier initialized through extern, it is always
possible through scope resolution operator. (::)

73. Can extern be used across files in the same directory –


True or False.
Answer: True – Very much possible. Object files of the files
would reside in the same directory and hence this would be a
problem.

74. Can register be used as storage qualifier? – True or False.


Answer: True – Yes. When needed, it can be used. In
embedded systems, when faster access is required, register is
used. But, otherwise, it would not be used.
75. What is the output of the following code snippet? (L3)
# include <iostream>
using namespace std;
int main (){
register int i = 10;
cout <<i <<”\n”;
getchar ();
return 0;
}
(a) 1
(b) 10
(c) Usage of register is wrong
(d) None of the above
Answer: (b) It is very much legal to use the register as storage
qualifier. But, programmers prefer when faster access is
required.

76. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int main (){
register int i ;
cout <<i <<”\n”;
getchar ();
return 0;
}
(a) 1
(b) Garbage
(c) 0
(d) None of the above
Answer: (b) It is very much legal to use the register as storage
qualifier. But, programmers prefer when faster access is
required.

77. What is the output of the below code snippet? (L3)


# include <iostream>
using namespace std;
int main (){
int i ;
static int i;
i =10;
cout <<i <<”\n”;
getchar ();
return 0;
}
(a) 1
(b) Garbage
(c) Compilation error
(d) None of the above
Answer: (c) redeclaration of a variable is not permitted hence,
it is an error.

78. Identify the error in the following code. (L4)


# include <iostream>
using namespace std;
global int sum = 0;
int auto_verify ()
{
sum = sum + 1;
cout <<”\n” << sum;
}
int main ()
{
int i, ret;
for (i=1;i<=5;i++)
{
ret = auto_verify();
}
getchar ();
return 0;
}
Answer: There is no explicit keyword called global supported
in C or CPP. If declared above main, it naturally gets qualified
as global storage qualifier.

79. What is the output of the below piece of code? (L4)


# include <iostream>
using namespace std;
int main ()
{
int i = 5;
{
int i = 10;
{
auto int i =15;
cout << “\n” <<i;
}
cout << “\n” <<i;
}
cout << “\n” <<i;
getchar ();
return 0;
}
(a) Compilation Error
(b) 5, 10, 15
(c) 15, 10, 5
(d) 5, 5, 5
Answer: (c) Scope of the auto storage qualifier is explained
here through this example.

80. What is the output of the below piece of code? (L3)


# include <iostream>
using namespace std;
int main ()
{
auto int a[5] = {1};
cout << “\n” << a[1];
getchar ();
return 0;
}
(a) Garbage
(b) 1
(c) 0
(d) None of the above
Answer: (c) If one of the components in an array is initialized,
rest will be automatically initialized to 0. This is referred to as
automatic array.
5
DYNAMIC MEMORY
ALLOCATION
One of the very important and tricky parts of code is memory
allocation. A good programmer should have a keen eye over
the resources, especially the memory. Dynamic memory
allocation allows us to manage memory easily and keep the
code robust. This chapter elaborates the terms and techniques
of DMA.

1. What would be the output of the following code snippet?


(L2)
#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int;
cout <<”return value” <<pointer;
return 0;
}
(a) No output
(b) If memory is allotted, an address would be printed
(c) Compilation fault
(d) 0
Answer: (b) is the correct answer. If there is sufficient
memory in the store, it would allocate memory for the integer
and shall return an address.
2. Assuming the memory allocation would start from 1000,
what would be the output of the following code? (Assume
you are using Dev C++ or G++) (L2)
#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int [2];
cout <<”return value” <<pointer <<”\n”;
cout <<”return value” <<pointer+1;
return 0;
}
(a) 1000, 1004
(b) 1000, 1000
(c) Error
(d) Invalid usage of array with new
Answer: (a) Since the usage of new and array is proper, the
allocation would start with 1000 and would also print 1004 for
second cout statement.

3. Which of the following is true with respect to memory


allocation being done with new? (L2)
(a) Memory would be allocated based on the request and
new would return an address.
(b) When sufficient memory is not available, an error
would be displayed.
(c) When sufficient memory is not available, an exception
would be thrown.
(d) If sufficient memory is not available, it would free the
already used memory and allocate memory for current
request.
Answer: ‘a’ and ‘c’ are valid.

4. Which of the following is true with respect to memory


allocation? (L2)
(a) New must be used with free always, if not it would
throw an exception.
(b) New must be used with delete always, if not it would
throw an exception.
(c) New need not be associated with delete.
(d) Though not mandatory, it is a good practice to use
delete.
Answer: ‘b’, ‘c’ and ‘d’

5. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int ;
cout <<”return value” <<pointer <<”\n”;
free pointer;
return 0;
}
(a) An address would be returned if space is available.
(b) Compilation error as free cannot be used in this code.
(c) Syntax error.
(d) No output. No error.
Answer: (b) Usage of free is not allowed in this context.
6. What is the output of the following code? (L3)
#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int;
cout <<”return value” <<pointer <<”\n”;
delete pointer;
return 0;
}
(a) An address would be returned if space is available and
delete will be executed perfectly.
(b) Compilation error as delete cannot be used in this code.
(c) Syntax error.
(d) No output. No error.
Answer: (a) is the correct answer as it has been used perfectly.

7. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int [2];
cout <<”return value” <<pointer <<”\n”;
delete [2] pointer;
return 0;
}
(a) An address would be returned if space is available and
delete will be executed perfectly.
(b) Compilation error.
(c) Syntax error.
(d) No output. No error.
Answer: (b) is the answer. Type ‘int’ argument given to
‘delete’ is the error.

8. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int [2];
cout <<”return value” <<pointer <<”\n”;
delete [] pointer;
return 0;
}
(a) An address would be returned if space is available and
delete will be executed perfectly.
(b) Compilation error.
(c) Syntax error.
(d) No output. No error.
Answer: (a) Usage of [ ] is proper with delete and it is
acceptable with the code. No error would be thrown.

9. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
delete ptr;
return 0;
}
(a) It is not legal to delete a null pointer with delete.
Compilation error.
(b) Nothing will happen when deleting a NULL pointer. It
is a normal practice.
(c) No error and no output.
(d) None of the above.
Answer: (b) Nothing will happen when deleting the null
pointer with delete.

10. What is output of the following code? (L4)


#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int;
cout <<”return value” <<pointer <<”\n”;
delete pointer;
delete pointer;
return 0;
}
(a) Compilation fault.
(b) No error and no harm with deleting pointer twice.
(c) Run time error.
(d) Warning will be issued.
Answer: (c) Run time error. This may even result in
corruption of the code. So it is preferred not to do this.

11. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int;
cout <<”return value” <<pointer <<”\n”;
delete [] pointer;
return 0;
}
(a) Compilation fault.
(b) No error and would return the address allotted.
(c) Run time error.
(d) Warning will be issued.
Answer: (b) No error. It is fine with using delete pointer or
delete [] pointer.
12. What is the output of the following code? (L4)
#include <iostream>
using namespace std;
int main ()
{
int *pointer;
pointer = new int;
pointer = new int;
cout <<”address “ <<pointer <<”\n”;
delete pointer;
return 0;
}
(a) Compilation fault
(b) Run time error
(c) address some address
(d) None of the above
Answer: (c) It is not illegal to use new twice for the same
instance. But, it is not a good practice. This code would return
the address.

13. What is the output of the following code? (L4)


(Assume address allocation starts from 1000)
# include <iostream>
using namespace std;
int main ()
{
int n=10;
int *pointer;
pointer = new (nothrow) int;
cout<<pointer<< “,”;
*pointer =n;
cout<<* pointer<<endl;
getchar ();
return 0;
}
(a) 1000, 10
(b) Syntax error as nothing called nothrow is usable.
(c) 10, 1000
d) Compilation fault
Answer: (a) is the correct answer. Here, nothrow is used by
the program to avoid throwing exception. Instead of throwing
exception it would give the address allotted as return value or
zero if address allocation fails.

14. What is the output of the following code? (L4)


(Assume address allocation starts from 1000)
# include <iostream>
using namespace std;
int main ()
{
int n=10;
int *pointer;
pointer = new (no throw) int;
cout<<pointer<< “,”;
*pointer =n;
cout<<*pointer<<endl;
getchar ();
return 0;
}
(a) 1000, 10
(b) Syntax error as nothing called nothrow is usable.
(c) 10, 1000
(d) Compilation fault
Answer: (d) is the answer as it is a compilation fault. Nothrow
is a single word and can be written like nothrow.

15. What is the output of the following piece of code? (L4)


# include <iostream>
using namespace std;
int main ()
{
int n=10;
int *pointer;
pointer = new (nothrow) float;
cout<<pointer<< “,”;
*pointer =n;
cout<<*pointer<< endl;
getchar ();
return 0;
}
(a) Compilation fault
(b) No error will display the address and 10
(c) Runtime error
(d) None of the above
Answer: (a) Compilation fault. Pointer is of type integer and
compiler cannot convert float to integer in assignment and vice
versa.

16. Null pointer is same as the void pointer. – True or False.


Answer: False – Both are significantly different.

17. What is the output of the following piece of code? (L3)


# include <iostream>
using namespace std;
int main ()
{
int *p;
p = NULL;
cout << “\n” << p;
getchar ();
return 0;
}
(a) invalid use of pointer error
(b) Runtime error
(c) 0
(d) None of the above
Answer: (c) This is a proper code and the NULL assigned to a
pointer makes the pointer NULL pointer. It is very much legal
to do this way of assignment and will prevent garbage from
entering the pointer.

18. What is the output of the following piece of code? (L3)


# include <iostream>
using namespace std;
int main ()
{
int *p;
p = null;
cout << “\n” << p;
getchar ();
return 0;
}
(a) Compilation error
(b) Runtime error
(c) 0
(d) None of the above
Answer: (a) is the answer as it can be only NULL and not
null.

19. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
int main ()
{
int *p;
p = 0;
cout << “\n” << p;
getchar ();
return 0;
}
(a) Compilation error
(b) Runtime error
(c) 0
(d) None of the above
Answer: (c), This is another way of keeping the pointer safe
from garbage. This is also a form of NULL pointer.

20. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int main ()
{
int *p;
cout << “\n” << p;
p = 0;
cout << “\n” << p;
getchar ();
return 0;
}
(a) Garbage and 0
(b) 0 and 0
(c) Compilation fault
(d) None of the above
Answer: (a) Since p is a pointer it would hold an address. But,
as far as the programmer is concerned it is a garbage value
only.

21. What is the output of the following code snippet ? (L3)


# include <iostream>
using namespace std;
int main ()
{
int *p;
cout << “\n” << *p;
p = 0;
cout << “\n” << p;
getchar ();
return 0;
}
(a) Garbage and 0
(b) 0 and 0
(c) Compilation fault
(d) None of the above
Answer: (a) Before assigning anything to the pointer, it may
hold garbage. Here, it would print an address as garbage value.

22. What is the output of the following code snippet?


# include <iostream>
using namespace std;
int main ()
{
int *p;
p = 0;
p = NULL;
cout << “\n” << p;
getchar ();
return 0;
}
(a) It is illegal to load the pointer twice with NULL.
Compilation error
(b) 0
(c) Garbage value
(d) None of the above
Answer: (b) Nothing wrong in loading a variable or pointer
twice with the same value. Hence, would not return any error.

23. Using new is preferred over Malloc. – True or False. (L3)


Answer: True.

24. What is the output of the following code? (L4)


# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void *p;
p= &a;
cout <<”\n” << *(int *)p;
p= &b;
cout <<”\n” << *(float *)p;
getchar ();
return 0;
}
(a) Compilation error
(b) 10 and 10.235
(c) No output
(d) Syntax error
Answer: (b) This is referred as void pointer and is a general
purpose pointer. It can hold the address of any data type.

25. What is the output of the following code? (L4)


# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void p;
p= &a;
cout <<”\n” << *(int *)p;
p= &b;
cout <<”\n” << *(float *)p;
getchar ();
return 0;
}
(a) Compilation error
(b) 10 and 10.235
(c) No output
(d) Syntax error
Answer: (a) void p is wrong way of initializing the pointer. It
has to be void *p.
26. What is the output of the following code? (L4)
# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void *p;
p = NULL;
cout <<p;
getchar ();
return 0;
}
(a) Compilation fault. Void pointer cannot be allotted with
0.
(b) 0
(c) No output, no error
(d) Runtime error
Answer: (b) No harm in allotting void pointer with 0.

27. What is the output of the following code? (L4)


# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void *p;
int *q;
q = NULL;
p = q;
cout <<p;
getchar ();
return 0;
}
(a) Compilation fault. Void pointer cannot be equated to
null pointer.
(b) 0
(c) No output, no error
(d) Runtime error
Answer: (b) It is very similar to the previous question.

28. What is the output of the below given piece of code? (L3)
# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void *p;
cout <<sizeof (p) <<”\n”;
getchar ();
return 0;
}
(a) Compilation fault. It is illegal to use sizeof with void.
(b) 4
(c) 8, since, the pointer is versatile.
(d) Syntax error
Answer: (b) Any pointer would need 4 bytes for it to be
stored. Same is the case with void pointer.

29. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int main ()
{
int *p;
p = NULL;
cout <<sizeof (p) <<”\n”;
getchar ();
return 0;
}
(a) Compilation fault. It is illegal to use sizeof for NULL
pointer.
(b) 4
(c) 8, since, the pointer is versatile.
(d) Syntax error
Answer: (b) Any pointer would need 4 bytes for it to be
stored. Same is the case with NULL pointer.

30. What is the output of the below code? (L3)


# include <iostream>
using namespace std;
int main ()
{
int a = 10;
float b = 10.235;
void *p;
p= &a;
cout <<”\n” << sizeof (*(int *)p);
p= &b;
cout <<”\n” << sizeof (*(float *)p);
getchar ();
return 0;
}
(a) Compilation error, sizeof used in a bad way.
(b) 10 and 10.235
(c) 4 and 4
(d) Syntax error
Answer: (c) Any pointer would need 4 bytes for it to be
stored. Same is the case with void pointer and here it does
work. And, we have not printed the content of the pointer
instead type of the pointer.
6
INHERITANCE
This chapter goes across a very important object oriented
concept “Inheritance”. It throws light on all forms and
techniques of inheritance. At the end of this chapter you will
be able to efficiently use the concept on your programming
skills. Inheritance is the concept of getting characteristics
from one class to another. Both data members and member
functions may be inherited.

1. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev : public base
{ };
int main()
{ dev S;
S.b = 9;
cout<<S.b; }
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) Here class ‘dev’ inherits class ‘base’
functionalities in ‘public’ mode. The colon is the operator for
inheritance. ‘public’ mode of inheritance means all the
‘public’ members of base class become ‘public’ members of
derived class and ‘protected’ members of base class become
‘protected’ members of derived class. This is simple
inheritance.

2. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ protected:
int b; };
class dev : public base
{ };
int main()
{ dev S;
S.b = 9;
cout<<S.b; }
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) ‘protected’ members of base class will be
inherited as ‘protected’ members of derived class in ‘public’
inheritance. ‘protected’ members cannot be directly accessed
by an object.

3. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class base
{ protected:
int b; };
class dev : public base
{ public:
void play()
{ b = 4;
cout<<b; }
}S;
int main()
{ S.play(); }
(a) 4
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) ‘protected’ members can be called by ‘public’
members.

4. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ }D;
int main()
{ D.b = 5;
cout<<S.b; }
(a) 5
(b) 0
(c) Unpredictable
(d) Error
Answer: (b) Initializing inherited members doesn’t have any
effect on base class members.

5. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ public:
int b; }D;
int main()
{ D.b = 5;
D.base::b = 9;
cout<<D.b<< “ ”<<D.base::b; }
(a) 5 9
(b) 5 0
(c) Unpredictable
(d) Error
Answer: (a) Here ‘D.b’ refers to the variable declared in
‘dev’. To access the inherited variable the base class name is
used with ‘::’.

6. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ public:
int b;
void fun()
{ ((base *) this)->b = 2;
cout<<b<<” “<<((base *) this)->b; }
}D;
int main()
{ D.b = 5;
D.fun(); }
(a) 5 2
(b) 5 0
(c) unpredictable
(d) Error
Answer: (a) ‘this’ operator is another way of accessing the
inherited variable.

7. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ public:
int b; }D;
int main()
{ D.b = 5;
D.((base *) this)->b = 2;
cout<<b<< “ ”<<D.((base *) this)->b;}
(a) 5 2
(b) 5 0
(c) Unpredictable
(d) Error
Answer: (d) Invalid use of ‘this’ operator.

8. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ public:
int b; }D;
int main()
{ D.b = 5;
D.((base *) this)->b = 2;
cout<<b<< “ ”<<D.((base *) this)->b;}
(a) Invalid use of ‘this’ in non-member function
(b) Expected unqualified-id before ‘(‘ token in D.((base *)
this)->b = 2;
(c) Invalid use of ‘this’ in ‘main()’
(d) Both ‘a’ and ‘b’
(e) Both ‘b’ and ‘c’
Answer: (e) ‘this’ can be used only inside a member function.
So outside the class member functions, to access the inherited
variable ‘base class ::’ should be used.

9. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev :: public base
{ }D;
int main()
{ D.b = 8;
cout<<D.b;}
(a) 8
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) ‘::’ cannot be used for inheritance. It is used for
defining functions and static variables declared inside the
class.

10. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev :: public base
{ }D;
int main()
{ D.b = 8;
cout<<D.b;}
(a) Expected identifier before ‘public’
(b) ‘dev’ has not been declared
(c) Expected id before public
(d) Both ‘a’ and ‘b’
(e) ‘a’, ‘b’ and ‘c’
Answer: (d) It has further errors regarding undeclared ‘D’.
Also it expects unqualified-id before ‘public’ and any normal
id.

11. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev
: public base
{ }D;
int main()
{ D.b = 8;
cout<<D.b;}
(a) 8
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) Even though the inherited part is given in a new
line, it is treated as continuous lines as the previous line
doesn’t meet an expected end or ‘{’ for its block.

12. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
int dev::b = 3;
int main()
{ cout<<dev::b;}
(a) 3
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) ‘static’ variables will not be inherited as ‘static’.

13. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
int dev::b = 3;
int main()
{ cout<<dev::b;}
(a) Unknown member ‘b’ of class ‘dev’
(b) Unknown member ‘dev::b’
(c) Undefined member ‘dev::b’ accessed
(d) None of the above
Answer: (d) It throws “ISO C++ forbids does not permit
‘base::b’ to be defined as ‘dev::b’ [-fpermissive]”

14. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
int main()
{ D.b = 9;
cout<<D.b;}
(a) 9
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) ‘static’ variables will not be inherited at all.
15. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
int main()
{ D.b = 9;
cout<<D.b;}
(a) Undefined reference to ‘base::b’
(b) Undefined reference to ‘dev::b’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) The compiler knows that ‘D.b’ is access of the
static variable of ‘base’. So it throws ‘a’ alone.

16. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
D.base::b = 3;
int main()
{ cout<<D.base::b;}
(a) 3
(b) 0
(c) Unpredictable
(d) Error
Answer: (d) This is not a valid initializing.

17. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ }D;
D.base::b = 3;
int main()
{ cout<<D.base::b;}
(a) Expected unqualified-id before ‘base’ in ‘D.base::b =
3’
(b) Expected initializer before ‘.’ Token in ‘D.base::b = 3’
(c) ISO C++ forbids doesn’t allow initializing static ‘base’
variable as ‘D.base::b = 3’
(d) None of the above
Answer: (b) This is not an appropriate initializing of base
class static variable.

18. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 3;
class dev : public base
{ public:
void fun()
{ cout<<((base *)this)->b; }
}D;
int main()
{ D.fun(); }
(a) 3
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) The ‘static’ variable retains the same value
irrespective of the class from which it is called from.

19. How many copies of ‘b’ will be created while executing


the code? (L4)
#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 3;
class dev : public base
{ public:
void fun()
{ cout<<((base *)this)->b; }
}D;
int main()
{ D.fun(); }
(a) 1
(b) 2
(c) Compiler dependent
Answer: (a) ‘static’ members will not be inherited. It is
created only once for the base class. It is accessed from the
derived class. The derived class doesn’t have a copy of the
variable for its own.

20. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : public base
{ public:
void fun()
{ cout<<((base *)this)->b; }
}D;
int dev::base::b = 3;
int main()
{ D.fun(); }
(a) 3
(b) 0
(c) Unpredictable
(d) Error
Answer: (a) Even this is right. The ‘::’ is used to represent the
full inheritance hierarchy.

21. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class base
{ protected:
int a;
public:
int b; };
class dev : protected base
{ public:
void fun()
{ a=1;
b=4;
. cout<<a<<“ ”<<b; }
}D;
int main()
{ D.fun(); }
(a) 1 4
(b) 1 0
(c) Unpredictable
(d) Error
Answer: (a) In ‘protected’ mode of inheritance, the ‘public’
and ‘protected’ members of base class is inherited as
‘protected’ members of derived class.
22. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ protected:
int a;
public:
int b; };
class dev : protected base
{ public:
void fun()
{ a=1;
cout<<a<<“ ”<<b; }
}D;
int main()
{ D.b = 3;
D.fun(); }
(a) 1 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) In ‘dev’ ‘b’ is a protected member. It cannot be
accessed by an object.

23. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ protected:
int a;
public:
int b; };
class dev : protected base
{ public:
void fun()
{ a=1;
cout<<a<<“ ”<<b; }
}D;
int main()
{ D.b = 3;
D.fun(); }
(a) Invalid call to protected member ‘dev::b’
(b) ‘int base::b’ is inaccessible
(c) ‘int dev::b’ is inaccessible
(d) None of the above
Answer: (b) Even though it is inherited, still it is a member of
class ‘base’.

24. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ protected:
int a;
static int b; };
int base::b = 1;
class dev : protected base
{ public:
void fun()
{ a=1;
. cout<<a<<“ ”<<dev::b; }
}D;
int main()
{ D.fun(); }
(a) 1 1
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) ‘static’ variables also behave in the same way as
expected.

25. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ protected:
int a;
static int b; };
int base::b = 1;
class dev : protected base
{ protected:
int b;
public:
int b;
void fun()
{ a=1;
base::b = 2;
. cout<<a<<“ ”<< b; }
}D;
int main()
{ D.fun(); }
(a) 1 0
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) A class cannot have two members with same
name in different access blocks.

26. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ protected:
int a;
static int b; };
int base::b = 1;
class dev : protected base
{ protected:
int b;
public:
int b;
void fun()
{ a=1;
base::b = 2;
. cout<<a<<“ ”<< b; }
}D;
int main()
{ D.fun(); }
(a) Redeclaration of ‘int dev::b’
(b) Member ‘b’ already declared
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) It just knows ‘b’ is already declared.

27. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ protected:
int a,b; };
class dev : protected base
{ public:
int b;
void fun()
{ a=1;
base::b = 2;
. cout<<a<<“ ”<< b; }
}D;
int main()
{ D.fun(); }
(a) 1 2
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (d) Here ‘b’ is not initiated. Only the inherited
variable is initialised — result is 1 0.

28. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ protected:
int a,b; };
class dev : protected base
{ protected:
int b;
public:
void fun()
{ a=1;
base::b = 2;
. cout<<a<<“ ”<< b; }
}D;
int main()
{ D.fun(); }
(a) 1 2
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (d) Here ‘b’ is not initiated. Only the inherited
variable is initialized — result is 1 0.
29. What is the output of the code? (L2)
#include<iostream>
using namespace std;
class base
{ int b; };
class dev : protected base
{ public:
void fun()
{ b = 2;
. cout<< b; }
}D;
int main()
{ D.fun(); }
(a) 2
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) ‘b’ is a private member of class ‘base’ so will not
be inherited.

30. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ int b; };
class dev : protected base
{ public:
void fun()
{ b = 2;
. cout<< b; }
}D;
int main()
{ D.fun(); }
(a) ‘int base::b’ is private
(b) ‘base::b’ is inaccessible
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) The compiler knows ‘b’ is a ‘private’ variable of
base class. As ‘dev’ is inherited from ‘base’ class it knows the
variable is in ‘private’ of ‘base’.

31. What is the output of the code? (L1)


#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev : private base
{ public:
void fun()
{ b = 2;
. cout<< b; }
}D;
int main()
{ D.fun(); }
(a) 2
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) ‘private’ mode of inheritance makes both ‘public’
and ‘protected’ members of base class into ‘private’ members
of derived class. So it is accessible from a function.

32. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev : private base
{ }D;
int main()
{ D.b = 2;
. cout<<D.b; }
(a) 2
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) As said above, ‘b’ will be inherited as ‘private’
variable.

33. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev : private base
{ }D;
int main()
{ D.b = 2;
. cout<<D.b; }
(a) ‘int base::b’ is inaccessible
(b) ‘int dev::b’ is inaccessible
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) Error still points to the base class only.

34. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ int b; };
class dev : private base
{ }D;
int main()
{ D.b = 2;
. cout<<D.b; }
(a) ‘int base::b’ is private
(b) ‘int dev::b’ is inaccessible
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) Here ‘b’ is not inherited as it is ‘private’.
35. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : private base
{ }D;
int dev::base::b = 4;
int main()
{ cout<<dev::base::b; }
(a) 4
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is not an appropriate usage of static variable.

36. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : private base
{ public:
void fun()
{ base::b = 3;
cout<<((base *)this)->b; }
}D;
int main()
{ D.fun(); }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is also not valid.

37. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : private base
{ public:
void fun()
{ base::b = 3;
cout<<((base *)this)->b; }
}D;
int main()
{ D.fun(); }
(a) Expected unqualified-id before ‘base::b’
(b) Undefined reference to ‘base::b’
(c) ‘base::base’ inaccessible
(d) None of the above
Answer: (b) ‘Private static’ variable cannot be inherited or
accessed.

38. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
class dev : private base
{ public:
void fun()
{ b = 3;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) Undefined reference. This is because, static
variable is not initialized. So the memory is not allocated.

39. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 8;
class dev : private base
{ public:
void fun()
{ b = 3;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Now this works as expected.

40. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 8;
class dev : private base
{ public:
int b;
void fun()
{ base::b = 3;
cout<<base::b; }
}D;
int main()
{ D.fun(); }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) This too works normally as explained above. Not
the ‘static’ variable has been defined outside and so it is
defined.

41. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 8;
class dev : private base
{ public:
int b;
void fun()
{ base::b = 3; }
}D;
int main()
{ D.fun();
cout<<base::b; }
(a) 3
(b) 8
(c) Unpredictable
(d) Error
Answer: (b) ‘3’ is initiated only within the context of ‘D’. The
original value is not changed.

42. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b; };
int base::b = 8;
class dev : private base
{ public:
int b;
void fun()
{ base::b = 3; }
}D;
int main()
{ D.fun();
cout<<dev::base::b; }
(a) 3
(b) 8
(c) Unpredictable
(d) Error
Answer: (d) It throws “‘class base base::base’ is
inaccessible”. This is because static variables are not inherited.
43. What will be the error thrown by the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev private base
{ public:
void fun()
{ b = 2;
. cout<< b; }
}D;
int main()
{ D.fun(); }
(a) Expected unqualified-id before ‘private’
(b) Expected ‘:’ or ‘{‘ before ‘private’
(c) Invalid start of access block ‘private’
(d) None of the above
Answer: (a) ‘:’ is very important in inheritance.

44. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
private:
int v;
public:
int c; };
class dev : public base
{ }D;
int main()
{ D.b = 9;
D.c = 8;
cout<<D.b<<“ ”<<D.c; }
(a) 9 8
(b) 9 0
(c) Unpredictable
(d) Error
Answer: (a) Even though two ‘public’ blocks have been
defined, both the blocks are inherited.

45. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
protected:
int c; };
class dev : public, protected base
{ public:
void fun()
{ b = 9;
c = 7;
cout<<b<<“ ”<<c; }
}D;
int main()
{ D.fun(); }
(a) 9 7
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) A class cannot be inherited with multiple access
modes.

46. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b;
protected:
int c; };
class dev : public, protected base
{ public:
void fun()
{ b = 9;
c = 7;
cout<<b<<“ ”<<c; }
}D;
int main()
{ D.fun(); }
(a) Expected expression before ‘,’ token in ‘public,
protected base’
(b) Expected class name before ‘,’ token in ‘public,
protected base’
(c) Expected class-name before ‘,’ token in ‘public,
protected base’
(d) None of the above
Answer: (c) The compiler knows that class-name is required
in the location according to inheritance syntax.

47. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b;};
class dev : base
{ public:
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Even without access mode inheritance can be
done.
48. What is the output of the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b;};
class dev : base
{ }D;
int main()
{ D.b = 3;
cout<<D.b; }
(a) 3
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) When the access mode is not specified it is
inherited in ‘private’ mode.

49. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class dev : public base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) Undefined class cannot be specified in
inheritance. Here ‘base’ is unknown to the compiler.

50. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class dev : public base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) Expected class-name before ‘{’ token in ‘{ public:’
(b) Unknown type ‘base’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (a) Compiler just requires a class-name.

51. What is the output of the code? (L4)


#include<iostream>
using namespace std;
typedef int base;
class dev : public base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) Even though ‘base’ is a defined type, it cannot be
used as base class for inheritance. So it throws the same error.

52. What is the output of the code? (L4)


#include<iostream>
using namespace std;
typedef int base;
class dev : base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This too throws the same error. No additional
errors will be thrown.

53. What is the output of the code? (L5)


#include<iostream>
using namespace std;
class dev : public class base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 9
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) A new class cannot be declared while inheriting.

54. How many errors will be thrown while executing the code?
(L5)
#include<iostream>
using namespace std;
class dev : public class base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 2
(b) 3
(c) 5
(d) None of the above
Answer: (d) It shows 6 errors. The problem is class ‘dev’ is
also not compiled so throws errors for usage of ‘D’.

55. Which of the following will be a part of the error thrown


by the code? (L5)
#include<iostream>
using namespace std;
class dev : public class base
{ public:
int b;
void fun()
{ b = 9;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) Expected class-name before ‘class’ in ‘dev: public
class base’
(b) Invalid type in declaration before ‘;’ token in ‘}D;’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) As the class has been marked wrong, its object
cannot be declared. Thus ‘b’ is thrown.

56. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
void fun()
{ cout<<“fun”; }
};
class dev : public base
{ }D;
int main()
{ D.fun(); }
(a) fun
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Even functions will be inherited.

57. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<<“fun”; }
};
class dev : public base
{ }D;
int main()
{ D.fun(); }
(a) fun
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Even static functions can be called like any
normal functions.

58. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<<“fun”; }
};
class dev : public base
{ }D;
int main()
{ dev::fun(); }
(a) fun
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) This call is also allowed unlike ‘static’ variables.

59. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<<“fun1”; }
};
class dev : public base
{ public:
static void fun()
{ cout<<“fun2”; }
}D;
int main()
{ D.fun(); }
(a) fun1
(b) fun2
(c) Error
(d) None of the above
Answer: (b) While there are two functions, derived class
object calls the original function and not the inherited function.
60. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<<“fun1”; }
};
class dev : public base
{ public:
static void fun()
{ cout<<“fun2”; }
}D;
int main()
{ D.base::fun(); }
(a) fun1
(b) fun2
(c) Error
(d) None of the above
Answer: (a) The base class function can be called using the
derived class object by using ‘::’ operator.

61. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<<“fun1”; }
};
class dev : public base
{ public:
static void funcall()
{ ((base *)this)->fun(); }
}D;
int main()
{ D.funcall(); }
(a) fun1
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) ‘this’ operator can also be used for calling the
function.

62. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev : public base , protected base
{ public:
void fun()
{ b = 8;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 8
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Same class cannot be inherited multiple times.

63. Which of the following will be a part of the error thrown


by the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev : public base , protected base
{ public:
void fun()
{ b = 8;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) Invalid base class
(b) Duplicate base class ‘base’ invalid
(c) Duplicate base type ‘base’ invalid
(d) None of the above
Answer: (b) Along with this declaration of object is also
thrown two more errors.
64. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class base : public base
{ public:
void fun()
{ b = 8;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) 8
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) A class can be defined only once.

65. Which of the following will be a part of the error thrown


by the code? (L4)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class base : public base
{ public:
void fun()
{ b = 8;
cout<<b; }
}D;
int main()
{ D.fun(); }
(a) Duplicate class ‘base’
(b) Invalid base type ‘base’ for class ‘base’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (d) It throws an error “redefinition of ‘class base’”.
Rest it has three more errors regarding the object ‘D’.

66. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base , public dev1
{public:
void fun()
{ b = 9;
c = 2;
cout<<b<<“ ”<<c; }
}D;
int main()
{ D.fun(); }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) A class can simultaneously inherit multiple
classes. This is called multiple inheritance.

67. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base , protected dev1
{public:
void fun()
{ b = 9;
c = 2;
cout<<b<<“ ”<<c; }
}D;
int main()
{ D.fun(); }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Each class can have separate access modes and it
can be of any mode. It doesn’t depend on each other or affect
each other.

68. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base , dev1
{public:
void fun()
{ b = 9;
c = 2;
cout<<b<<“ ”<<c; }
}D;
int main()
{ D.fun(); }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This also works the same.

69. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base , dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) The mode is not specified for the second class. So
it is inherited in ‘private’ mode. Thus, member ‘c’ is ‘private’.
It is inaccessible.

70. How many errors will be thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 4
(b) 3
(c) No Error
(d) None of the above
Answer: (a) Two class names cannot be specified
continuously.

71. Which of the following will be a part of the error thrown


by the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) Expected ‘{’ before ‘dev1’
(b) Expected ‘,’, ‘{‘ or unqualified-id before ‘dev1’
(c) Invalid type in declaration before ‘{‘ token
(d) Both ‘a’ and ‘c’
(e) Both ‘b’ and ‘c’
Answer: (d) Along with this it throws errors for the object
‘D’.
72. What is the output of the code? (L4)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base : public dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Cascading ‘:’ operator doesn’t mean all the
continuous classes will be inherited into the specified class.

73. How many errors will be thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base : public dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 2
(b) 3
(c) 4
(d) None of the above
Answer: (c) Two errors for object ‘D’, and two errors
regarding the invalid inheritance specified.

74. Which of the following will be a part of the error thrown


by the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : public base : public dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) Expected ‘{’ before ‘:’ token in ‘base : public dev1’
(b) Expected unqualified-id before ‘:’ token in ‘base :
public dev1’
(c) Both ‘a’ and ‘b’
(d) None of the above
Answer: (c) ‘:’ cannot be in between inheritance base class
list.

75. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1
{ public:
int c;
};
class dev2 : (public base , public dev1)
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Throws the same errors. Base class list cannot be
specified inside ‘()’.

76. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b;
};
class dev1 : public base
{ public:
int c;
};
class dev2 : public dev1
{ }D;
int main()
{ D.b = 9;
D.c = 2;
cout<<D.b<<“ ”<<D.c; }
(a) 9 2
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This type of inheritance is called multi-level
inheritance. Here ‘dev1’ inherits ‘base’ and ‘dev2’ inherits
‘dev1’. Thus, ‘dev2’ has members of both ‘base’ and ‘dev1’.

77. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static void fun()
{ cout<< “fun”; }
};
class dev1 : public base
{ };
class dev2 : public dev1
{ }D;
int main()
{ dev2::fun(); }
(a) fun
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) ‘static’ function is still ‘static’ after many
inheritances.
78. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ public:
static int fun;
};
class dev1 : public base
{ };
class dev2 : public dev1
{ }D;
int dev2::fun = 3;
int main()
{ cout<<dev2::fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) ‘static’ member is not ‘static’ after many
inheritance. Its copy is also not created for every class.

79. What will be error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
static int fun;
};
class dev1 : public base
{ };
class dev2 : public dev1
{ }D;
int dev2::fun = 3;
int main()
{ cout<<dev2::fun; }
(a) Invalid call ‘dev2::fun’
(b) Unknown member for call ‘dev2::fun’
(c) ISO forbids does not permit ‘base::fun’ to be defined as
‘dev2::fun’ [-fpermissive]
(d) None of the above
Answer: (c) ‘fun’ is a static member of ‘base’ only.

80. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int fun;
};
class dev1 : public base
{ };
class dev2 : public dev1
{ }D;
int dev2::dev1::base::fun = 3;
int main()
{ cout<<dev2::dev1::base::fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Here the hierarchy specified is right, so works on
the right way.

81. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int fun;
};
class dev1 : public base
{ };
class dev2 : public dev1
{ }D;
int dev2:: base::fun = 3;
int main()
{ cout<<dev2::base:: fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Even this works normally, mainly because the
‘static’ member is defined in ‘base’ and that is right in the
inheritance hierarchy.
82. What is the output of the code? (L3)
#include<iostream>
using namespace std;
class base
{ };
class dev1 : public base
{ public:
static int fun; };
class dev2 : public dev1
{ }D;
int dev2:: dev1::fun = 3;
int main()
{ cout<<dev2::dev1::fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This also works normally.

83. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ };
class dev1 : public base
{ public:
static int fun; };
class dev2 : public dev1
{ }D;
int dev2::base::fun = 3;
int main()
{ cout<<dev2::base::fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) ‘fun’ is declared in ‘dev1’ only. So it cannot be
accessed from ‘base’.

84. What will be the error thrown by the code? (L4)


#include<iostream>
using namespace std;
class base
{ };
class dev1 : public base
{ public:
static int fun; };
class dev2 : public dev1
{ }D;
int dev2::base::fun = 3;
int main()
{ cout<<dev2::base::fun; }
(a) ‘fun’ is not a member of ‘base’
(b) ‘int base::fun’ is not a static member of ‘class base’
(c) Both ‘a’ and ‘b’
(d) ‘a’ twice
(e) ‘b’ twice
Answer: (c) ‘a’ will be thrown for the ‘cout’ statement while
‘b’ will be thrown for initializing the static variable.

85. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class dev1 : public base
{ };
class base
{ public:
static int fun; };
class dev2 : public dev1
{ }D;
int dev2::base::fun = 3;
int main()
{ cout<<dev2::base::fun; }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Base class must be defined before the derived
class. It throws the error “Expected class-name before ‘{’
token”.

86. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ public:
int b; };
class dev1 : public base
{ }S;
class dev2 : public base
{ }D;
int main()
{ S.b = 9;
D.b = 3;
cout<<S.b<< “ ”<<D.b; }
(a) 9 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This form of inheritance is called hierarchical
inheritance.

87. What is the output of the code? (L2)


#include<iostream>
using namespace std;
class base
{ };
class dev1 : public base
{ public:
int b; }S;
class dev2 : public base
{ public:
int fun; }D;
int main()
{ S.b = 9;
D.b = 3;
cout<<S.b<< “ ”<<D.b; }
(a) 9 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Empty classes can also be inherited.

88. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
void fun()
{ cout<<b<< “ ”; }
};
class dev1 : public base
{ public:
int b; }S;
class dev2 : public base
{ public:
int b; }D;
int main()
{ S.b = 9;
D.b = 3;
D.fun();
S.fun(); }
(a) 3 9
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Undefined variables cannot be used in a function.

89. What will be the error thrown by the code? (L5)


#include<iostream>
using namespace std;
class base
{ public:
void fun()
{ cout<<b<< “ ”; }
};
class dev1 : public base
{ public:
int b; }S;
class dev2 : public base
{ public:
int b; }D;
int main()
{ S.b = 9;
D.b = 3;
D.fun();
S.fun(); }
(a) ‘b’ undeclared
(b) ‘b’ was not declared in this scope
(c) ‘b’ was not declared first use in this function
(d) None of the above
Answer: (b) When ‘fun’ is compiled ‘b’ will not be known.
So it throws errors.

90. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
void fun()
{ cout<< “fun”; }
};
class dev1 : public base
{ public:
int b;
void fun()
{ cout<<b<< “ ”; } }S;
class dev2 : public base
{ public:
int b; }D;
int main()
{ S.b = 9;
D.b = 3;
D.fun();
S.fun(); }
(a) 3 9
(b) fun 9
(c) Error
(d) None of the above
Answer: (b) In ‘dev1’ ‘fun’ is defined. So it accesses the local
function. While in ‘dev2’ it is not defined, so calls the
inherited function. But the definitions do not affect each other.

91. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
void fun()
{ cout<< “fun”; }
};
class dev1 : public base
{ public:
void fun()
{ fun(); } }S;
class dev2 : public base
{ public:
{ }D;
int main()
{ D.fun();
S.fun(); }
(a) fun fun
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (d) In ‘dev1’ call ‘fun()’ is a recursive call and
doesn’t call the inherited function. On continuous recursion,
the stack overflows and segmentation fault occurs.

92. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
static int b;
static void fun()
{ cout<< b; }
};
class dev1 : public base
{ }S;
class dev2 : public base
{ }D;
int main()
{ base::dev1::b = 9;
base::dev2::b = 3;
dev1::fun();
dev2::fun(); }
(a) 9 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) The hierarchy given is wrong; should be
‘dev1::base::’ and ‘dev2::base’.

93. Which of the following will be one of the errors thrown by


the code? (L4)
#include<iostream>
using namespace std;
class base
{ public:
static int b;
static void fun()
{ cout<< b; }
};
class dev1 : public base
{ }S;
class dev2 : public base
{ }D;
int main()
{ base::dev1::b = 9;
base::dev2::b = 3;
dev1::fun();
dev2::fun(); }
(a) Invalid class hierarchy ‘base::dev2’
(b) ‘base::dev2’ has not been declared
(c) ‘dev2’ was not inherited by ‘base’. Invalid class
hierarchy ‘base::dev2’
(d) None of the above
Answer: (b) The compiler searched for ‘base’ which has
inherited ‘dev2’. As it is not defined it throws not declared.
Similarly, it also throws “‘base::dev1’ has not been declared”.

94. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ public:
int b;
}S;
class dev2 : public base
{ }D;
class dev3 : public base
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (d) It prints ‘0 2 5’. Here ‘3’ in ‘dev1’ goes to its
original member. But ‘fun’ in ‘base’ points to its member ‘b’.
So the inherited member ‘b’ of ‘dev1’ doesn’t get value. Thus,
it gets 0.

95. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ int b; }S;
class dev2 : public base
{ }D;
class dev3 : public base
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (c) Here also ‘S.b’ points to the private member of
‘dev1’ and not the inherited variable. So it is not accessible
and throws error.

96. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ }S;
class dev2 : public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This type of inheritance is called hybrid or virtual
inheritance. It is a combination of multilevel, hierarchical and
multiple inheritance. Here, the public members of ‘base’ are
copied twice to ‘dev3’ one copy from ‘dev1’ and another from
‘dev3’. So it throws some errors.
97. Which of the following will be a part of the error thrown
by the code? (L5)
#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ }S;
class dev2 : public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) Request for member ‘b’ is ambiguous.
(b) Redeclaration of member ‘b’ in ‘dev1’
(c) Duplicate variable ‘base::b’ in ‘dev1’
(d) Both ‘a’ and ‘c’
Answer: (a) Also it gives a note: “candidates are: int base::b”.
The same happens for ‘base::fun()’ also.

98. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : virtual public base
{ }S;
class dev2 : virtual public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (a) Adding ‘virtual’ to first level inheritance avoids
this duplicating. Now in ‘dev3’ only one copy of ‘base’
members will be inherited.

99. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ }S;
class dev2 : virtual public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) To avoid duplication, virtual must be specified in
all duplication possible classes. Gives the same set of errors.

100. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : virtual public base
{ }S;
class dev2 : virtual base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 3 2 5
(b) Unpredictable
(c) Error
(d) None of the above
Answer: (c) This is possible. But inheritance will be in private
mode. So ‘D.base::b’ is inaccessible.

101. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : virtual public base
{ public:
int b; }S;
class dev2 : virtual public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 0 2 5
(b) Unpredictable, depends on the compiling environment
(c) Error
(d) None of the above
Answer: (d) It prints ‘0 3 0’. When calling to variable, the
compiler points to the variable that is closest in hierarchy. So
in ‘E.b’ the value initialized is ‘dev1::b’ and not ‘base::b’. So
while ‘base::fun()’ is called 0 is printed and not 5.

102. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ public:
int b; }S;
class dev2 : public base
{ }D;
class dev3 : public dev1, public dev2
{ }E;
int main()
{ S.b = 3;
D.b = 2;
E.b = 5;
S.fun();
D.fun();
E.fun(); }
(a) 0 2 5
(b) Unpredictable, depends on the compiling environment
(c) Error
(d) None of the above
Answer: (c) Even though the preference is changed, while
inheriting all the members will follow. So duplication occurs
and errors will be thrown.

103. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : virtual public base
{ }S;
class dev2 : virtual public dev1
{ }D;
class dev3 : virtual public dev1
{ }E;
class dev4 : public dev2, public dev3
{ }F;
int main()
{ F.b = 3;
F.fun(); }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This works as expected.

104. What is the output of the code? (L3)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : virtual public base
{ }S;
class dev2 : virtual public dev1
{ }D;
class dev3 : virtual public dev1
{ }E;
class dev4 : virtual public dev2, virtual public dev3
{ }F;
int main()
{ F.b = 3;
F.fun(); }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) This also works fine, but the ‘virtual’ specified
while inheriting dev4 goes useless.

105. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ public:
int b;
void fun()
{ cout<< b<< “ ”; }
};
class dev1 : public base
{ }S;
class dev2 : virtual public dev1
{ }D;
class dev3 : virtual public dev1
{ }E;
class dev4 : public dev2, public dev3
{ }F;
int main()
{ F.b = 3;
F.fun(); }
(a) 3
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Even this works right. The necessity of ‘virtual’
is only on hierarchical inheritance part.

106. What is the output of the code? (L4)


#include<iostream>
using namespace std;
class base
{ };
class dev1 : public base
{ }S;
class dev2 : public dev1
{ }D;
class dev3 : public dev1
{ }E;
class dev4 : public dev2, public dev3
{ }F;
int main()
{ cout<< “fun”; }
(a) fun
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) When both the base classes is empty there is no
chance of collision and ‘virtual’ keyword can be skipped. But
it has no significance.
107. What is the type of inheritance used? (L3)
#include<iostream>
using namespace std;
class base
{ //block }A;
class dev1 : public base
{ //block }S;
class dev2 : public dev1
{ //block }D;
class dev3 : public dev1
{ //block }E;
class dev4 : public dev2, public dev3
{ //block }F;
class dev5 : public dev4
{ //block }V;
int main()
{ //block }
(a) Hybrid
(b) Hierarchical
(c) Multilevel
(d) Multiple
Answer: (a) It is a combination of simple, multilevel and
hierarchical modes.

108. What is the type of inheritance used? (L3)


#include<iostream>
using namespace std;
class base
{ //block }A;
class dev1 : public base
{ //block }S;
class dev2 : public dev1
{ //block }D;
class dev3 : public dev2
{ //block }E;
class dev4 : public dev3
{ //block }F;
class dev5 : public dev3
{ //block }V;
int main()
{ //block }
(a) Hybrid
(b) Hierarchical
(c) Multilevel
(d) Multiple
Answer: (a) It has multilevel followed by hierarchical.

109. What is the type of inheritance used? (L5)


#include<iostream>
using namespace std;
class base
{ //block }A;
class dev1 : public base
{ //block }S;
class dev2 : public dev1
{ //block }D;
class dev3 : public dev2
{ //block }E;
class dev4 : public dev3
{ //block }F;
class dev5 : public dev4, public dev3
{ //block }V;
int main()
{ //block }
(a) Hybrid
(b) Hierarchical
(c) Multilevel
(d) Multiple
Answer: (a) It is considered to be a type of hybrid inheritance.

110. What is the type of inheritance used? (L5)


#include<iostream>
using namespace std;
class base
{ //block }A;
class dev1 : public base
{ //block }S;
class dev2 : public base
{ //block }D;
class dev3 : public dev2 , public dev1
{ //block }E;
int main()
{ //block }
(a) Hybrid
(b) Hierarchical
(c) Multilevel
(d) Multiple
Answer: (a) It is also considered to be a type of hybrid
inheritance.
7
OPERATOR OVERLOADING
Operator overloading is the art of adding new, useful and
creative functionalities to operators. It is a part of
‘Polymorphism’. This chapter travels all across overloading
operators and will make you strong enough to face them.

1. Identify the characteristics of overloading and overriding.


(L1)
(a) Overloaded entities are bound during compile time and
overriding during runtime.
(b) Overloaded entities are bound during runtime and
overriding during compile time.
(c) Both exhibit the same characteristics.
(d) None of the above.
Answer: (a) Overloaded entities are bound during compile
time and overriding during runtime.

2. Using what kind of functions, we can overload operators in


C++ (L1)
(a) Member functions which are non-static
(b) Friend functions
(c) Member functions which are static
(d) a and b
(e) b and c
(f) a and c
Answer: (f) a and c
3. Say True or False – by overloading operator, the original
purpose is lost. (L1)
(a) True
(b) False
Answer: (b) False.

4. Choose the operators which cannot be overloaded in C++


(L1)
(a) .
(b) .*
(c) ?:
(d) All of the above
Answer: (d) All of the above. In addition to the above
operators, we cannot overload ::, #, ##, sizeof in C++

5. Which of the following points are true about operator


overloading in C++? (L1)
(a) We can’t have the default arguments while overloading
operators
(b) Operators doesn’t follow
(c) Both bitwise operator & and Address of operator &
take same number of operands
(d) Operator overloading is performed using functions.
(e) a,b,c
(f) a,d
(g) d only
Answer: (f) a, d

6. Say True or False: it is not mandatory to stick to the native


return types while overloading unary operators. (L1)
(a) True
(b) False
Answer: (a) True. Generally ! will be returning Boolean
value. But it can be overloaded to return an integer value too!

7. Predict the output of the following program. (L2)


#include <iostream>
using namespace std;
class Inc
{
private:
int num;
public:
Inc(int b)
{
num=b;
}
int operator ++() {
return num=num+1;
}
};
int main()
{
Inc t(10);
cout<<++t;
return 0;
}
(a) Error, since we cannot use ++ over an instance of a
class
(b) Prints 11
(c) Prints a junk value
(d) None of the above
Answer: (b) Prints 11

8. By default, the compiler overloads an operator. Choose the


operator. (L1)
(a) =
(b) *
(c) ?:
(d) ==
Answer: (a) Assignment operator is able to handle values and
variables of any type. This is able through overloading.

9. What is the following technique called, to assign one object


to another of same type? (L2)
int main()
{
Inc t(10),t1(0);
cout<<++t<<endl9;
t1=t;
cout<<++t1;
return 0;
}
(a) Copy constructor
(b) Overload constructor
(c) Copy operator
(d) Overload operator
Answer: (a) Copy constructor

10. Identify the statements that are true regarding operator


functions. (L1)
(a) They are similar to member functions, except the fact
that, they have the keyword operator and the to-be
overloaded symbol
(b) The return type can be void
(c) It can either return by value or return by reference
(d) All the above
Answer: (d) All the above

11. Predict the output of the following code. (L2)


#include <iostream>
using namespace std;
class Inc
{
private:
int num;
public:
Inc(int b)
{
num=b;
}
int operator ++() {
return num=num+1;
}
};
int main()
{
Inc t(10),t1(0);
cout<<++t<<”\t”;
t1=t;
cout<<++t1;
return 0;
}
(a) Since the operator= is not overloaded, it is illegal to
assign t1=t. it throws error
(b) 11 12
(c) 11 1
(d) 11 2
Answer: (b) t gets 10 initially and is increment to 11. Then t1
gets t, which is already 11. So on further increment of t gives
12.

12. How to differentiate postfix and prefix operator overloads?


(L1)
(a) We aren’t allowed to overload both the operators in the
same class
(b) We will overload postfix operator as a global function
(c) We will overload prefix operator as a global function
(d) We will pass a dummy value to the postfix operator
overload function
Answer: (d) We will pass a dummy value to the postfix
operator overload function

13. Identify issue with the following code. (L2)


#include<iostream>
using namespace std;
class Negation
{
int param1;
public:
Negation()
{}
Negation(int paramPassed)
{
param1=paramPassed;
}
int operator +(Negation obj)
{
return param1+obj.param1;
}
int operator +(int obj)
{
return param1+obj;
}
};
int main()
{
Negation obj1(100),obj2(200);
cout<<”add 2 obj—>”<<obj1+obj2<<endl;
cout<<”add a scalar number with obj—
>”<<obj1+200<<endl;
}
(a) We can’t overload the same operator multiple times
(b) no issue, give output as add 2 obj 300

add a scalar number with obj 300

(c) no issue, give output as add 2 obj 300

add a scalar number with obj 100


(d) none of the above
Answer: (b) It works normally as expected.

14. Identify the output of the following program. (L3)


#include<iostream>
using namespace std;
class Negation
{
int param1;
public:
Negation()
{}
Negation(int paramPassed)
{
param1=paramPassed;
}
int operator +(Negation obj)
{
return param1+obj.param1;
}
int operator +(int obj)
{
return param1+obj;
}
};
int main()
{
Negation obj1(100),obj2(200);
cout<<”add 2 obj—>”<<obj1+obj2<<endl;
cout<<”add a scalar number with obj—
>”<<200+obj1<<endl;
}

(a) add 2 obj 300

add a scalar number with obj 300

(b) add 2 obj 300

add a scalar number with obj 200


(c) compile error, no match for operator+ with operands
int and Negation
(d) no error, no output
Answer: (c) the first operator is integer which is not allowed
by the method signature.

15. Identify the output of the following program. (L3)


#include<iostream>
using namespace std;
class Negation
{
public:
int param1;
Negation()
{}
Negation(int paramPassed)
{
param1=paramPassed;
}
int operator +(Negation obj)
{
return param1+obj.param1;
}
Negation operator +(int obj,Negation obj2)
{
cout<<obj+obj2.param1;}
};
int main()
{
Negation obj1(100),obj2(200);
cout<<”add 2 obj—>”<<obj1+obj2<<endl;
}
cout<<”add a scalar number with obj—>”;
200+obj1;
}
(a) Compile error, since first operand cannot be integer
(b) Program throws exception and terminates

(c) add 2 obj 300

add a scalar number with obj 300

(d) add 2 obj 300


add a scalar number with obj 200
Answer: (c) Using friend functions, we can pass a scalar
variable as the first parameter to the overloaded method.

16. Which of the following operators cannot be overloaded by


friend functions? (L1)
(a) ()
(b) []
(c) Only a
(d) Both a and b
Answer: (d) Both a and b

17. How many parameters we need to pass when we overload


a binary operator using friend function? (L1)
(a) 1
(b) 2
(c) 3
(d) 0
Answer: (b)

18. How many parameters we need to pass when we overload


a unary operator using friend function? (L1)
(a) 1
(b) 2
(c) 3
(d) 0
Answer: (a) 1

19. Which of the following operators, when overloaded, are


not inherited by the child class? (L1)
(a) *
(b) =
(c) ++
(d) –
Answer: (b) =

20. Can we pass a scalar variable value to an overloaded


member function as the first parameter? (L1)
(a) Yes
(b) No
Answer: (b) No

21. Identify the properties of a binary operator overload. (L2)


(a) When overloaded as a member function, it takes one
parameter
(b) When overloaded as a global function, it takes two
parameters
(c) One of the parameters should be of type class
(d) All of the above
Answer: (d) All of the above

22. Predict the output of the following code. (L3)


#include<iostream>
using namespace std;
class TestAssignment
{
public:
TestAssignment &operator=( TestAssignment & );
int param1, param2;
};
TestAssignment &TestAssignment::operator=(
TestAssignment &ptRHS )
{
param1 = ptRHS.param1;
param2 = ptRHS.param2;
return *this;
}
int main()
{
TestAssignment p1, p2, p3;
p3.param1 =100;
p3.param2 =100;
p1=p2=p3;
cout<<”P1 Values=”<<p1.param1<<”,”<<p1.param2<<endl;
cout<<”P2 Values=”<<p2.param1<<”,”<<p2.param2<<endl;
cout<<”P3 Values=”<<p3.param1<<”,”<<p3.param2<<endl;
}
(a) P1 Values=100,100
P2 Values=100,100
P3 Values=100,100
(b) Error, to use p1=p2=p3
(c) Program terminates
(d) Junk values
Answer: (a) First P3 is assigned to P2. And then P2 is
assigned to P1.

23. Say Yes or No – can we overload function call operator ()?


(L1)
(a) Yes
(b) No
Answer: (a) Yes

24. Identify the output of the following code. (L3)


#include <iostream>
using namespace std;
typedef void(*ptrtofunc)();
void Wish()
{
cout<<”Hi from function called using overloaded ()”;
}
struct testFnCallOverload
{
operator ptrtofunc()
{
return Wish;
}
};
int main()
{
testFnCallOverload obj;
obj();
}
(a) Compile error as call to function obj() is wrong
(b) Hi from function called using overloaded ()
(c) Unexpected behavior
(d) None of the above
Answer: (b) We have overloaded the function call operator
with the help of function pointer.

25. Say True or False: function call operator is treated as a


binary operator when we overload it.
(a) True
(b) False
Answer: (a) True

26. Identify the output of the following code. (L2)


#include <iostream>
using namespace std;
class Test
{
int var=100;
public:
operator int ()
{
return var;
}
};
void TestFun ( int var)
{
cout << “Function with integer parameter called”;
cout<<endl<<var;
}
int main()
{
Test obj;
TestFun(obj);
return 0;
}
(a) TestFun(obj) throws error as there is no appropriate
function definition
(b) Function with integer parameter called
100
(c) Function with integer parameter called
Junk value
(d) None of the above
Answer: (b) Here operator int () overloads the type cast
operator.

27. Say Yes or No: Can we change the behavior of ++ operator


so that it subtracts one value from the given value using
operator overloading?
(a) Yes
(b) No
Answer: (a) Yes. But it is not a good practice.

28. What does the following code signify? (L2)


#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
class newOperatorExampple {
private:
void* operator new(size_t size) { }
void* operator new[](size_t size) { }
};
int main()
{
newOperatorExampple *obj = new newOperatorExampple;
newOperatorExampple *arr = new
newOperatorExampple[10];
return 0;
}
(a) It lets the class allocate memory as needed
(b) It throws error during compile time
(c) It prevents the user from instantiating
newOperatorExampple class
(d) a and b
(e) a and c
(f) b and c
Answer: (f) b and c

29. Say Yes or No. can we overload a destructor? (L1)


(a) Yes’
(b) No
Answer: (b) No, there can only be one destructor in a class.

30. Among the following operators, which will throw error


when we declare the operator function with global scope?
(L1)
(a) +=
(b) -=
(c) ()
(d) None of the above
Answer: (c) () The left operand is actually the calling object,
so the operand must be of object type.

31. While we are about to overload a binary operator, what


point should be kept in mind among the following? (L1)
(a) All the operands should be an object
(b) Operand in RHS must be of type object
(c) Operand in LHS must be of type object
(d) All of these should be considered.
Answer: (c) Operand in LHS must be of type object. The left
operand is actually the calling object, so the must be of object
type.

32. Say yes or No: We can overload any new (apart from built-
in ones) operator in C++. (L1)
(a) Yes
(b) No
Answer: (b) No. We can only overload built-in operators.

33. Say True or False : When we overload unary operator +,


we need to overload – too. (L1)
(a) True
(b) False
Answer: (b) False

34. Predict the output of the following program. (L2)


#include <iostream>
using namespace std;
class Inc
{
private:
int num;
public:
Inc(int b)
{
num=b;
}
int operator ++() {
return num=num+1;
}
};
int main()
{
Inc t(10);
cout<<++t++;
return 0;
}
(a) Prints 12
(b) Prints 11
(c) Prints junk value
(d) Compile error
Answer: (d) Because, we have not overloaded the postfix
operator.

35. Say True or False. It is not allowed to overload assignment


operator since copy constructor is already there by default.
(L2)
(a) True
(b) False
Answer: (b) False. We can overload the assignment operator
even though it is done by default.

36. Predict the output of the following. (L2)


#include <iostream>
using namespace std;
class Inc
{
private:
int num;
public:
Inc(int b)
{
num=b;
}
int operator ++() {
return num=num+1;
}
bool operator ==(Inc op1) {
if(op1.num==this->num)
return true;
}
};
int main()
{
Inc t1(10),t2(0);
t2=t1;
if(t1==t2)
cout<<”Both objects are same”;
else
cout<<”Both objects are not same”;
return 0;
}
(a) Error since there is no definition for !=
(b) Prints both objects are same
(c) Prints both objects are not same
(d) None of the above
Answer: (b) This is a way of overloading relational operators.

37. Say Yes or No: Can you use == operator to compare two
strings? (L1)
(a) Yes
(b) No
Answer: (b) No, because, when we overload a binary
operator, at least one of the operands should be of type class or
any other user defined type.

38. Predict the output of the following code. (L2)


#include <iostream>
using namespace std;
class Inc
{
private:
int num;
public:
Inc(int b)
{
num=b;
}
int operator ++() {
return num=num+1;
}
bool operator !=(Inc op1) {
if(op1.num!=this->num)
return true;
}
};
int main()
{
Inc t1(10),t2(0);
if(t1!=t2)
cout<<”Both objects are not same”;
return 0;
}
(a) Prints Both objects are not same
(b) Prints nothing
(c) Error
(d) None of the above
Answer: (a) Prints Both objects are not same.

39. Say True or False. When we declare an overload function


for ==, compiler automatically inserts one function for !=
(L2)
(a) True
(b) False
Answer: (b) False
40. Identify the output of the following code. (L2)
#include<iostream>
using namespace std;
class IntArray
{
private:
int privateArray[10];
public:
int& operator[] (const int index);
};
int& IntArray::operator[] (const int index)
{
return privateArray[index];
}
int main()
{
IntArray array;
array[1] = 100; // set a value
std::cout << array[1]; // get a value
return 0;
}
(a) Error as the array is privately scoped in class
(b) Prints 100
(c) Prints junk
(d) Program hangs
Answer: (b) Prints 100, the program overloads the subscript
operator to assign value to the privately scoped array and to
get the set value.
8
FUNCTION OVERLOADING
AND OVERRIDING
Function overloading is one of the most useful features of
OOP that allows increasing the functionality of a program
without losing readability. This chapter deals in detail about
the nooks and corners of function overloading and leads you
into overriding.

1. Which of the object orientation concepts is used in the


below piece of code? (L2)
#include <iostream>
using namespace std;
class function_echo
{
public:
void echo(int x) {
cout << “Output: “ << x << endl;
}
void echo(double y) {
cout << “Output: “ << y << endl;
}
void echo(char* z) {
cout << “Output: “ << z << endl;
}
};
int main(void)
{
function_echo foo;
foo.echo(76);
foo.echo(7878.099);
foo.echo(“Hello, Welcome to Polymorphism”);
return 0;
}
(a) Operator overloading
(b) Function overloading
(c) Function overriding
(d) None of the above
Answer: (b) Function overloading is used in the code.
Function name echo has been used for getting all data types
printed.

2. What is the output of the following piece of code? (L2)


#include <iostream>
using namespace std;
class function_echo
{
public:
void echo() {
cout << “I have nothing passed as an argument” << endl;
}
void echo(double y) {
cout << “Output: “ << y << endl;
}
void echo(char* z) {
cout << “Output: “ << z << endl;
}
};
int main(void)
{
function_echo foo;
foo.echo();
foo.echo(780.23);
foo.echo(“Hello, This is a tough question”);
return 0;
}
(a) No output
(b) Syntax error
(c) I have nothing passed as an argument
Output: 780.23
Output: Hello, This is a tough question
(d) Compilation error
Answer: (c) This code will work fine and the function will be
identified based on the number of arguments and since there is
no argument for the first call, it would search for the
appropriate function with no arguments and call the same. So
C is the answer.

3. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
class function_echo
{
public:
void echo() {
cout << “I have nothing passed as an argument” << endl;
}
void echo() {
cout << “I too have nothing with me: “ << endl;
}
void echo(char* z) {
cout << “Output: “ << z << endl;
}
};
int main(void)
{
function_echo foo;
foo.echo();
foo.echo();
foo.echo(“Hello, This is a tough question”);
return 0;
}
(a) Code will get compilation error
(b) Code will run smoothly
(c) Code will fetch syntax error
(d) None of the above
Answer: (a) Code will fetch compilation error as echo has
been ambiguous with no arguments twice. Compiler will not
be able to select one as both resemble the same.

4. What is the output of the following piece of code? (L3)


#include <iostream>
using namespace std;
class function_add
{
public:
void add(int x, int y) {
cout<<x+y<<” “;
}
void add(double x, double y) {
cout<<x+y<<” “;
}
};
int main(void)
{
function_add foo;
foo.add(76, 45);
foo.add(1.0000, 2.000);
return 0;
}
(a) Compilation fault
(b) Syntax error
(c) 121 3
(d) 3 121
Answer: (c) This is proper function overloading and function
add has been overloaded to handle double arguments.

5. What is the output of the following piece of code? (L3)


#include <iostream>
using namespace std;
class function_add
{
public:
void add(int x, int y) {
cout<<x+y<<” “;
}
void add(double x, double y, int z) {
cout<<x+y+z<<” “;
}
};
int main(void)
{
function_add foo;
foo.add(76, 45);
foo.add(1.0000, 2.000, 2);
return 0;
}
(a) Compilation fault
(b) Syntax error
(c) 121 5
(d) 5.0 121
Answer: (c) This is the right way of using function
overloading and will work fine. The number of arguments are
different for both the functions hence, the call will be made
based on the number of arguments. 2 arguments for the former
and 3 for the latter.

6. Which of the following points about function overloading


are true? (L2)
(a) Number of arguments can be the same for the
functions.
(b) Number of arguments must be different for all the
functions.
(c) Number of arguments or type of the arguments shall be
different.
(d) There is no requirement on data types or number of
arguments.
Answer: (c) Number of arguments or type of the arguments
shall be different for overloading to be performed.

7. What is the output of the following piece of code? (L3)


#include <iostream>
using namespace std;
class function_add
{
public:
void add(int x, int y, int z) {
cout<<x+y+z<<” “;
}
void add(int a, int b, int c) {
cout<<a+b+c<<” “;
}
};
int main(void)
{
function_add foo;
foo.add(1, 2, 3);
foo.add(4, 5, 6);
return 0;
}
(a) 6 15
(b) 15 6
(c) Compilation error (Cannot be overloaded)
(d) None of the above
Answer: c) The number and type of arguments remain the
same for both the functions while name of the function being
the same. This is ambiguous and shall fail the compilation
saying cannot overload.

8. What is the output of the following code snippet? (L3)


#include <iostream>
using namespace std;
void show(char []);
void show(char [], char []);
void show(char [], char [], char []);
int main()
{
char one[] = “I LOVE INDIA”;
char two[] = “INDIA IS MY COUNTRY”;
char three[] = “JAIHIND”;
show(one);
show(one, two);
show (one, two, three);
return 0;
}
void show (char x[])
{
cout << x << endl;
}
void show (char x[], char y[])
{ cout << x << endl << y << endl; }
void show (char x[], char y[], char z[])
{
cout << x << endl << y << endl << z << endl;
}
(a) No output.
(b) I LOVE INDIA
I LOVE INDIA
INDIA IS MY COUNTRY
I LOVE INDIA
INDIA IS MY COUNTRY
JAIHIND
(c) JAIHIND
I LOVE INDIA
INDIA IS MY COUNTRY
(d) Compilation fault
Answer: (b) This is an example for how number of arguments
would be used for identifying appropriate function.

9. Which of the following are inappropriate with respect to


function overloading in C++? (L2)
(a) Overloading functions is not possible.
(b) Overloading operators is not possible.
(c) Overloading constructors is not possible.
(d) Overloading destructors is not possible.
Answer: a, b and c are possible and are claimed to be not
possible in the question. Only destructors cannot be
overloaded.

10. What is the output of the following code snippet? (L3)


#include <iostream>
using namespace std;
void add(int);
void add(int, int);
void add(int, int, int);
int main()
{
int x = 1;
int y = 2;
int z = 3;
add(x);
add(x, y);
add (x, y, z);
return 0;
}
void add (int a)
{
cout << a << endl;
}
void add (int a, int b)
{
cout << a + b << endl;
}
void add (int a, int b, int c)
{
cout << a + b + c << endl;
}
(a) Syntax error
(b) 1, 3, 6
(c) Compilation fault
(d) None of the above
Answer: (b) is the answer. The number of arguments are
different for all the three functions hence, the call will be
precise. The output will be 1, 1+ 2 and 1 +2 + 3 getting 1, 3
and 6.

11. Why could someone overload constructor? Select the


probable reasons from the below given options. (L2)
(a) To attain more flexibility
(b) Because it is mandatory
(c) To support the concept of copy constructors
(d) To avoid compilation faults
Answer: (a) and (c) It is not mandatory to overload the
constructors and if it is not overloaded it would not result in
any compilation faults.

12. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a;
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
}
constructor_overloading ()
{
cout <<”\n” << “No Argument”<< endl;
}
};
int main()
{
constructor_overloading obj1(2);
cout << obj1.a << endl;
constructor_overloading obj2;
return 0;
}
(a) Syntax error
(b) Constructors cannot be overloaded
(c) Single parameter
2
No argument
(d) Since there is no destructor in the code, it will fail.
Answer: (c) is the correct answer as the constructors can be
overloaded and the first one would call the constructor with
one argument and the second will call the constructor with
none. It would have been preferred if the destructor is added in
the code, but, not mandatory.
13. What is the output of the following code? (L3)
#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a,c;
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
}
constructor_overloading ()
{
cout <<”\n” << “No Argument”<< endl;
}
constructor_overloading (int d)
{
cout <<”\n” << “single parameter”<< endl;
c = d;
}
};
int main()
{
constructor_overloading obj1(2);
cout << obj1.a << endl;
constructor_overloading obj2;
constructor_overloading obj3(4);
cout << obj1.c << endl;
return 0;
}
(a) Compilation fault
(b) The code will throw segmentation fault
(c) No output
(d) Destructor missing error
Answer: (a) ‘constructor_overloading
::constructor_overloading(int)’ cannot be overloaded’. The
code has tried to overload constructor with same argument
type and number of arguments.

14. What is the output of the following code?


#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a,c;
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
cout << a << endl;
}
constructor_overloading (int d, int e)
{
cout <<”\n” << “two arguments”<< endl;
c = d + e;
cout << c << endl;
}
};
int main()
{
constructor_overloading obj1(2);
constructor_overloading obj3(4, 3);
return 0;
}
(a) 2, 4, 3
(b) 2, 7
(c) single parameter
2
Two arguments
7
(d) none of the above
Answer: (c) is the correct answer as the constructor has been
overloaded properly and nothing was out of the rule book.

15. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a,c;
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
cout << a << endl;
}
constructor_overloading (int d, int e)
{
cout <<”\n” << “two arguments”<< endl;
c = d + e;
cout << c << endl;
}
~ constructor_overloading ()
{}
};
int main()
{
constructor_overloading obj1(2);
cout <<”\n calling the destructor for first obj”;
constructor_overloading obj3(4, 3);
cout <<”\n calling the destructor for second obj”;
return 0;
}
(a) Compilation error
(b) 2, 7
(c) single parameter
2
calling the destructor for first obj
Two arguments
7
calling the destructor for second obj
(d) None of the above
Answer: (c) The destructor will be called appropriately and
‘c)’ is the correct answer.

16. What is the output of the below code snippet? (L3)


#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a,c;
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
cout << a << endl;
}
constructor_overloading (int d, int e)
{
cout <<”\n” << “two arguments”<< endl;
c = d + e;
cout << c << endl;
}
~ constructor_overloading ()
{ cout <<”This is a destructor for base class” << endl; }
~ constructor_overloading ()
{ cout <<”This is a destructor for derived class” << endl;
}
};
int main()
{
constructor_overloading obj1(2);
cout <<”\n calling the destructor for first obj”;
constructor_overloading obj3(4, 3);
cout <<”\n calling the destructor for second obj”;
return 0;
}
(a) Compilation error as destructor cannot be overloaded.
(b) Code will throw syntax error.
(c) No output, no warning.
(d) Code will compile normally.
Answer: (a) Compilation error as destructor cannot be
overloaded. This is a basic rule and destructors cannot be
overloaded.

17. What is the output of the below code snippet? (L4)


#include <iostream>
using namespace std;
class constructor_overloading
{
public:
int a,c;
~ constructor_overloading ()
{
}
constructor_overloading (int b)
{
cout <<”\n” << “single parameter”<< endl;
a = b;
cout << a << endl;
}
constructor_overloading (int d, int e)
{
cout <<”\n” << “two arguments”<< endl;
c = d + e;
cout << c << endl;
}
};
int main()
{
constructor_overloading obj1(2);
cout <<”\n calling the destructor for first obj”;
constructor_overloading obj3(4, 3);
cout <<”\n calling the destructor for second obj”;
return 0;
}
(a) Destructor has to follow the constructor in the
sequence.
(b) Warning will be thrown as Destructor in wrong place.
(c) Single parameter
2
calling the destructor for first obj
Two arguments
7
calling the destructor for second obj
(d) None of the above. Code will not produce any output.
Answer: (c) is the correct answer as the destructor can be
placed in the top of the class or bottom. Does not matter for
the execution to be carried out.

18. Which of the following points are true with respect to


constructor overloading? (L3)
(a) If a program has no constructor of appropriate type
found, object creation will result in compile time error.
(b) Constructor overloading permits usage of individual
objects as well as array of objects within the same code.
(c) Usage of constructor increases the compile time by a
huge volume.
(d) Constructor must be definitely accompanied by a
destructor.
Answer: (a) and (b) are true with respect to the constructor
overloading.

19. What is the output of the below piece of code? (L4)


#include<iostream>
using namespace std;
class Constructor_Array_Overloading
{
int x;
public:
Constructor_Array_Overloading()
{ x=0; }
Constructor_Array_Overloading(int n)
{ x=n; }
int get_value()
{ return x; }
};
int main()
{
Constructor_Array_Overloading obj1[2];
Constructor_Array_Overloading obj2[2] = {1,2,};
int i;
for(i=0;i<2;i++)
{
cout << “obj1[“ << i << “]: “ << obj1[i].get_value() <<
endl;
cout << “obj2[“ << i << “]: “ << obj2[i].get_value()<<
endl;
}
return 0;
}
(a) obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 2
(b) Compilation error
(c) Segmentation fault
(d) obj1[0]: 2
obj2[0]: 0
Answer: (a) Is the correct answer and constructors can be
overloaded to initialize array as well.
20. What is the output of the below piece of code? (L4)
#include<iostream>
using namespace std;
class Constructor_Array_Overloading
{
int x;
public:
Constructor_Array_Overloading()
{
x=0;
}
Constructor_Array_Overloading(int n)
{
x=n;
}
int get_value()
{
return x;
}
};
int main()
{
Constructor_Array_Overloading obj1[2];
Constructor_Array_Overloading obj2[2]= {1};
int i;
for(i=0;i<3;i++)
{
cout << “obj1[“ << i << “]: “ << obj1[i].get_value() <<
endl;
cout << “obj2[“ << i << “]: “ << obj2[i].get_value()<<
endl;
}
return 0;
}
(a) obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 0
(b) Compilation error
(c) Segmentation fault
(d) obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 1
Answer: (a) Because, if one element of the array is initialized,
rest all will be zero.
obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 0

21. What is the output of the following code? (L4)


#include<iostream>
using namespace std;
class Constructor_Array_Overloading
{
int x;
public:
~Constructor_Array_Overloading()
{}
Constructor_Array_Overloading()
{ x=0; }
Constructor_Array_Overloading(int n)
{ x=n; }
int get_value()
{ return x; }
};
int main()
{
Constructor_Array_Overloading obj1[2];
Constructor_Array_Overloading obj2[2]= {1};
int i;
for(i=0;i<2;i++)
{
cout << “obj1[“ << i << “]: “ << obj1[i].get_value() <<
endl;
cout << “obj2[“ << i << “]: “ << obj2[i].get_value()<<
endl;
}
return 0;
}
(a) obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 0
(b) Compilation error
(c) Segmentation fault
(d) obj1[0]: 0
obj2[0]: 1
obj1[1]: 0
obj2[1]: 1
Answer: (a) Is the correct answer as destructor can be at the
top of the code as well.

22. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
void func (int a=0, float b =0.000, char c = ‘a’)
{
cout <<”\n” << a;
cout <<”\n” << b;
cout << “\n” << c;
}
int main() {
func ();
func (10);
func (10,20.000);
return 0;
}
(a) Compilation fault
(b) Overloading error
(c) 0
0
a
10
0
a
10
20
a
(d) None of the above
Answer: (c) is the answer and this concept is referred to as
Default Arguments.

23. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
void func (int a=0, int b, char c = ‘a’)
{
cout <<”\n” << a;
cout <<”\n” << b;
cout << “\n” << c;
}
int main() {
func ();
func (10);
func (10,20.000);
return 0;
}
(a) Compilation error
(b) 0
0
a
(c) Syntax error
(d) 10
20
000
Answer: (a) Compilation error. Default argument missing for
parameter 2 of ‘void func (int, int, char)’

24. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
void func (int a=0, int b=0, char c = ‘a’)
{
int a=1;
int b=1;
cout<<a<<”,”<<b<<”,”<<c;
}
int main()
{
func ();
func (10);
func (10,20.000);
return 0;
}
(a) Compilation error
(b) 1,1,a
(c) Syntax error
(d) 10,20,000
Answer: (a) Compilation error. Declaration of ‘int a’ and ‘int
b’ shadows the default values and is not permitted.

25. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
void func (int a=0, int b=0, char c = ‘a’, int d =0)
{
cout <<”\n” << a;
cout <<”\n” << b;
cout << “\n” << c;
}
int main()
{
func ();
func (10);
func (10,20.000);
return 0;
}
(a) Compilation fault
(b) Overloading error
(c) 0
0
a
10
0
a
10
20
a
(d) None of the above
Answer: (c) The code will get compiled normally and one
more variable in the function definition will not change the
course of flow.

26. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
void func (int a=0,int a =1, int b=0, char c = ‘a’)
{
cout <<”\n” << a;
cout <<”\n” << b;
cout << “\n” << c;
}
int main() {
func ();
func (10);
func (10,20.000);
return 0;
}
(a) Compilation error
(b) 1
0
a
10
0
a
10
20
a
(c) 0
0
a
10
0
a
10
20
a
(d) None of the above.
Answer: (a) Duplicate formal parameter name.

27. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
int a,b;
int ambiguity_learn (int x, int y)
{
a = x + y;
return a;
}
int ambiguity_learn (int x, int y)
{
b = x - y;
return b;
}
int main()
{
int x=9, y=7;
ambiguity_learn (x,y);
return 0;
}
(a) 16
(b) 2
(c) Compilation error
(d) None of the above
Answer: (c) redefinition of ‘int ambiguity_learn(int, int)’ is
not permitted.

28. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
int a,b;
(int &x, int &y)
{
a = x + y;
return a;
}
(int &x, int &y)
{
b = x * y;
return b;
}
int main()
{
int x=9, y=7;
ambiguity_learn (x,y);
return 0;
}
(a) 16
(b) 63
(c) Compilation error
(d) None of the above
Answer: (c) Call of overloaded ‘ambiguity_learn(int&, int&)’
is ambiguous. There is no difference from syntax point of view
for calling a function with a value and with a reference.

29. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
int a,b;
int ambiguity_learn (int &x, int y)
{
a = x + y;
return a;
}
int ambiguity_learn (int x, int &y)
{
b = x * y;
return b;
}
int main()
{
int x=9, y=7;
ambiguity_learn (x,y);
return 0;
}
(a) 16
(b) 63
(c) Compilation error
(d) None of the above
Answer: (c) Call of overloaded ‘ambiguity_learn(int&, int&)’
is ambiguous. There is no difference from syntax point of view
for calling a function with a value and with a reference.

30. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
void func (int a, int b=1)
{
cout<<a<<”,”;
cout<<b<<” “;
}
void func (int a)
{
cout<<a<<” “;
}
int main() {
func (10);
func (10,20);
return 0;
}
(a) 10 10 20
(b) 10 20 10
(c) Compilation error
(d) Syntax error
Answer: (c) It is ambiguous here as func(10) call matches
both the functions hence, it is ambiguous.

31. What is the OOPS feature used in the following code? (L1)
#include <iostream>
using namespace std;
class base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in base class” << endl;
}
};
class derived_class : public base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in derived class” << endl;
}
};
int main ()
{
base_class b;
b.function_foo();
derived_class d;
d.function_foo();
getchar ();
return 0;
}
(a) Operator overloading
(b) Function overloading
(c) Function overriding
(d) None of the above
Answer: (c) It is function overriding. The function
function_foo has different contents in the base class and
derived class thus, overriding the function.

32. What would be the output of the following code? (L1)


#include <iostream>
using namespace std;
class base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in base class” << “, “;
}
};
class derived_class : public base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in derived class” << “, “;
}
};
int main ()
{
base_class b;
b.function_foo();
derived_class d;
d.function_foo();
getchar ();
return 0;
}
(a) Hello, I am in base class, Hello, I am in base class
(b) Hello, I am in base class, Hello, I am in derived class
(c) Hello, I am in derived class, Hello, I am in derived
class
(d) Syntax error
Answer: (b) Since the function is overridden successfully, it
will call the functions appropriately for each function call.
Base class object will call base class function and derived class
object will call derived call function.

33. What would be the output of the following code? (L1)


#include <iostream>
using namespace std;
class base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in base class” << “, “;
}
};
class derived_class : private base_class {
public:
void function_foo ()
{
cout <<”Hello, I am in derived class” << “, “;
}
};
int main ()
{
base_class b;
b.function_foo();
derived_class d;
d.function_foo();
return 0;
}
(a) Hello, I am in base class, Hello, I am in base class
(b) Hello, I am in base class, Hello, I am in derived class
(c) Hello, I am in derived class, Hello, I am in derived
class
(d) Syntax error
Answer: (b) Deriving the class with private rights has not
affected the overridden function. Since the function is
overridden successfully, it will call the functions appropriately
for each function call. Base class object will call base class
function and derived class object will call derived call
function.

34. Which of the following points hold good for function


overriding? (L2)
1. The definition of the function being overridden must
have same method name.
2. The base class function and the overriding function
must have same data type.
3. The base class function and the overriding function
must have same argument list.
4. The derived class must be inherited only with private
access rights.
(a) 1, 2
(b) 1, 2, 3
(c) 1, 2, 3, 4
(d) 4
Answer: (b) 1,2 and 3 are true with respect to function
overriding. It is referred to be as signature.

35. What is the output of the following code? (L2)


#include <iostream>
using namespace std;
class base_class {
public:
int c;
void function_foo (int a, int b)
{
c = a + b;
cout <<endl << c;
}
};
class derived_class : private base_class {
public:
int d;
void function_foo (int e, int f)
{
d = e + f;
cout<<d<<” “;
}
};
int main ()
{
base_class b;
b.function_foo(3, 4);
derived_class d;
d.function_foo(4, 5);
return 0;
}
(a) 3 5
(b) 7 9
(c) 9 7
(d) Error
Answer: (b) Since the data type, number of arguments
everything goes as per the rule referred in Question number 4,
the code will work fine and overriding will happen. The output
of the code would be 7, 9.
36. Identify mistakes if any in the following code. (L2)
#include <iostream>
using namespace std;
class base_class {
public:
float c;
void function_foo (float a, float b)
{
c = a + b;
cout <<endl << c;
}
};
class derived_class : private base_class {
public:
int d;
void function_foo (int e, int f)
{
d=e+f;
cout << endl << d;
}
};
int main ()
{
base_class b;
b.function_foo(3.222, 4.568);
derived_class d;
d.function_foo(4, 5);
return 0;
}
(a) The code will run fine, no errors. Output will be 7.79
and 9.
(b) The code will generate error as the arguments passed
are different to the called function.
(c) The code will generate warning.
(d) None of the above.
Answer: (a) The code will run. But, this does not qualify to be
called function overriding as the signature is changed. This is
referred as shadowing.

37. Which of the following are/is true about overriding? (L1).


(a) Overriding can be done with only one class in place.
(b) Overriding can be done even without inheritance.
(c) Overriding cannot be done within a class.
(d) Overriding cannot be achieved if no inheritance is
deployed.
1. a and b
2. b and c
3. c and d
4. None of the above
Answer: 3, c and d are the true about overriding.

38. What will be the output in the following code? (L2)


#include <iostream>
using namespace std;
class base_class {
public:
void function_foo (void a, void b)
{
cout<<a<<b;
}
};
class derived_class : public base_class {
public:
void function_foo (void e, void f)
{
cout<<e<<f;
}
};
int main ()
{
base_class b;
b.function_foo(3, 4);
derived_class d;
d.function_foo(4, 5);
}
(a) 3445
(b) Unpredictable symbols
(c) Error
(d) None of the above
Answer: (c) Void is the not the type of argument being passed.
So, it is an error.

39. Which of the following rules are broken in the following


code with respect to overriding? (L2)
#include <iostream>
using namespace std;
class base_class {
public:
float c;
void function_foo (float a, float b)
{
c = a + b;
cout <<endl << c;
}
};
class derived_class : public base_class {
public:
int d;
void function_foo (int e, int f)
{
d=e+f;
cout << endl << d;
}
};
int main ()
{
base_class b;
b.function_foo(3.222, 4.568);
derived_class d;
d.function_foo(4, 5);
return 0;
}
1. The definition of the function being overridden must
have same method name.
2. The base class function and the overriding function
must have same data type.
3. The base class function and the overriding function
must have same argument list.
4. Everything is fine and no rule is broken.
(a) 1 and 2
(b) 1, 2 and 3
(c) 2
(d) 4
Answer: (c) The base class function and the overriding
function must have same data type and this rule is not
followed in the above code snippet.

40. Which of the following types of inheritances supports


overriding? (L3)
1. Multiple inheritance
2. Multilevel inheritance
3. Single inheritance
4. Hybrid inheritance
5. All the above
(a) 1, 2, 3
(b) 1,3
(c) 5.
(d) 1
Answer: (c) All the types of inheritances support overriding.

41. Which of the following is true about virtual functions?


(L1)
(a) Virtual functions will enable the programmer to
redefine the functions declared in the base class in derived
class.
(b) No specific keywords are required to make a function
virtual.
(c) Virtual function enables early binding or compile time
binding.
(d) Virtual function enables late binding or runtime
binding.
Answer: (a) and (d) are true.

42. Which of the following is said to be late binding? (L2)


(a) A function call is resolved at runtime.
(b) Compiler will determine object type at runtime, and
will bind the function call.
(c) Compiler determines the object type well in advance
and binds it in time.
(d) None of the above.
Answer: (a) and (b)

43. True or False


Virtual functions also follow the same principle of one
interface and multiple methods like polymorphism. (L1)
Answer: True. It is referred as runtime polymorphism.

44. True of False


A class if using virtual function can be referred by the
term polymorphic class. (L1)
Answer: True.

45. Which of the following are wrong about virtual functions?


(L1)
(a) It is one of the member functions of a class and carries
no additional privilege.
(b) The keyword ‘virtual’ is used to make a function
virtual function.
(c) Provides no different functionality in the derived class.
(d) ‘virtual’ keyword has to be used only in upper case
letters.
Answer: (c) and (d) are wrong perceptions about virtual
functions.

46. What is the object orientation concept used in the


following code? (L2)
#include <iostream>
using namespace std;
class Base_class
{
public:
void virtual show()
{
cout << “Function Show in Base Class” << endl;
}
void display()
{
cout << “Function display in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
void display()
{
cout << “Function display in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
p->display();
Derived_class obj2;
p = &obj2;
p->show();
p->display();
return 0;
}
(a) Inline functions
(b) pure virtual function
(c) virtual function
(d) function overloading
Answer: (c) The virtual keyword used the base class member
function reveals the fact that the concept used is virtual
functions.

47. What is the output of the following piece of code? (L2)


#include <iostream>
using namespace std;
class Base_class
{
public:
void virtual show()
{
cout << “Function Show in Base Class” << endl;
}
void display()
{
cout << “Function display in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
void display()
{
cout << “Function display in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
p->display();
Derived_class obj2;
p = &obj2;
p->show();
p->display();
return 0;
}
(a) Syntax error
(b) Function Show in Base Class
Function display in Base Class
Function Show in derived Class
Function display in Base Class
(c) Function Show in Base Class
Function display in Base Class
Function Show in derived Class
Function display in derived Class
(d) Compilation fault, invalid usage of keyword virtual
Answer: (b) is the correct answer. Keyword virtual is used for
the function show hence, the compiler will call the redefined
show from derived class appropriately.
48. What is the output of the following code? (L3)
#include <iostream>
using namespace std;
class Base_class
{
public:
void virtual show()
{
cout << “Function Show in Base Class” << endl;
}
void virtual display()
{
cout << “Function display in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
void display()
{
cout << “Function display in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
p->display();
Derived_class obj2;
p = &obj2;
p->show();
p->display();
return 0;
(a) Syntax error
(b) Function Show in Base Class
Function display in Base Class
Function Show in derived Class
Function display in Base Class
(c) Function Show in Base Class
Function display in Base Class
Function Show in derived Class
Function display in derived Class
(d) Compilation fault, invalid usage of keyword virtual
Answer: (c) Since both the functions in the base class are
made virtual, the calls will be made to appropriate functions
from the derived class at runtime through late binding concept.

49. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
void display()
{
cout << “Function display in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
void display()
{
cout << “Function display in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
p->display();
Derived_class obj2;
p = &obj2;
p->show();
p->display();
return 0;
}
(a) Syntax error
(b) Function Show in Base Class
Function display in Base Class
Function Show in Base Class
Function display in Base Class
(c) Function Show in Base Class
Function display in Base Class
Function Show in derived Class
Function display in derived Class
(d) Compilation fault, invalid usage of keyword virtual
Answer: (b) is the answer. Since the early binding will happen
the compiler would call only the base class functions as
everything gets resolved at compile time. Virtual keyword as
used in previous examples would avoid this error.

50. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Syntax error
(b) Function Show in Base Class
Function Show in Base Class
(c) Function Show in Base Class
Function Show in derived Class
(d) Virtual keyword should be used as void virtual show
and not virtual void show.
Answer: (c) It does not matter if the virtual is kept before or
after function return type. It will work fine.

51. What is the output of the following code? (L3)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “Function Show in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Syntax error
(b) Function Show in Base Class
Function Show in Base Class
(c) Function Show in Base Class
Function Show in derived Class
(d) Compilation error. Keyword virtual cannot be used in
derived class.
Answer: (b) It is absolutely fine using it in a base class or a
derived class. When derived from the derived class, it will
show the usage and otherwise, no use will be there in inclusion
of the virtual keyword. The type of the pointer, i.e., of the type
base class or derived class matters.

52. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “Function Show in derived Class” << endl;
}
};
class Derived_1_class:public Derived_class
{
public:
void show()
{
cout << “Function Show in derived _ 1 Class (derived to
derived)” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
Derived_1_class obj3;
p = &obj3;
p->show();
return 0;
}
(a) Function Show in Base Class
Function Show in Base Class
Function Show in Base Class
(b) Function Show in Base Class
Function Show in Base Class
(c) Function Show in Base Class
(d) Compilation error. Keyword virtual cannot be used in
derived class.
Answer: (a) The keyword virtual is used the first derived class
and it is to be noted that the pointer is of type base class hence,
is the result.

53. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “Function Show in derived Class” << endl;
}
};
class Derived_1_class:public Derived_class
{
public:
void show()
{
cout << “Function Show in derived _ 1 Class (derived to
derived)” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
Derived_class *p1;
Derived_1_class obj3;
p1 = &obj3;
p1->show();
return 0;
}
(a) Function Show in Base Class
Function Show in Base Class
Function Show in Base Class
(b) Function Show in Base Class
Function Show in Base Class
Function Show in derived _ 1 Class (derived to derived)
(c) Function Show in Base Class
(d) Compilation error. Keyword virtual cannot be used in
derived class.
Answer: (b) Since the pointer of type derived class is used
properly, the code will work as expected.

54. Identify the error in the following piece of code. (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:private Base_class
{
public:
virtual void show()
{
cout << “Function Show in derived Class” << endl;
}
};
class Derived_1_class:private Derived_class
{
public:
void show()
{
cout << “Function Show in derived _ 1 Class (derived to
derived)” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
Derived_class *p1;
Derived_1_class obj3;
p1 = &obj3;
p1->show();
return 0;
}
(a) No mistake, the code will run fine.
(b) Syntax error will be thrown.
(c) ‘Base_class’ is an inaccessible base of ‘Derived_class’
and ‘Derived_class’ is an inaccessible base of
‘Derived_1_class’
(d) None of the above.
Answer: (c) The access specifier used is Private and hence
‘Base_class’ is an inaccessible base of ‘Derived_class’ and
‘Derived_class’ is an inaccessible base of ‘Derived_1_class’

55. Identify the error in the following code. (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:protected Base_class
{
public:
virtual void show()
{
cout << “Function Show in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) No mistake, the code will run fine.
(b) Syntax error will be thrown.
(c) ‘Base_class’ is an inaccessible base of ‘Derived_class’
(d) None of the above
Answer: (c) Since the access specifier is chosen to be
protected, it would throw the error “‘Base_class’ is an
inaccessible base of ‘Derived_class’”

56. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
};
class Derived_class_2:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class_2” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
Derived_class_2 obj3;
p = &obj3;
p->show();
return 0;
}
(a) Virtual keyword is used wrongly
(b) Function Show in Base Class
Function Show in derived Class
Function Show in derived Class_2
(c) Function Show in derived Class
Function Show in derived Class_2
(d) None of the above
Answer: (b) Virtual once used in the base class will be valid
all over the code.

57. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{}
};
class Derived_class:public Base_class
{
public:
void show()
{
cout << “Function Show in derived Class” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation error
(b) Show () cannot be empty in the base class
(c) Function Show in derived Class
(d) None of the above
Answer: (c) The statement in the derived class will get printed
as the function in the base class is referred as “Pure Virtual
Function”. The function, the derived class, will be re-defined
in the derived class.

58. What is the output of the following piece of code?


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{}
};
class Derived_class:public Base_class
{
public:
void show()
{}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) Illegal not to override the function in derived class,
when the base class function is virtual
(d) None of the above
Answer: (b) No error and no output as the function in derived
class has got nothing inside.

59. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{}
};
class Derived_class:public Base_class
{
public:
virtual void show()
{}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) Illegal as a function cannot be made virtual in base and
derived classes
(d) None of the above
Answer: (b) No error and no output and it is not harmful to
have same function virtual in both base and derived classes.

60. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = 0;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (c) This is demo for pure virtual function as the base
class virtual function is equated to zero and has been
overridden in the derived class.

61. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = 0;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (c) This is demo for pure virtual function as the base
class virtual function is equated to zero and has been
overridden in the derived class.

62. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = NULL;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (a) Compilation error as NULL is invalid pure
specifier. Only 0 is preferred as pure specifier.

63. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = “ZERO”;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (a) Compilation error as “ZERO” is invalid pure
specifier. Only 0 is preferred as pure specifier.

64. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show();
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (a) Compilation error. Virtual void show () is not
presented properly and it has to be equated to 0 or { } to be
used.
65. What is the output of the following piece of code? (L4)
#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = 80;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” << “ This is a demo for pure virtual function”;
}
};
int main()
{
Base_class *p;
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Compilation fault
(b) No error. No output
(c) This is a demo for pure virtual function
(d) None of the above
Answer: (a) Compilation error as 80 is invalid pure specifier.
Only 0 is preferred as pure specifier.

66. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
virtual void show() = 0;
};
class Derived_class_2:public Derived_class
{
public:
void show()
{
cout << “Function Show in derived Class_2” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class *p1;
Derived_class_2 obj3;
p1 = &obj3;
p1->show();
return 0;
}
(a) Compilation error with usage of virtual in derived class
(b) No error. No output
(c) Function Show in Base Class
Function Show in derived Class_2
(d) None of the above
Answer: (c) It is absolutely legal to use the keyword virtual
with base class or derived class and it does not matter at all.

67. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
void show()
{
cout << “Function Show in Base Class” << endl;
}
};
class Derived_class:public Base_class
{
public:
virtual void show();
};
class Derived_class_2:public Derived_class
{
public:
void show()
{
cout << “Function Show in derived Class_2” << endl;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class *p1;
Derived_class_2 obj3;
p1 = &obj3;
p1->show();
return 0;
}
(a) Syntax error.
(b) Compilation error.
(c) Function Show in derived Class_2
(d) Function Show in Base Class
Answer: (b) Compilation error. As the virtual function has
been drafted wrongly. It could be either equated to 0 or { }
should have been used.

68. What is wrong in the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() =0;
};
class Derived_class:public Base_class
{
public:
virtual void show()
{
cout << “\n” <<”Test”;
}
};
int main()
{
Base_class obj1;
Base_class *p;
p = &obj1;
p->show();
Derived_class obj2;
p = &obj2;
p->show();
return 0;
}
(a) Nothing wrong. The code will get compiled.
(b) Syntax error.
(c) No output.
(d) Compilation error.
Answer: (d) Compilation error. Cannot declare variable ‘obj1’
to be of abstract type ‘Base_class’. When a function is equated
to 0, one cannot try to create an object for that class as it
qualifies to be abstract class.

69. Which of the following are/is true about virtual function?


(L3)
(a) A virtual function gets qualified to be pure if assigned
with 0.
(b) Keyword pure is required to make a function pure
virtual function.
(c) If a pure virtual function is created in an abstract class,
there will be a slot reserved in for function in Virtual table,
with having no address being stored there in the slot.
(d) Instance of abstract class cannot be created.
Answer: (a), (c) and (d)

70. Which of the following is/are true about virtual function?


(L3)
(a) When a function gets called as virtual function, binding
happens at compile time.
(b) When a function gets called as virtual function, binding
happens at runtime.
(c) Assigning a NULL is equivalent to assigning 0 with
respect to pure virtual function.
(d) Using virtual functions will slow down the execution
speed as the binding happens runtime.
Answer: (b) and (d)

71. What is the output of the following piece of code? Also


point out the error in the code which could be logical. (L4)
#include <iostream>
using namespace std;
class Base_class {
public:
Base_class ()
{
cout << “This is a base class constructor” << “\n”;
}
~Base_class ()
{
cout << “This is a base class destructor” << “\n”;
}
};
class Derived_class : public Base_class {
public:
Derived_class ()
{
cout << “This is a Derived_class constructor” << “\n”;
}
~Derived_class ()
{
cout << “This is a Derived_class destructor” << “\n”;
}
};
int main()
{
Base_class *b;
b = new Derived_class;
delete b;
return 0;
}
Answer: The expected output would not arrive and the
following is the output one would get.
This is a base class constructor.
This is a Derived_class constructor.
This is a base class destructor.
Reasoning: If the destructor in the base class is not made
virtual, then an object that might have been declared of
type base class and instance of child class would simply
call the base class destructor without having called the
derived class destructor. This can be related and is
synonymous to the previous learning about the virtual
functions.

72. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class {
public:
Base_class ()
{
cout << “This is a base class constructor” << “\n”;
}
virtual ~Base_class ()
{
cout << “This is a base class destructor” << “\n”;
}
};
class Derived_class : public Base_class {
public:
Derived_class ()
{
cout << “This is a Derived_class constructor” << “\n”;
}
~Derived_class ()
{
cout << “This is a Derived_class destructor” << “\n”;
}
};
int main()
{
Base_class *b;
b = new Derived_class;
delete b;
return 0;
}
(a) This is a base class constructor, This is a Derived_class
constructor, This is a base class destructor
(b) This is a base class constructor, This is a Derived_class
constructor, This is a Derived_class destructor, This is a
base class destructor
(c) Compilation fault. Keyword virtual used wrongly for
destructor
(d) Syntax error
Answer: (b) Since, keyword virtual is used appropriately with
the destructor of base class, calling sequence of the destructor
would be proper.

73. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class {
public:
virtual Base_class ()
{
cout << “This is a base class constructor” << “\n”;
}
virtual ~Base_class ()
{
cout << “This is a base class destructor” << “\n”;
}
};
class Derived_class : public Base_class {
public:
Derived_class ()
{
cout << “This is a Derived_class constructor” << “\n”;
}
~Derived_class ()
{
cout << “This is a Derived_class destructor” << “\n”;
}
};
int main()
{
Base_class *b;
b = new Derived_class;
delete b;
return 0;
}
(a) This is a base class constructor, This is a Derived_class
constructor, This is a base class destructor
(b) This is a base class constructor, This is a Derived_class
constructor, This is a Derived_class destructor, This is a
base class destructor
(c) Compilation fault. Keyword
(d) Syntax Error.
Answer: (c) The compiler would throw compilation error. One
can never make the constructor virtual.

74. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class {
public:
Base_class ()
{
cout << “This is a base class constructor” << “\n”;
}
~Base_class ()
{
cout << “This is a base class destructor” << “\n”;
}
};
class Derived_class : public Base_class {
public:
Derived_class ()
{
cout << “This is a Derived_class constructor” << “\n”;
}
virtual ~Derived_class ()
{
cout << “This is a Derived_class destructor” << “\n”;
}
};
int main()
{
Base_class *b;
b = new Derived_class;
delete b;
return 0;
}
(a) This is a base class constructor, This is a Derived_class
constructor, This is a base class destructor
(b) This is a base class constructor, This is a Derived_class
constructor, This is a Derived_class destructor, This is a
base class destructor
(c) Compilation fault.
(d) Syntax error.
Answer: (a) Since the base class destructor is not made
virtual, the sequence of calling the destructor would remain as
quoted in Q.No. 71.

75. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class {
public:
Base_class ()
{
cout << “This is a base class constructor” << “\n”;
}
~Base_class virtual ()
{
cout << “This is a base class destructor” << “\n”;
}
};
class Derived_class : public Base_class {
public:
Derived_class ()
{
cout << “This is a Derived_class constructor” << “\n”;
}
~Derived_class ()
{
cout << “This is a Derived_class destructor” << “\n”;
}
};
int main()
{
Base_class *b;
b = new Derived_class;
delete b;
return 0;
}
(a) This is a base class constructor, This is a Derived_class
constructor, This is a base class destructor
(b) This is a base class constructor, This is a Derived_class
constructor, This is a Derived_class destructor, This is a
base class destructor
(c) Compilation fault. Invalid use of virtual with destructor
(d) Syntax Error
Answer: (c) Virtual cannot be used the way it has been used in
this example.

76. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Code will throw syntax error.
(b) Derived class No. 2
(c) Will this code work
(d) Compilation error.
Answer: (d) The compiler throw compilation error as there is
an ambiguity associated with the variable x. Since both the
derived classes will have copy of x, the ambiguity will raise on
using the x from one of the derived classes. This can be
avoided by virtual base class concept.

77. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error. Fault with using virtual keyword)
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (b) Since the virtual base class concept is used
appropriately, there will not be any ambiguity associated with
the code and it shall have one copy of the variable to avoid
ambiguity.

78. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error. Ambiguity raised.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Since the virtual keyword is not used with the
second derived class, it would tend to create ambiguity with
the copy of the variable. Hence, virtual keyword is expected
for the derived classes which are going to form another class
from them.

79. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class virtual Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Virtual keyword for the class in the base class is
done wrongly. For a class, virtual cannot precede the class
name.
80. What is the output of the following code? (L4)
#include <iostream>
using namespace std;
class Base_class virtual
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Invalid usage of virtual keyword with base class.
Invalid use of incomplete type ‘class Base_class’ will be
raised.

81. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived:: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Though the usage of virtual keywords are all
perfect, in the class mix_derived, we have used :: instead of :.
Hence, it is an invalid usage of the operators at an
inappropriate place.

82. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) “example() returns an int value which is not
received properly”.

83. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Since the Derived_1_class and Derived_2_class
are private by default, the access restrictions are imposed on
the mix_derived which is derived from Derived_1_class and
Derived_2_class. Hence, compilation fault would be raised.

84. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) It needs both the Derived_1_class and
Derived_2_class to be public for the mix_derived to be
working fine. Though virtual keywords and concepts of virtual
base class are properly embedded, it will throw compilation
fault.
85. What is the output of the following code? (L4)
#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Compilation error. Even in the derived class if its
access restrictions are private, one would not get access from
the main (). Hence, there would be a compilation error raised
for this code.

86. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : virtual virtual public Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
obj.example ();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (a) Virtual keyword has been specified more than
once in the Derived_1_class. Hence it is a compilation fault.

87. What is the output of the following code? (L4)


#include <iostream>
using namespace std;
class Base_class
{
public:
int x;
};
class Derived_1_class : public virtual Base_class
{
public:
Derived_1_class ()
{
cout << “\n” << “Derived Class No.1”;
}
};
class Derived_2_class : virtual public Base_class
{
public:
Derived_2_class ()
{
cout << “\n” << “Derived Class No.2”;
}
};
class mix_derived: public Derived_1_class, public
Derived_2_class
{
public:
int example()
{
cout <<”\n” <<”Will this code work” <<”\n”;
return x;
}
};
int main ()
{
mix_derived obj;
int i = obj.example();
return 0;
}
(a) Compilation error.
(b) Derived Class No. 1
Derived Class No. 2
Will this code work
(c) Will this code work
(d) Derived Class No. 1
Derived Class No. 2
Answer: (b) In this scenario, the keyword virtual can be used
before or after the class name and there would not be any
compilation fault. The code will run fine resulting in the
output as b)
9
FRIEND CLASS AND
FRIEND FUNCTIONS
Friend class and friend functions are the only members that
can access the ‘private’ data of the class. This chapter makes
you strong on the basics and usage of ‘friend’.

1. When data members of a class are to be accessed by another


class, the easiest way to achieve this is through friend class
– True or False. (L2)
Answer: True.

2. Friend functions are similar to friend class – True or False.


(L1)
Answer: False. (Friend functions are meant for functions and
not for classes.)

3. Friendship between classes are mutual – True or False. (L3)


Answer: False. (If class X is friend of Y, it does not mean
class Y is friend of X.)

4. Friendship gets inherited naturally. – True or False. (L4)


Answer: False. (No friendship will get inherited by default)

5. What is the output of the following code snippet? (L4)


#include <iostream>
using namespace std;
class base_class
{
private:
int a, b;
public:
void test ()
{
a = 1;
b = 2;
}
int calculate (base_class e1);
};
int calculate (base_class x)
{
return int (x.a + x.b) + 9 - 3;
}
int main ()
{
base_class e;
e.test();
cout << calculate (e) <<”\n”;
getchar ();
return 0;
}
(a) 8
(b) 9
(c) Compilation error
(d) Syntax error
Answer: (c) Since the data members a and b are private to the
class base_class, the access restrictions are imposed.

6. What is the output of the following code snippet? (L4)


#include <iostream>
using namespace std;
class base_class
{
private:
int a, b;
public:
void test ()
{
a = 1;
b = 2;
}
friend int calculate (base_class e1);
};
int calculate (base_class x)
{
return int (x.a + x.b) + 9 - 3;
}
int main ()
{
base_class e;
e.test();
cout << calculate (e) <<”\n”;
getchar ();
return 0;
}
(a) 8
(b) 9
(c) Compilation error
(d) Syntax error
Answer: (b) Since the keyword friend is used, the function
calculate which is made friend will gain access even to the
private members. Hence, the output is (1 + 2) + 6 = 9.

7. What is the output of the following code snippet? (L4)


#include <iostream>
using namespace std;
class base_class
{
private:
int a, b;
public:
void test ()
{
a = 1;
b = 2;
}
Friend int calculate (base_class e1);
};
int calculate (base_class x)
{
return int (x.a + x.b) + 9 - 3;
}
int main ()
{
base_class e;
e.test();
cout << calculate (e) <<”\n”;
getchar ();
return 0;
}
(a) 8
(b) 9
(c) Compilation error
(d) Syntax error
Answer: (c) Friend is to be used as ‘friend’.

8. What is the output of the following code snippet? (L4)


#include <iostream>
using namespace std;
class base_class
{
public:
int a, b;
void test ()
{
a = 1;
b = 2;
}
};
int calculate (base_class x)
{
return int (x.a + x.b) + 9 - 3;
}
int main ()
{
base_class e;
e.test();
cout << calculate (e) <<”\n”;
getchar ();
return 0;
}
(a) 8
(b) 9
(c) Compilation error
(d) Syntax error
Answer: (b) 9. Since the data members are public, there are
no access restrictions.

9. What is the output of the following code snippet? (L4)


#include <iostream>
using namespace std;
class base_class{
private:
int a, b;
public:
void read_input ()
{
a = 5;
b = 10;
}
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation error
(b) 10
(c) 15
(d) Compiler dependent
Answer: (a) Since ‘a’ and ‘b’ are private, they are not
accessible from other classes.
10. What is the output of the following piece of code? (L4)
#include <iostream>
using namespace std;
class base_class{
private:
int a, b;
public:
void read_input ()
{
a = 5;
b = 10;
}
friend class friend_class;
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation error
(b) 10
(c) 15
(d) Compiler dependent
Answer: (c) This code reveals the concept of friend class.
Since a class has been made a friend to another class, by law,
the private data members are even accessible. Hence, the
output is 15.

11. What is the output of the following piece of code? (L4)


#include <iostream>
using namespace std;
class base_class{
private:
int a, b;
public:
void read_input ()
{
a = 5;
b = 10;
}
friend class friend_class;
friend class friend_class;
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation fault
(b) 15
(c) 10
(d) No output and no error
Answer: (b) It is not wrong to have a class being made a
friend twice, but, it is a bad practice. So, it is better to avoid it.

12. What is the output of the following code snippet? (L3)


#include <iostream>
using namespace std;
class base_class{
public:
int a,b;
void read_input ()
{
a = 5;
b = 10;
}
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation error
(b) 15
(c) 10
(d) No output and no error
Answer: (b) Since the data members a and b are public, no
access restrictions would be imposed and the code will work
fine. There is no need for someone to use the friend class as
well in this case.

13. What is the output of the following code snippet? (L3)


#include <iostream>
using namespace std;
class base_class{
protected:
int a,b;
void read_input ()
{
a = 5;
b = 10;
}
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation error
(b) 15
(c) 10
(d) No output and no error
Answer: (a) Protected is the access specifier used in this
scenario hence, the data members of the base class are
accessible only by its derived class. Hence, it would result in
compilation fault.

14. What is the output of the below code snippet? (L4)


#include <iostream>
using namespace std;
class base_class{
protected:
int a, b;
public:
int d;
void read_input ()
{
a = 5;
b = 10;
d = 10;
}
friend class friend_class;
};
class friend_class{
public:
int c;
void add(base_class rd){
c = rd.a+ rd.b + rd.d;
cout << “\n” << c;
}
};
int main ()
{
int cont;
base_class rd;
friend_class rs;
rd.read_input();
rs.add(rd);
getchar ();
return 0;
}
(a) Compilation fault
(b) 25
(c) 15
(d) Syntax error
Answer: (b) Though protected, since the base_class is made
friend to friend_class, the access would not be a problem.
Output would be 25.
10
NAMESPACES
Namespace is a very small but powerful feature of C++. This
chapter throws light on the unknown powers of namespace
and its usage.

1. Say True or False. Namespaces in C++ would help the


programmer to reduce ambiguity while calling functions.
(L1)
Answer: True. Using proper namespace identifier one would
be able to appropriately call the functions. Reader can refer the
subsequent question to get an idea of what the namespaces are
meant for.

2. Predict the output of the following code snippet. (L3)


# include <iostream>
using namespace std;
namespace a_name_space{
void f1()
{
cout << “First namespace function” <<“\n”;
}
}
namespace b_name_space{
void f1()
{
cout << “second namespace function” <<“\n”;
}
}
int main ()
{
a_name_space :: f1();
b_name_space :: f1();
getchar ();
return 0;
}
(a) First namespace function
First namespace function
(b) First namespace function
Second namespace function
(c) Compilation fault
(d) Second namespace function, second namespace
function
Answer: (b) Since the scope of the function f1 is mapped
properly to both the functions, when used with appropriate
namespace name, it would call relevant functions without
ambiguity.

3. Predict the output of the following code snippet. (L4)


# include <iostream>
using namespace std;
namespace a_name_space{
int f1(int a, int b)
{
int c = a + b;
cout<<c<<” “;
}
}
namespace b_name_space{
int f1(int a, int b)
{
int c = a - b;
cout<<c<<” “;
}
}
int main ()
{
a_name_space :: f1(2,2);
b_name_space :: f1(1,1);
getchar ();
return 0;
}
(a) Compilation error
(b) 4 0
(c) 0 4
(d) 4 4
Answer: (b) Like passing parameters to the normal functions,
here we have passed arguments to the functions, identified
through appropriate namespaces.

4. Using directive will inform the compiler that the names


used in the code is from the specified namespace. – True
or False. (L3)
Answer: True. Using is a directive and it makes sure that
compiler calls the correct code from appropriate namespace.
5. What is the output of the below code snippet? (L3)
# include <iostream>
using namespace std;
namespace a_name_space{
int f1(int a, int b)
{
int c = a + b;
cout << c <<”\n”;
}
}
namespace b_name_space{
int f1(int a, int b)
{
int c = a - b;
cout << c <<”\n”;
}
}
int main ()
{
a_name_space :: f1(2,2);
getchar ();
return 0;
}
(a) 4.
(b) Compilation error
(c) 0
(d) No output
Answer: (a) No harm in having a namespace without using
the same. It may be used at a later point of time.
6. Identify the error in the following code snippet? (L4)
# include <iostream>
using namespace std;
namespace a_name_space{
int f1(int a, int b)
{
int c = a + b;
cout << c <<” ”;
}
}
namespace a_name_space{
int f1(int a, int b)
{
int c = a - b;
cout << c <<” ”;
}
}
int main ()
{
a_name_space :: f1(2,2);
getchar ();
return 0;
}
(a) Compilation error
(b) 4
(c) 0
(d) No output
Answer: (a) Redefinition of ‘int a_name_space::f1(int, int)’ is
illegal and not permitted. Hence, would result in a compilation
error.

7. What is the output of the following code snippet?


# include <iostream>
using namespace std;
namespace a_name_space{
int f1(int a, int b)
{
int c = a + b;
cout << c << “ ”;
}
}
namespace b_name_space{
int f1(int a, int b)
{
int c = a - b;
cout << c << “ ”;
}
int f1(float a, float b, float d)
{
float c = a + b + d;
cout << c <<”\n”;
}
}
int main ()
{
a_name_space :: f1(2,2);
b_name_space :: f1(5,2);
getchar ();
return 0;
}
(a) Compilation error
(b) 4 3
(c) 4 7
(d) 3 4
Answer: (b) It is very much legal and the code has both
namespace and function overloading concept used. C++
compiler is intelligent to identify the appropriate function
based on the argument types and number of arguments.

8. What is the output of the following code snippet? (L4)


# include <iostream>
using namespace std;
namespace a_name_space{
int f1(int a, int b)
{
int c = a + b;
cout << c << “ ”;
}
}
namespace b_name_space{
int f1(int a, int b)
{
int c = a - b;
cout << c << “ ”;
}
int f1(int a, int b, int d)
{
float c = a + b + d;
cout << c << “ ”;
}
}
int main ()
{
a_name_space :: f1(2,2);
b_name_space :: f1(5,2);
getchar ();
return 0;
}
(a) Compilation error.
(b) 4 3
(c) 4 7
(d) 3 4
Answer: (b) It is very much legal and the code has both
namespace and function overloading concept used. C++
compiler is intelligent to identify the appropriate function
based on the argument types and number of arguments.

9. What is the output of the following piece of code? (L3)


# include <iostream>
using namespace std;
namespace a_name_space{
int x = 4;
int y = 5;
}
namespace b_name_space{
float x = 4.2222;
float y = 5.2222;
}
int main ()
{
using a_name_space::x;
using b_name_space::y;
cout << x << “, ” << y << “ ”;
getchar ();
return 0;
}
(a) Compilation fault
(b) 4, 5.2222
(c) 4.2222, 5
(d) None of the above
Answer: (b) This is the way one can specify which variable
from which namespace one wishes to access. Using directive
is used for this purpose.

10. Predict the output of the following code snippet. (L3)


# include <iostream>
using namespace std;
namespace a_name_space{
int x = 4;
int y = 5;
}
namespace b_name_space{
float x = 4.2222;
float y = 5.2222;
}
int main ()
{
a_name_space::x=10;
using a_name_space::x;
cout << x << “\n”;
getchar ();
return 0;
}
(a) Compilation error
(b) 10
(c) 4
(d) 4.2222
Answer: (b) Using scope resolution operator, the variable x of
namespace a_name_space is altered, hence the code will work
fine.

11. What is the output of the following code? (L3)


# include <iostream>
using namespace std;
namespace a_name_space{
int x = 4;
int y = 5;
}
namespace b_name_space{
float x = 4.2222;
float y = 5.2222;
}
int main ()
{
a_name_space::x=10;
using a_name_space::x;
cout << x << “ ”;
b_name_space::y=11.2222;
using b_name_space::y;
cout << y << “ ”;
getchar ();
return 0;
}
(a) Compilation error.
(b) 10 11.2222
(c) 11.2222 10
(d) 10 10
Answer: (b) 10 11.2222. Usage of namespace and scope
resolution operators are proper in this code hence, it would
work fine.
11
TEMPLATES
Template is the most useful part of C++. Mainly because of
its ability to reuse the code any number of times. This chapter
travels across the creation and various forms of usage of
templates.

1. Templates were brought to implement which of the


following concept? (L1)
(a) Overloading
(b) Polymorphism
(c) Inheritance
(d) Generic programming.
Answer: (d)

2. Which among the following data type supports in the given


template (L1)
template <typename T>
void add(T a, T b){ }
(a) Int
(b) String
(c) Float
(d) All the above
Answer: (d)

3. Can a function template be overloaded? (L1)


(a) Yes
(b) No
(c) Possible by template argument list
(d) None of the above
Answer: (c)

4. Can operator be overloaded in Class template? (L1)


(a) Yes
(b) No
Answer: (a)

5. Is it possible to write a template in a separate cpp file? (L1)


(a) Yes
(b) No
Answer: (b)

6. Class Template names area and -> rectangle and square are
classes created using the template. Can object be created
for rectangle? (L1)
(a) Yes
(b) No
(c) Possible because it’s a class not a template
Answer: (c)

7. Class Template names area and -> rectangle and square are
classes created using the template. Can object be created
for area? (L1)
(a) Yes
(b) No
(c) Not possible because it’s not a class it is a template
Answer: (c)
8. Predict the output of the following code snippet. (L3)
# include <iostream>
# include <vector>
using namespace std;
int main ()
{
vector<int> a;
int i;
a.push_back(5);
a.push_back(3);
a.push_back(1);
for (i=0;i<3;i++)
cout << a[i] << “ ”;
return 0;
}
(a) Compilation fault
(b) 5 3 1
(c) 1 3 5
(d) No output
Answer: (b) vector <> a; is the syntax through which
templates can be handled. <> is the symbol to be used with
template code.

9. Predict the output of the following piece of code. (L3)


# include <iostream>
# include <vector>
using namespace std;
int main ()
{
int i;
vector<int> f (3,2);
vector<int> d (2,3);
f.swap(d);
for (i=0;i<f.size();i++)
cout << f[i] << “\t”;
cout <<”\n”;
for (i=0;i<d.size();i++)
cout << d[i] << “\t”;
cout <<”\n”;
return 0;
}
(a) 3 3
(b) 2 2
222333
(c) Compilation fault
(d) None of the above
Answer: (a) Using swap and templates, the contents of the
two vectors are swapped hence, the result would be ‘a’.

10. What is the output of the following code snippet? (L4)


# include <iostream>
# include <vector>
using namespace std;
int main ()
{
int i;
vector<int> f (3,’b’);
vector<int> d (2,’a’);
f.swap(d);
for (i=0;i<f.size();i++)
cout << f[i] << “\t”;
cout <<”\n”;
for (i=0;i<d.size();i++)
cout << d[i] << “\t”;
cout <<”\n”;
return 0;
}
(a) a a
(b) b b
bbbaaa
(c) 97 97
(d) Compilation error
98 98 98
Answer: (c) Since the vector<int> is the way the code has
been written, it would print the ascii value of a and b.

11. What is the output of the below code snippet? (L4)


# include <iostream>
# include <vector>
using namespace std;
int main ()
{
int i;
vector<char> f (3,’b’);
vector<char> d (2,’a’);
f.swap(d);
for (i=0;i<f.size();i++)
cout << f[i] << “\t”;
cout <<”\n”;
for (i=0;i<d.size();i++)
cout << d[i] << “\t”;
cout <<”\n”;
return 0;
}
(a) a a
(b) b b
bbbaaa
(c) 97 97
(d) Compilation error
98 98 98
Answer: (a) is the correct answer. Since the data type is
correctly associated with the vector, we have correct answer at
this attempt.

12. Predict the output of the following code snippet? (L3)


# include <iostream>
# include <queue>
using namespace std;
int main()
{
queue <int> q;
int i;
for (i=1; i<=5; i++)
q.push(i);
while (!q.empty())
{
cout <<q.front() <<” “;
q.pop();
}
cout <<”\n”;
return 0;
}
(a) Compilation error
(b) 1 2 3 4 5
(c) 5 4 3 2 1
(d) None of the above
Answer: (b) This code depicts the simplest way of
constructing queues.

13. Predict the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
int main()
{
queue <int> q;
int i;
for (i=1; i<=5; i++)
q.push(i);
while (!q.empty())
{
cout <<q.front() <<” “;
q.pop();
}
cout <<”\n”;
return 0;
}
(a) Compilation error
(b) 1 2 3 4 5
(c) 5 4 3 2 1
(d) None of the above
Answer: (a) Without having the appropriate header file
include <queue> the code will not be recognized properly by
the compiler.
12
EXCEPTION HANDLING
Errors and bugs are always a burden to a professional
programmer. Exception handling is an intelligent way to
handle the various errors and bypass them while
programming. This chapter introduces you the art of
exception handling and increase your skill set in debugging.

1. Which of the following class is the parent class for any


exception that may occur in a C++ program? (L1)
(a) Std::ParentException
(b) Std::Exception
(c) Std::bad_Exception
(d) Std::invalid_argument
Answer: (b) Std::Exception is the parent class of all the
exception classes present in C++

2. Say Yes or No: Can we declare user defined exceptions in


C++? (L1)
(a) Yes
(b) No
Answer: (a) Yes. We can declare user defined exceptions by
inheriting the Exception class

3. Predict the output of the following code snippet, given


val1=10, val2=20 (L2)
#include <iostream>
#include <exception>
using namespace std;
struct UserDefinedException : public exception
{
const char * what () const throw ()
{
return “Value 2 cannot be greater than value 1”;
}
};
int main()
{
int val1,val2;
std::cout<<”Please enter value1”;
std::cin>>val1;
std::cout<<”Please enter value2”;
std::cin>>val2;
try
{
if(val2>val1)
throw UserDefinedException();
else
std::cout<<val1/val2;
}
catch(UserDefinedException& e)
{
std::cout << e.what() << std::endl;
}
}
(a) No output
(b) Value 2 cannot be greater than value 1
(c) 0
(d) Compile error
Answer: (b) Value2 cannot be greater than value1. Try block
compares value1 with value2. When value2 is greater than
value1, we are throwing user defined exception. When we call
What() method present in user defined exception class, it
prints the output statement, Value2 cannot be greater than
value1.

4. Say Yes or No : Can we attach more than one catch block


with a try block? (L1)
(a) Yes
(b) No
Answer: (a) Yes. We can capture multiple types of exceptions
in a program. For that, we can attach more than one catch
block, each of which capturing a type of exception.

5. Which of the following exception occurs when we allocate


memory using new keyword? (L2)
(a) Std::bad_cast
(b) Std::length_error
(c) Std::out_of_range
(d) Std::bad_alloc
Answer: (d) Std::bad_alloc

6. Predict the outcome of the following program, when the


array size is 10 and index position is 11. (L2)
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
int i,index,value;
std::cout<<”enter array size”;
std::cin>>i;
int array[i];
try
{
std::cout<<”enter the array index position”;
std::cin>>index;
if(index<i)
{
cout<<”enter value”;
cin>>value;
array[index]=value;
cout<<array[index];
}
else
throw std::out_of_range(“Range Overflow”);
}
catch(std::out_of_range& e)
{
std::cout<<e.what();
}
return 0;
}
(a) – 1
(b) Range overflow
(c) Compile time error
(d) None of the above
Answer: (b) Range overflow

7. What happens when we don’t include the header file


<stdexcept> in following program? (L2)
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
int i,index,value;
std::cout<<”enter array size”;
std::cin>>i;
int array[i];
try
{
std::cout<<”enter the array index position”;
std::cin>>index;
if(index<i)
{
cout<<”enter value”;
cin>>value;
array[index]=value;
}
else
throw std::range_error(“Range Overflow”);
}
catch(std::range_error& e)
{
std::cout<<e.what();
}
return 0;
}
(a) Throws the compile time error - ‘range_error’ is not a
member of ‘std’
(b) Prints Range Overflow
(c) Prints the value of array[index]
(d) None of the above
Answer: (a) It is mandatory to include the header stdexcept in
order to use the exception classes.

8. Which of the following symbols is used in catch block in


order to make the catch block catch any type of exception?
(a) ::
(b) ??
(c) …
(d) **
Answer: (c) … ellipsis symbol is used in the catch block in
order to make it catch any type of exception.

9. Which of the following exception types doesn’t get derived


from logic_error class? (L2)
(a) Invalid_argument
(b) Domain_error
(c) Out_of_range
(d) Range_error
Answer: (d) range_error. It is derived from the class
runtime_error.

10. Predict the error of the following code. (L3)


#include <iostream>
#include <typeinfo>
struct Chocolate { virtual ~Chocolate() { } };
struct Biscuits { virtual ~Biscuits() { } };
int main()
{
Chocolate c;
try {
Biscuits& b = dynamic_cast<Biscuits&>(c);
} catch(const std::bad_cast& e)
{
std::cout << e.what();
}
}
(a) It throws a compile time error
(b) It executes without any exception
(c) It generates std::bad_cast exception and prints the
message std::bad_cast
(d) None of the above
Answer: (c) It generates bad_Cast exception as we are trying
to do a dynamic cast of a Chocolate class instance to a Biscuits
class instance.

11. Predict the output of the following code, provided a=100


and b=100 (L2)
#include <iostream>
using namespace std;
class TestException
{
int a, b;
public:
TestException(int a, int b)
{
this->a = a;
this->b = b;
}
int divide()
{
std::cout<<”a=”<<a<<”\n”<<”b=”<<b<<”\n”<<”a/b=”<<
a/b<<”\n”;
return a/b;
}
};
int main (void)
{
try
{
int a,b;
cout<<”Enter a = “;
cin>>a;
cout<<”Enter b = “;
cin>>b;
TestException obj(a,b);
std::cout<<”Trying to divide”<<”\n”;
int quotient = obj.divide();
if(quotient==-1)
throw quotient;
else
cout<<”quotient=”<<quotient;
}
catch(int quotient)
{
std::cout<<”caught an exception”<<quotient;
}
};
(a) Trying to divide
a=100
b=100
a/b=1
quotient=1
(b) Trying to divide
a=100
b=100
a/b=-1
caught an exception-1
(c) Trying to divide
a=100
b=100
a/b=1
caught an exception1
(d) None of the above
Answer: (a)

12. Predict the output of the following code, given a=100,


b=100
#include <iostream>
using namespace std;
int main (void)
{
try
{
int a,b;
cout<<”Enter a = “;
cin>>a;
cout<<”Enter b = “;
cin>>b;
std::cout<<”Trying to divide”<<”\n”;
int quotient = a/b;
if(quotient==-1)
{
throw quotient;
cout<<”after throw”;
}
else
cout<<”quotient=”<<quotient;
}
catch(int quotient)
{
std::cout<<”after catch”<<quotient;
}
};
(a) Trying to divide
(b) Trying to divide
after throw after catch
after catch
(c) after catch
(d) after throw
after throw after catch
Answer: (a) The statements after catch will not be executed,
they remain unreachable code.

13. Predict the output of the following code snippet. (L3)


#include<iostream>
using namespace std;
class Parent {
public:
Parent()
{
std::cout<<”Parent Constructor”<<endl;
}
};
class Child: public Parent {
public:
Child()
{
std::cout<<”Child Constructor”<<endl;
}
};
int main()
{
Child c;
try {
throw c;
}
catch(Child c) {
cout<<”Caught Child Exception”<<endl;
}
catch(Parent p) {
cout<<”Caught Parent Exception”<<endl;
}
return 0;
}
(a) Child Constructor
Parent Constructor
Caught Child Exception
(b) Parent Constructor
Child Constructor
Caught Child Exception
(c) Child Constructor
Parent Constructor
Caught Parent Exception
(d) Parent Constructor
Child Constructor
Caught Parent Exception
Answer: (d)
14. Predict the output of the following piece of code. (L3)
#include <iostream>
using namespace std;
void MyFunction()
{
try
{
throw 1;
}
catch (int arg)
{
cout << “int exception\n”;
throw;
}
catch (char arg)
{
cout << “char exception!\n”;
}
catch (…)
{
cout << “generic exception!\n”;
}
cout << “After Exception”;
}
int main()
{
try
{
MyFunction();
}
catch(…)
{
std::cout<<”Caught Rethrown Exception”;
}
}
(a) int exception
Caught Rethrown Exception
After Exception
(b) int exception
Caught Rethrown Exception
(c) int exception
After exception
(d) generic exception
caught Rethrown Exception
Answer: (b) There is a ‘throw’ in the catch of type int. This
makes it to throw exception in the return block of address
which leads it to print “Caught Rethrown Exception”

15. Predict the output of the following piece of code. (L3)


#include <iostream>
using namespace std;
void MyFunction()
{
try
{
throw 1;
}
catch (…)
{
cout << “generic exception!\n”;
}
catch (int arg)
{
cout << “int exception\n”;
throw;
}
catch (char arg)
{
cout << “char exception!\n”;
}
cout << “After Exception”;
}
int main()
{
try
{
MyFunction();
}
catch(…)
{
std::cout<<”Caught Rethrown Exception”;
}
}
(a) Doesn’t compile, since catch block with ellipsis should
be the last among other catch blocks
(b) generic exception
Caught Rethrown Exception
(c) int exception
Caught Rethrown Exception
(d) None of the above
Answer: (a)

16. Predict the output of the following code snippet. (L2)


#include <iostream>
using namespace std;
class Exceptiontest {
int num1, num2;
public:
Exceptiontest(int num1, int num2) {
cout << “Inside Constructor” << endl;
this->num1 = num1;
this->num2 = num2;
}
~Exceptiontest() {
cout << “Inside destructor” << endl;
}
void PrintSum()
{
cout<<”A+B=”<<num1+num2<<endl;
}
};
int main() {
try {
Exceptiontest obj(10,10);
obj.PrintSum();
throw -1;
} catch(int num) {
cout << “Caught Exception “ << -1 << endl;
}
}
(a) Inside Constructor
A+B = 20
Caught Exception -1
Inside destructor
(b) Inside Constructor
A+B = 20
Inside destructor
Caught Exception -1
(c) Inside Constructor
A+B = 20
Inside destructor
(d) Inside Destructor
A+B = 20
Inside Constructor
Caught Exception -1
Answer: (b) Since destructor is called before the control gets
transferred to catch block.

17. Predict the output of the following code. (L2)


#include <iostream>
using namespace std;
class Exceptiontest {
int num1, num2;
public:
Exceptiontest(int num1, int num2) {
cout << “Inside Constructor” << endl;
this->num1 = num1;
this->num2 = num2;
}
~Exceptiontest() {
cout << “Inside destructor” << endl;
}
void PrintSum()
{
cout<<”A+B=”<<num1+num2<<endl;
}
};
int main() {
try {
Exceptiontest obj(10,10);
obj.PrintSum();
throw true;
} catch(bool num) {
cout << “Caught Exception “ << num << endl;
}
}
(a) Inside Constructor
A+B = 20;
Inside destructor
Caught Exception true
(b) Inside Constructor
A+B = 20;
Inside destructor
Caught Exception 1
(c) Inside Constructor
A+B = 20;
Inside destructor
Caught Exception 0
(d) Inside Constructor
A+B = 20;
Inside destructor
Caught Exception -1
Answer: (b) Throwing true assigns the value 1, false will print
0.

18. Can we use throw statement to throw any kind of


exception? Say Yes or No. (L1)
(a) Yes
(b) No
Answer: (b) Yes. Any type of operand can be thrown

19. Identify the output of the following code. (L2)


#include <iostream>
#include <string>
#include<typeinfo>
using namespace std;
int main( )
{
try
{
string str1(“Except”);
string str2(“ion”);
str1.append(str2, 0, 2);
cout << str1 << endl;
}
catch (exception &ex)
{
cout << “Type: “ << typeid(ex).name() << endl;
};
return 0;
}
(a) Throws out of range exception
(b) Compiles and executes successfully printing ioExcept
(c) Throws bad_cast exception
(d) Compiles and executes successfully printing Exceptio
Answer: (d) Exceptio is the exception class for input and
output.

20. Identify the output of the following program. (L2)


#include <iostream>
#include <string>
#include<typeinfo>
using namespace std;
int main( )
{
try
{
string str1(“Except”);
string str2(“ion”);
str1.append(str2, -1, 2);
cout << str1 << endl;
}
catch (exception &ex)
{
cout << “Type: “ << typeid(ex).name() << endl;
};
return 0;
}
(a) Throws out of range exception
(b) Compiles and executes successfully printing ioExcept
(c) Throws bad_cast exception
(d) Compiles and executes successfully printing Exceptio
Answer: (a) Throws out of range exception, since we are
trying to append 2 characters from – 1 position in str2 whose
index starts from 0.

21. Predict the output of the following code snippet. (L3)


#include <iostream>
#include <string>
#include<typeinfo>
using namespace std;
int main( )
{
try
{
string str1(“Except”);
string str2(“ion”);
str1.append(str2, 3, 2);
cout<<”Str2” << str2.substr(100,10);
cout << str1 << endl;
cout << str2 << endl;
}
catch (int)
{
cout<<”Exception Caught”;
};
return 0;
}
(a) Throws compile time error
(b) Executes successfully and prints Exception Caught
(c) The program terminates
(d) None of the above
Answer: (c) The program terminates; in the above program,
there is no appropriate catch handler for catching out of_range
exceptions. The exception is thrown when substr(100, 10) is
called, but there is no matching catch to receive it. Thus, the
exception is not caught and no output.

22. Predict the output of the following code snippet. (L3)


#include <iostream>
#include <string>
#include<typeinfo>
using namespace std;
void testfunction()
{
cout<<”testfunction is called before terminating”;
}
int main( )
{
try
{
set_terminate(testfunction);
string str1(“Except”);
string str2(“ion”);
str1.append(str2, 3, 2);
cout<<”Str2” << str2.substr(100,10);
cout << str1 << endl;
cout << str2 << endl;
}
catch (int)
{
cout<<”Exception Caught”;
};
return 0;
}
(a) Executes successfully and prints Exception Caught
(b) Executes successfully and prints testfunction is called
before terminating
(c) Program terminates after calling the function
testfunction()
(d) Program terminates without calling the function
testfunction()
Answer: (c) Program terminates after calling the function
testfunction(), since we have set the terminate function, using
set_terminate. It calls the mentioned function before calling
terminate() function.

23. Say True or False. We cannot place the catch handler of a


parent class before the catch handler of the child class.
(L1)
(a) True
(b) False
Answer: True, this is why we keep the catch handler with
ellipsis at last.

24. How can we mention the compiler that, a particular


function will not propagate any exceptions. (L1)
(a) Use noexcept
(b) Use nocatch
(c) Use nothrow
(d) Use noexception
Answer: (a) Use noexcept

25. What happens when an exception reaches a function


marked noexcept? (L1)
(a) The program behaves in an unexpected manner
(b) Terminate() method will be called
(c) It throws logic_error exception
(d) None of the above
Answer: (b) Terminate() method will be called
26. Choose all that are applicable with respect to stack
unwinding. (L2)
(a) Destruction of variables happen in the opposite way as
construction
(b) This is a process to perform destruction of all
automatic variables that go out of scope after an exception
has been thrown in the try block
(c) a and b
(d) Only b
Answer: (c) a and b

27. What happens when an exception is thrown from a


function that is marked with throw()? (L2)
(a) The program may not execute correctly
(b) The exception will be caught by the catch block
present in calling code
(c) The program terminates
(d) The program will call unexpected()
Answer: (a) The program may not execute correctly

28. What is the meaning of attaching throw(type) with a


function? (L1)
(a) The function can throw any type of exception
(b) The function cannot throw exception of type type
(c) The function can throw exception of type specified
(d) None of the above
Answer: (c) The function can throw exception of type
specified.
29. Say true or false: we can’t have a finally block in a C++
program. (L1)
(a) True
(b) False
Answer: (a) True

30. When will be unexpected() function called in a C++


program? (L1)
(a) When there is more than one catch handler to handle
same type of exception
(b) When there is no catch block associated with the try
block
(c) When throw statement is not used
(d) When there occurs an exception in function which is of
different type than that of the exception specification,
unexpected() method will be called
Answer: (d)

31. Identify the statements that are correct with respect to


unexpected() function. (L2)
(a) Unexpected() calls terminate() by default
(b) It aborts the program
(c) It is called when there is an exception thrown in a
function which is of different type than that of the
exception specification
(d) b and c
(e) a and c
Answer: (d) b and c
32. Identify the error with the following piece of code. (L2)
#include <iostream>
#include <string>
#include<typeinfo>
using namespace std;
void testfunction() throw(int,bool)
{
cout<<”testfunction is called”<<endl;
throw true;
}
int main( )
{
try
{
testfunction();
}
catch (…)
{
cout<<”Exception Caught”;
};
return 0;
}
(a) No error
(b) Termination occurs
(c) Unexpected behavior
(d) Throws invalid_cast exception
Answer: (a) No error
33. Which of these keywords is used to re-throw a caught
exception? (L1)
(a) Throw
(b) Rethrow
(c) finally
(d) catch(…)
Answer: (a) Throw

34. C++ throws exceptions which are of which kind among the
following? (L1)
(a) Checked
(b) Unchecked
Answer: (b) Unchecked. In C++, all the exceptions are
unchecked. They are not checked by the compiler during
compile time. It is the programmers’ responsibility to take care
of situations.

35. Say Yes or No: Can we nest try-catch blocks in a C++


program? (L1)
(a) Yes
(b) No
Answer: (a) Yes

36. Divide by zero error has to be handled by the programmers


themselves. Say true or false. (L1)
(a) True
(b) False
Answer: (a) True. Std::overflow_error has to be thrown, after
checking if the denominator is zero.

37. Predict the output of the following program. (L2)


#include <iostream>
#include <string>
#include<typeinfo>
#include<stdexcept>
using namespace std;
int main( )
{
try
{
cout<<”Outside try”<<endl;
try
{
int numerator = 10, denominator =0;
if(denominator==0)
throw std::overflow_error(“Divide by zero exception
occured”);
else
cout<<numerator/denominator;
}
catch(std::overflow_error& e)
{
cout<<”inner catch”<<endl<<e.what()<<endl;
throw;
}
}
catch (…)
{
cout<<”outer catch”<<endl;
};
return 0;
}
(a) Outside try; after this, the program terminates
(b) Outside try
Inner catch
Divide by zero exception occurred
Outer catch
(c) Outside try
Outer catch
Inner catch
Divide by zero exception occurred
(d) Compile time error occurs
Answer: (b)

38. Choose the exception which is not handled by C++


program? (L1)
(a) Out of range exception
(b) Memory overflow exception
(c) Keyboard interrupts
(d) Invalid cast exception
Answer: (c) Keyboard interrupts. It is an asynchronous
exception, which is not supported by C++.

39. What happens when there is no exception specification


attached to a method in C++? (L1)
(a) The method can throw no exception
(b) The method can throw any type of exception
(c) The method can catch any type of exception
(d) None of the above
Answer: (b) The method can throw any type of exception

40. Say true or false. range_error and out_of_range error are


one and the same. (L1)
(a) True
(b) False
Answer: (b) False. range_error is meant to throw exceptions
when there occurs an exception in internal computations.
Out_of_range is thrown when the value is not in the expected
range of the specified type.
13
FILES
Files are external files. A C++ code has the ability to interact
with external files and manipulate them. It is very powerful as
data can be kept in record. This chapter teaches you to open,
manipulate and play with files.

1. Which of the following header file would be needed if we


want to perform read and write? (L1)
(a) fstream
(b) ofstream
(c) ifstream
(d) None
Answer: (a) fstream. fstream helps us do both read and write
operations. ofstream is meant to perform only writing and
ifstream is meant to perform only reading from file.

2. Say true or false. We need to include both ifstream.h and


fstream.h to open and read a file. (L1)
(a) True
(b) False
Answer: (b) False. It is enough if we include either of the
header files to open and read a file.

3. What is the syntax for opening and runcating a file which is


already existing? (L1)
(a) ofstream outvariable;
outvariable.open(“fullfilename.txt”, ios::out | ios::delete );
(b) ofstream outvariable;
outvariable.open(“fullfilename.txt”, ios::out & ios::flush );
(c) ofstream outvariable;
outvariable.open(“fullfilename.txt”, ios::out | ios::trunc );
(d) ofstream outvariable;
outvariable.open(“fullfilename.txt”, ios::out & ios::trunc);
Answer: (c) ofstream outvariable; outvariable.open
(“fullfilename.txt”, ios::out |ios::trunc );

4. Say true of false. It is not mandatory to close the file with


streamobject.Close() after using it. (L1)
(a) True
(b) False
Answer: (a) True. It is because, C++ automatically flushes the
file object once the scope of the stream gets over. But it is
always the best practice to close the file objects after using
them.

5. Which of the following flags is used to append data to the


existing file and also lets us move the pointer to anywhere
in the file to write? (L1)
(a) ios::add
(b) ios::app
(c) ios::ate
(d) ios::in
Answer: (c) ios::ate. Ios::add also is used to append data to
the existing file. But it lets us to add only at the end and not
anywhere else.

6. Which of the following options is the default file


positioning when we use seekg? (L1)
(a) ios::cur
(b) ios::end
(c) ios::first
(d) ios::beg
Answer: (d) ios::beg is the default option while we reposition
the file pointer.

7. Say yes or no. Can we have two file pointers to the same
file for reading? (L1)
(a) Yes
(b) No
Answer: (a) Yes. We can have as many handles as we want to
read the file.

8. Which of the following syntax moves the file pointer 250


bytes back from the end of file? (L1)
(a) fileStreamObject.seekg(250, ios::end)
(b) fileStreamObject.seekg(250, ios::cur)
(c) fileStreamObject.seekg(250, ios::beg)
(d) fileStreamObject.seekg(250, ios::first)
Answer: (a) When we use the flag ios::end, whatever value
we give in the first parameter, it takes us backwards in the file.

9. What is the output of the following piece of code? (L2)


void main()
{
int fileLength;
char * charbuffer;
ifstream ifsObject;
is.open (“test.txt”, ios :: binary );
is.seekg (0, ios :: end);
length = ifsObject.tellg();
cont<<fileLength;
}
(a) Length of the file in bytes
(b) – 1 if the file doesn’t exist
(c) Both a and b
(d) Only a
Answer: (c)

10. Which of the following functions is used to check if the


read/write operation did not fail due to any I/O error or
format error at once? (L1)
(a) StreamObject.good()
(b) StreamObject.Fail()
(c) StreamObject.Bad()
(d) StreamObject.EOF()
Answer: (a) StreamObject.good(). This method checks if the
I/O operation got succeeded without any error.

11. Say true or False. If we open a file using text stream, the
data will undergo conversion to and from ASCII, whereas
if we open a file using binary stream, there will not be any
conversion. (L2)
(a) True
(b) False
Answer: (a) True. When text mode is used, the data we insert
to the file will be saved in ASCII equivalent. For instance, if 0
is in the file, it will be stored as 48 (ASCII equivalent). If it is
in binary mode, the value 0 will be saved as 0000000 (binary
equivalent of 0). While reading the data back from file, it will
be converted from ASCII.
12. By which editor, we can open the files written using binary
stream? (L1)
(a) Notepad
(b) Wordpad
(c) MS Word
(d) Only program which was used to create/write the file
Answer: (d) Only program which was used to create/write the
file. When the file is created using binary mode, we can’t read
the content of the file using any text editor, but we can only
read it using the C++ program.

13. Random access using seekp() and seekg() in file handling


helps us to do which of the following option? (L1)
(a) Move to any byte of the file
(b) Move to any word of the file
(c) Move to any line of the file
(d) None of the above
Answer: (a) Move to any byte of the file

14. Identify the piece of code to determine the length of file in


bytes. (L2)
(a) InputFile.tellg(0, ios::end); Length = InputFile.seekg();
(b) InputFile.seekg(0, ios::end); Length = InputFile.tellg();
(c) InputFile.seekg(100, ios::end); Length =
InputFile.tellg();
(d) InputFile.seekg(0, ios::Beg); Length =
InputFile.tellg();
Answer: (b) InputFile.seekg(0, ios::end); Length =
InputFile.tellg(); first we need to move the file pointer to the
end and then we need to check the total bytes of the file.
15. Identify the line number in the below mentioned passage at
which the following program stops with? (L2)
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
char charInput;
streambuf * strbfPtr;
ofstream osObject (“test.txt”);
pbuf = osObject.rdbuf();
do {
charInput= cin.get();
strbfPtr-> sputc(charInput);
} while (charInput != ‘^’);
osObject.close();
return 0;
}
India is my country.
We find so many religions, cultures and practices in this
country. But there is unity in diversity^
Delhi, Chennai, Bangalore are metro cities.

Coimbatore is getting hotter day by day because of global


warming.
(a) 2
(b) 1
(c) 3
(d) 4
Answer: (a) 2. Once the caret (^) is encountered, the do while
loop stops processing and the program comes to an end.

16. Which of the following options determines end of file


(EOF)? (L1)
(a) while(filestr.eof() ==0) or while(!file.eof())
(b) while(filestr.eof() !=0) or while(file.eof())
(c) while(filestr.eof() ==0) or while(file.eof())
(d) while(filestr.eof() !=0) or while(!file.eof())
Answer: (b) eof() function returns 0 when there is some
character to be read from the file. It returns a non-zero number
when there is no data to be read or end of file has been
reached.

17. Identify the piece of code that determines the number of


characters in the file. (L4)
(a) fstream fsObj;
int count = 0; char charValue;
fsObj.open(“demoFile.txt”,ios : :out);
fsObj.get(charValue);
while(fsObj.eof( )==0)
{
fsObj.put(‘test’); count++;
}
Cout<<count;
(b) fstream fsObj;
int count = 0; char charValue;
fsObj.open(“demoFile.txt”,ios : :in);
fsObj.get(charValue);
while(fsObj.eof( )==0)
{
fsObj.get(ch); count++;
}
Cout<<count;
(c) fstream fsObj;
int count = 0; char charValue;
fsObj.open(“demoFile.txt”,ios : :in);
fsObj.get(charValue);
while(fsObj.eof( )==0)
{
fsObj.get(ch); count ++;
}
Cout<<count;
(d) None
Answer: (b)

18. Identify the line where we have a bug in the program


meant to reverse the content of file and print it on console.
(L2)
1. x=1;
2. file.seekg(0,ios : :end)
3. count = file.tellg();
4. while(x<=count)
5. {
6. file.seekg(x,ios : :end);
7. file.get(ch);
8. cout.put(ch);
9. x++;
10. }
(a) No error
(b) Seekg should have a negative value in the first
parameter on line 6
(c) x<=count on the line 4; it should have been x>=count
(d) x— should have been there on line 9 instead of x++
Answer: (a) The pointer is at the end and we cannot move it
in the forward direction.

19. Choose the purpose of using clear (iostate state=value)


function of the file stream. (L1)
(a) De-allocates the memory occupied by the stream object
(b) Clears the content of the file
(c) Overwrites the current value of the error state flags
with the value provided
(d) There is no clear() function associated with the file
stream
Answer: (c) If the state value is 0, then it means there is no
error.

20. Say true or false. Can we use a file stream to connect to


more than a file at a time? (L1)
(a) True
(b) False
Answer: True

21. Which file will be set when we execute the following piece
of code? (L2)
std::fstream fsObj;
fsObj.open (“fileName.txt”,std::fstream::in);
fsObj<< “test”;
(a) Good bit
(b) Bad bit
(c) Fail bit
(d) EOF bit
Answer: (c) Fail bit, since we have opened the file for reading
and we are performing write to the file.

22. Function to read the current error state. (L1)


(a) readstate()
(b) getstate()
(c) rdstate()
(d) None
Answer: (c) rdstate()

23. What does the following iostate value denote : 0010? (L3)
(a) Fail bit is set
(b) EOF bit is set
(c) Good bit is set
(d) Bad bit is set
Answer: (a) From left the bits are identified as follows. Good
bit bad bit fail bit EOF bit. When bad bit, fail bit is not
set, good bit will be set. So 1000 indicates that there is no error
in the file processing.

24. What is the following rdstate indicates: 8? (L1)


(a) Good bit is set
(b) Bad bit is set
(c) EOF bit is set
(d) None of the above
Answer: (a) Good bit is set. Binary equivalent of 8 is 1000
and it denotes that good bit is set.

25. Find the output of the following piece of code. (L3)


OutFileStreamObj.open(“FewLines.txt”);
OutFileStreamObj.write(“C++Programming”, 15);
FilePointerCurrentPosition = OutFileStreamObj.tellp();
OutFileStreamObj.seekp(FilePointerCurrentPosition -15);
OutFileStreamObj.write(“C”, 1);
(a) C Programming
(b) C+C Programming
(c) Programming C
(d) None of the above
Answer: (a) we are writing the words “C++ Programming” to
the file, after writing, the file pointer would be in the EOF
position. We are then moving the pointer to the beginning of
the file and replace C++ by C.

26. Say true or false. C++ supports reading a video file. (L1)
(a) True
(b) False
Answer: (a) True. Note: we can include opencv header file for
achieving this.

27. Which of the following I/O modes fails when we try to


open a file which is not existing? (L1)
(a) ios::nocreate
(b) ios::noreplace
(c) ios::ate
(d) ios::app
Answer: (b) ios::noreplace checks for the existence of the file.
If it doesn’t exist, then the call to open fails.

28. Identify the piece of code used to get number of lines in a


file. (L4)
(a) while(!fileInputStreamObj.eof())
{
fileInputStreamObj>>strWord;
count++;
}
Cout<<count;
(b) while(!fileInputStreamObj.eof())
{
fileInputStreamObj.getLine(strWord,255);
count++;
}
Cout<<count;
(c) while(!fileInputStreamObj.eof())
{
fileInputStreamObj.get(charVariable);
count++;
}
Cout<<count;
(d) None of the above
Answer: (b) getLine() function reads line by line. After we
call getLine(), we are incrementing the count.
29. Which of the following flags are used to calculate the
offset from the current file pointer position. (L1)
(a) ios::ate
(b) ios::beg
(c) ios::app
(d) ios::cur
Answer: (d) ios::cur

30. Identify the output of the following program. (L2)


Assume the file “InputFile.txt” has the following text:
“Learning C++ Programming on 4th may 2016”;
int digitCount=0;
ifStream ifStreamObject(“InputFile.txt”,ios::in);
while(!ifStreamObject.eof())
{
If(isdigit(ifStreamObject.get(charVariable)))digitCount++;
}
Cout<<digitCount;
(a) 40
(b) 5
(c) 7
(d) 6
Answer: (b) 5. The above piece of code checks the number of
digits in the file InputFile.txt. in the file, there are 5 digits - 4,
2, 0, 1, 6

31. Identify the piece of code which we can use in a program


to determine the number of words starting with S in the
file InputFile.txt (L4)
(a) ifstream finObj;
char wordInFile[50]; int len=0;
finObj.open(“InputFile.TXT”);
while(!finObj.eof())
{
finObj>>wordInFile;
len = strlen(wordInFile);
if (wordInFile[len]==’S’) count++;
}
(b) ifstream finObj;
char wordInFile[50];
finObj.open(“InputFile.TXT”);
while(!finObj.eof())
{
finObj>>wordInFile;
if (wordInFile[1]==’S’) count++;
}
(c) ifstream finObj;
char wordInFile[50];
finObj.open(“InputFile.TXT”);
while(!finObj.eof())
{
finObj>>wordInFile;
if (wordInFile[0]==’S’) count++;
}
(d) ifstream finObj;
char wordInFile[50];
finObj.open(“InputFile.TXT”);
while(!finObj.eof())
{
finObj>>wordInFile;
if (wordInFile[1]==’S’) count—;
}
Answer: (c)

32. What is the output of the following piece of code? (L3)


ifstream finPlayerFile;
finPlayerFile.open(“Players.TXT”);
char testWord[10];
int wordCunt=0;
while(!finPlayerFile.eof())
{
finPlayerFile >> testWord;
if(strcmpi(testWord,”Sachin”)==0)
wordCunt++;
}
cout<<wordCunt;
finPlayerFile.close();
(a) Program doesn’t compile.
(b) In the players.txt file, number of word equals to
‘Sachin’.
(c) In the players.txt file, number of word equals to
‘testWord’.
(d) Prints the word Sachin as many times as present in the
file Players.txt file.
Answer: (b)
33. Say true of false. C++ supports read/write to be performed
on Excel files. (L1)
(a) True
(b) False
Answer: (a) True.

34. Predict the functionality of the following piece of code.


(L3)
const char* testPtr = “testfileName.txt”;
ifstream filePtr(testPtr, ifstream::in);
filePtr.exceptions(ifstream::eofbit|ifstream::failbit);
try {
char ch;
while (file.get(ch)) {
//Some logic to process ch
}
}
catch (ifstream::failure& exObj) {
if (filePtr.rdstate() & ifstream::eofbit) {
cout << “End of file reached.” << endl;}
}
(a) When failbit is set, it generates it throws exception and
prints “End of file reached”
(b) When End of file is reached, it throws exception and
prints “End of file reached”
(c) a or b
(d) a and b
Answer: (c)
35. Say yes or no. Can we read the filename from an array of
strings? (L1)
(a) Yes
(b) No
Answer: (a) Yes. We can create fstream/ifstream object from
an array of file names.
14
MACROS AND INCLUDE
DIRECTIVES
Macros are user defined substitutes. It is done by the
preprocessor. This chapter introduces the usage of macros and
the preprocessor directive usage in coding.

1. Which of the following characters are only allowed to


appear before a pre-processor directive? (L1)
(a) ;
(b) :
(c) ?
(d) <whitespace>
Answer: (d) <whitespace>. No other character is allowed to
be present before a preprocessor directive. In case present, it is
a compilation error.

2. Choose the appropriate definition about preprocessor


directives. (L1)
(a) These directives are meant to give instruction to the
compiler to preprocess the information during
compilation.
(b) These directives are meant to give instruction to the
compiler to preprocess the information before compilation.
(c) These directives are meant to give instruction to the
compiler to preprocess the information after compilation.
(d) None of the above.
Answer: (b)
3. Say true or false. Preprocessor directives are C++
Statements. (L1)
(a) True
(b) False
Answer: (b) False. They are not statements; hence they are
not terminated by a semicolon.

4. Macros can only be defined using the pre-processor


directive ‘#define’ – True or False.
Answer: True.

5. Macros are expected only to be written in upper case letters


like #define PI 3.14 – True or False.
Answer: True. But, not mandatory. It is a good coding practice
to have all the macro in upper case letters.

6. A macro cannot be nested with another macro – True or


False.
Answer: False. It is possible to nest a macro with another.

7. Predict the output of the following code.


#include <iostream.h>
using namespace std;
#define PI 3.14
#define RADIUS 10
int main ()
{
cout << “the area of square is”<< PI*RADIUS*RADIUS;
return 0;
}
(a) 3.14
(b) 10 (c) 31.4
(d) 314
Answer: (d) 314. The output statement will be replaced as
follows before being compiled. 3.14*10*10. So, it produces a
result 314.

8. Predict the output of the following code.


#include <stdio.h>
#define SQ(p) p*p
void main() {
int val=4;
printf(«\nSQ(val+4)=٪i»,SQ(val+4));
}
(a) 64
(b) 256
(c) 24
(d) None of the above
Answer: (c) 24. The moment the compiler sees the
SQ(something), it is replaced as SQ(something)*
SQ(something). So, SQ(val+4) becomes, val+4*val+4,
4+4*4+4, which is then evaluated to 4+16+4 which is equal to
24.

9. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# define PI 3.14
int main ()
{
int r=5;
cout <<”\n” << PI*r*r <<”\n”;
getchar ();
return 0;
}
(a) Compilation error
(b) 78.5
(c) 25
(d) None of the above
Answer: (b) 78.5. The macro gets expanded and instead of PI
it would be 3.14 * r* r. Hence, the answer is 78.5.

10. Which of the following symbols help you to write


preprocessor directives which spans across more than one
line? (L3)
(a) /
(b) ^
(c) \
(d) None of the above
Answer: (c) \ (backslash) this character lets you extend the
preprocessor directives across multiple lines.

11. Say True or False. We can declare a preprocessor directive


without giving the token-string. (L4)
(a) True
(b) False
Answer: True. We can declare the macros without token
string, during conditional compilation, using #ifdef, #ifundef,
etc.
12. Say true or false. Macro directives are not case-sensitive.
(L2)
(a) True
(b) False
Answer: false. Just like any other identifier in C++, macro
directives are also case sensitive.

13. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# DEFINE PI 3.14
int main ()
{
int r=5;
cout <<”\n” << PI*r*r <<”\n”;
getchar ();
return 0;
}
(a) Compilation error
(b) 78.5
(c) 25
(d) None of the above
Answer: (a) It is # define and not # Define. Hence, the
compiler would return an error message.

14. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# define PI 3.14
# define radius PI*r*r
int main ()
{
int r=2;
cout <<”\n” << radius <<”\n”;
getchar ();
return 0;
}
(a) Compilation error
(b) 12.56
(c) 4
(d) None of the above
Answer: (b) Nesting the macros is a good practice and is
followed quite consistently in the industry. Hence, the output
would be 3.14 * 2* 2 = 12.5.

15. What is the output of the following code snippet? (L3)


# include <iostream>
using namespace std;
# define radius PI*r*r
# define PI 3.14
int main ()
{
int r=2;
cout <<”\n” << radius <<”\n”;
getchar ();
return 0;
}
(a) Compilation error
(b) 12.56
(c) 4
(d) None of the above
Answer: (b) The order of macros in the definition area does
not matter, as we have shown here. Radius is defined first. But
it has PI, which is defined next. This is legal and shall have no
impact in the code.

16. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# define calculate_sum(a,b) (a+b)
int main ()
{
int x = 4, y = 6;
cout <<”\n” << calculate_sum (x,y);
getchar ();
return 0;
}
(a) 5
(b) 10
(c) Compilation error
(d) No output
Answer: (b) X,Y would be passed on to the calculate_sum
and hence 10 would be the result.
17. What is the output of the following code snippet? (L2)
# include <iostream>
using namespace std;
# define calculate_sum(a,b) (a+b*a-b)
int main ()
{
int x = 4, y = 6;
cout <<”\n” << calculate_sum (x,y);
getchar ();
return 0;
}
(a) Compilation fault
(b) 22
(c) – 20
(d) 20
Answer: (b) The macro would be expanded as a+ (b * a) -b =
4 + (4 * 6) – 6 = 4 + 24 – 6 = 22.

18. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# define calculate_sum(a,b) (a*b*a-b)
int main ()
{
int x = 2, y = 2;
cout <<”\n” << calculate_sum (x,y);
getchar ();
return 0;
}
(a) 7
(b) 6
(c) 8
(d) None of the above
Answer: (b) Macro gets expanded as (2*2*2) – 2 = 6.

19. What is the output of the following code snippet? (L2)


# include <iostream>
using namespace std;
# define add(x) (x * x * x)
int main ()
{
int a;
int b = 2;
a = add (b+2);
cout <<”\n” <<a <<”\n”;
getchar();
return 0;
}
(a) 10
(b) 12
(c) 20
(d) Compilation fault
Answer: (b) 12. It is evaluated as (b + 2 * b + 2 * b + 2), ( 2 +
2 * 2 + 2 * 2 + 2), (2 + 4 + 4 + 2) which is evaluated as 12.

20. Identify the output of the following piece of code? (L3)


#include <stdio.h>
#define SQ(p) p*\p
#ifndef ARRAY_SIZE
#define ARRAY_SIZE 50
#elif ARRAY_SIZE>=50
#undef ARRAY_SIZE
#endif
int main() {
printf(“tbl size=%i”,ARRAY_SIZE);
return 0;
}
(a) Compile error
(b) ARRAY_SIZE will be undefined no error will be
thrown
(c) 50
(d) – 1
Answer: (c) 50.

21. What happens when a preprocessor identifier appears in a


comment statement in C++? (L3)
(a) The statement is not evaluated. It is ignored
(b) The statement will be evaluated
(c) It leads to a runtime error
(d) None of the above
Answer: (a) The statement is not evaluated. It is ignored.
Similar to this, if the identifier appears as part of string literal,
it is not replaced with the token string.

22. What happens when there is no token string associated


with the #define preprocessor directive? (L3)
(a) It generates a compile-time error
(b) It generates a runtime error
(c) Substitutes junk value
(d) Removes all occurrences of the particular identifier
from the source file.
Answer: (d)

23. Identify the error (if any) in the following code snippet.
(L4)
#include<iostream>
#define product( f1, f2 ) ( f1 * f2 )
#define product( a1, a2 ) ( a1 * a2 )
int main() {
std::cout<<product(100,200);
return 0;
}
(a) Product is declared twice. It generates compile-time
error
(b) No error. Prints 20000
(c) Generates runtime error
(d) Prints junk value
Answer: (b) No error. Prints 20000. There will be warning
issued saying, <identifier> redefined.

24. Predict the error/output of the following code snippet. (L5)


#include<iostream>
#define type floa##t
type a = 10000;
int main() {
std::cout<<a;
return 0;
}
(a) Error
(b) Float
(c) Unpredictable
(d) 10000
Answer: (d) 10000. ## is token pasting operator. This operator
merges the arguments present on either side of it. Floa##t will
merge ‘floa’ and ‘t’, hence it becomes float. So, type a=10000
is similar to float a=10000. Hence, it generates no error.

25. Say Yes or No. The order of execution of multiple token


pasting operators in the same preprocessor directive is
undefined. (L1)
(a) Yes
(b) No
Answer: (a) Yes. When there are multiple token pasting
operators or stringizing operators, the order of execution is
undefined.

26. Identify the output of the following code. (L5)


#include <iostream>
#define multipleTPOperator i##n##t m ##ain()
multipleTPOperator
{
std::cout<<”test token pasting operator”;
}
(a) Test token pasting operator
(b) Compile error, since there is a space between ‘m’ and
‘ain’
(c) Runtime error
(d) None of the above
Answer: (a) Test token pasting operator. Token pasting
operator generally ignores whitespaces. So, the space between
‘m’ and ‘ain’ is ignored and they are merged as main.

27. Identify the output of the following code. (L3)


#include <iostream>
#define LENGTH 10
#define BREADTH 20
#define AREA LENGTH*BREADTH
int main()
{
std::cout<<AREA;
return 0;
}
(a) 20
(b) 30
(c) 2
(d) 200
Answer: (d) 200.

28. Which of the following macro is used to test the


duplication in header file/ preprocessor directive inclusion.
(L3)
(a) #Ifdef and #ifndef
(b) #include
(c) #define
(d) #elif
Answer: (a) #ifdef and #ifndef are used to test the occurrence
of preprocessor directives.

29. Identify the output of the following code. (L5)


#include <iostream>
#define CONVERT(Z) #Z
int main()
{
std::cout<<CONVERT(C++ PROGRAMMING IS VERY
EFFICIENT);
return 0;
}
(a) Error since the string in output statement is not covered
with “”
(b) No error, prints C++ PROGRAMMING IS VERY
EFFICIENT
(c) Z
(d) None of the above
Answer: (b) # is the stringizing operator. It converts the
parameter passed to it to a string literal.

30. Identify when the following code will fail. (L4)


#include <iostream>
#ifdef MULTIPLY
#error “It is not must to define MULTIPLY”
#endif
int main()
{
std::cout<<MULTIPLY(10,10);
return 0;
}
(a) It fails when there is no macro definition for
MULTIPLY, with the error, ‘MULTIPLY’ was not
declared in this scope’.
(b) If fails when there is a macro definition for
MULTIPLY, with the error “It is not must to define
MULTIPLY”.
(c) Both ‘a’ and ‘b’.
(d) It doesn’t fail at any cost.
Answer: (c) When we have defined MULTIPLY, it throws
user defined error It is not must to define MULTIPLY. When
we have not defined MULTIPLY, the call to the macro in
main() fails.

31. What is the difference between enclosing the header file in


angled bracket and enclosing it in double quotes. (L2)
(a) There is no difference
(b) The difference lies in the search location for the header
file
(c) The difference lies in the way the file contents are
pasted on to the code
(d) None of the above
Answer: (b) The difference lies in the search location for the
header file. When we enclose the header file in double quotes,
the file will be searched in the place where the source file is
present. On the other hand if it is enclosed in the angled
bracket, the file will be looked upon in the places designated
by the compiler.
15
CONCEPTUAL THEORY
In most of the interviews there are theoretical and oral
questions from C++ and OOP. So this part will be helpul in
making you strong in all the cocepts explained above.

1. What are tokens? How many are there in C++?


Answer: The smallest elements of the program that are
reasonably correlated by collection of characters to form
tokens. There are 5 types of tokens.
9 Keywords
9 Identifiers
9 Literals
9 Punctuators
9 Operators

2. Give the precedence of operators in C++?


The precedence of operator in C++ is followed to maintain the
standards for operators sequence while performing
calculations. The list of precedence is as followed and the
list is classified based on the associativity rules.

Category Associativity Name of the Operators Symbols


/Keywords

Class 1 No Associativity Scope Resolution ::

Class 2 Left to Right Member selection (object or . or –>


Associativity pointer) []
Array subscript ()
Function call ++
Postfix increment ––
Postfix decrement
Type name typeid( )
Constant type conversion const_cast
Dynamic type conversion dynamic_cast
Reinterpreted type conversion reinterpret_cast
Static type conversion static_cast

Class 3 Right to Left Size of object or type Sizeof


Associativity Prefix increment ++
Prefix decrement –
One’s complement ~
Logical not !
Unary negation -

Unary plus +
Address-of &
Indirection *
Create object New
Destroy object Delete
Cast Cast: ()

Class 4 Left to Right Pointer-to-member (objects or .* or –>*


Associativity pointers) *
Multiplication /
Division %
Modulus +
Addition -
Subtraction <<
Left shift >>
Right shift <
Less than >
Greater than <=
Less than or equal to
>=
Greater than or equal to ==
Equality !=
Inequality &
Bitwise AND ^
Bitwise exclusive OR |
Bitwise inclusive OR &&
Logical AND ||
Logical OR

Class 5 Right to Left Conditional ?:


Associativity Assignment =
Multiplication assignment *=
Division assignment /=
Modulus assignment %=
Addition assignment +=
Subtraction assignment –=
Left-shift assignment <<=
Right-shift assignment >>=
Bitwise AND assignment &=
Bitwise inclusive OR |=
assignment ^=
Bitwise exclusive OR
throw
assignment
throw expression

Class 6 Left to Right Comma ,


Associativity

3. What are arithmetic operators? Name them in the order of


their precedence?
9 Arithmetic Operators of C++ are
9 Addition +
9 Subtraction -
9 Multiplication *
9 Division /
9 Modulus %
The order of precedence for arithmetic operator is given
below.

Order of Precedence Operators

Function call ()

Multiplication *
Division /
Modulus %

Addition +
Subtraction -

4. How is type definition done?


The typedef is a keyword that informs the complier to redefine
the existing data types in C++ program to their own terms
of data types without any meaning change.
Syntax: typedef exisitingdata type newdata type
Example: typedef int Distances

5. What is user defined data type? How is it useful?


User-Define Data Types are:
9 Structure
9 Classes
9 Typedef
9 Enumeration

Structure: To collect the data of various other data types and


process together as one single entity. It starts with keyword
called Struct and is followed by user defined type.

Classes: The purpose of this data type is for reusability, the


program can have its own class with Class Keyword. The
class consists of data members and member function
enclosed within parenthesis { }

Typedef: The typedef is a keyword that informs the complier to


redefine the existing data types in C++ program to their
own terms of data types without any meaning change.
Enumeration: This Data Type provides the integer constant by
specifying in terms of identifiers or variables (names), thus
the integer constants referred by variables are called
Enumeration. By default it starts at zero (0). The keyword
used is enum.

6. For a program with no object oriented concept involved,


which language should be preferred C or C++?
This is a very hypothetical question. If object orientation is
required and the programmer is familiar with C++, it is
always preferred to go with C++. It is by the very basic
intuition, C++ is advanced than C and hence would be
preferred by that way too.

7. What are the three basic concepts of Object oriented


programing?
The three basic concepts of OOP

i. Encapsulation

ii. Inheritance

iii. Polymorphism

8. What is a class? What is the relationship between class and


object?
A class is nothing but a group of related objects aligned
together. Or, multiple objects together form a class. An
object will be an instance of a class too. Members of the
structure are public by default whereas members of the
class remain private.
9. What is the difference between class and structure?
Class is always seen as an advancement of the structure. There
are few major differences between them. Class uses the
constructor and destructor. Structure does not use
constructor or destructor. Class has scope and accessibility
which is missing in structures. Also the OOP concepts are
supported only in class.

10. What is the size of an empty class?


The size of an empty class is always 1 byte. An object can be
created for a class even though it is empty. So, to hold that
object, minimum amount of memory required is 1 byte.
One can try running the below piece of code to get a clear
visibility.
#include <iostream>
using namespace std;
class function_echo
{ };
int main(void)
{
function_echo foo;
cout <<”\n” <<sizeof(foo);
return 0;
}

11. State few object oriented programming languages.


1. Small Talk
2. C++ (Not fully object oriented)
3. Java (Pure object oriented language)
4. Python
5. Lingo
6. Perl (From Version 5.0)
7. Python

12. How is C different from C++? State 5 points.

C C++

C++ is an Object oriented


C is the procedural language, i.e., it is a POP
programming language.

Data is not so secured in the case of C programming


Data hiding is supported C++.
where it is highly secured in C++.

C language is fully function driven. C++ is fully object driven

C++ follows a bottom-up


C programming follows a top-down approach
approach.

Function overloading is
Function overloading is not permitted in C
supported in C++

13. How is C++ different from Java? State 3 points.

C++ Java

C++ support operator Java does not support operator overloading.


overloading.

C++ has the support for Java does not have the concept of pointer.
pointers.

Garbage collection is not Java has got a support for garbage collection, which will
supported in C++. automatically free the memory.

14. What are basic features supported in object oriented


languages?
Polymorphism, virtual functions, inheritance, inline functions,
etc. are supported in object oriented languages.
15. What is an object?
Anything that can be seen in real world can be referred to as
objects. Object can also be referred as instance of class.
Alternatively, group of similar objects forms a class.

16. How can someone identify something as an object?


There are three basic things to be remembered about an object.
It has
9 attributes
9 behavior and
9 identity.

With these three one can identify an object.

17. What is encapsulation?


Enfolding of state and behavior into single unit, this process is
known as encapsulation. Encapsulation can be achieved
using a keyword called Class.

18. What was the older name of ‘C++’?


C++ was originally called C with classes. Later on it got
changed as C++.

19. Name some real time-objects and give their attributes.


A table for an instance. It has a name called Table. It will have
a color. It will have size and behavior. Any object will
have these, by default.
20. Is there any difference between ‘printf’ and ‘cout’?
Printf () is a function whereas cout is not a function. Cout
depends on the operator overloading concept by using <<
operator whereas printf is no way like that. Cout is always
regarded as more extensible in nature as it is easier to
work with any data type. Also, the formatting and related
stuff remain very easy with respect to cout where it
remains complex in printf.

21. What is IOSTREAM? How is it used?


IOSTREAM is like stdio.h in C programming. IOSTREAM
defines the standard input/output services for the C++
program. One cannot use cout or cin without having the
iostream header file included.

22. Can a structure be a member of a class?


Yes

23. Can a structure be defined inside a class? If so what will be


its scope?
Yes the structure can be a member of the class and it should be
in the public scope so that the return type is publicly
visible. Otherwise will throw an error.

24. Can a file object be a member of a class?


No

25. Can a C++ program have two main functions? If so which


will be executed first?
No. The compiler won’t compile if it has 2 main methods. It
throws error saying “redefinition of ‘int main ()‘ ”.

26. What are predefined functions? Where are they defined?


The predefined function are some standalone functions of C++
Library (like cmath or cstdlib) that are declared in the
header files using pre-processor directives. Predefined
functions are listed below.
9 sqrt
9 pow
9 abs
9 exit
9 assert

27. Can a program be executed without header files included?


No, it throws an error. The program should include header files
which are like standards to define for writing a program.
Therefore, the program should always begin with the
header files.
28. Is it possible to edit a header file from standard C++
library?
No, we can’t edit the header files.

29. Is command line arguments allowed in C++? Give a small


snippet to use it?
Yes, it is allowed to be used in C++ for DOS mode, i.e.,
command prompt mode. DOS does not support the GUI
and so command prompt is the only option to interact.
argc and argv two very important things to learn when talking
about command line arguments.
argc tells total number of arguments that it holds and is passed
to main function and it is of integer type.
argv[] tells the actual number of arguments passed to the main
function and it is of character type.
An example is presented below.

30. Can classes communicate data among them? If so, how?


Yes, they can communicate each other’s data among
themselves using Forward Declaration. That is include the
header files with the name of the other class which is
needed. The following snippet shows an example for
forward declaration where there are 2 classes called RAIN
and ORDERPIZZA. They include header file of other
classes where they need to communicate the data.

31. How to compile different files each with a class, and an


independent file with ‘main’ class?
In C++ we save classes or main function in separate files and
compile them separately finally linking them to get
executable as follows:
9 g++ -c grace.cpp
9 g++ -c main.cpp
9 g++ main –o grace.o – o samples
and execute the samples files as follow
. /samples

32. What are the modifiers available in C++?


The modifiers in C++ are:
9 Signed
9 Unsigned
9 Long
9 Short

33. Can a variable declaration have a modifier and variable


name alone skipping the data type?
Yes, the variable declaration can have modifier and can have
data type skipped for that variable. The variable take
Integer data type by default.

34. Can two classes with same name exists in different scope?
No two classes with the same name can exist with same name
even in different scope. It throws an error “redefinition of
‘class name’” error during compilation.

35. Can two classes with same name and same object name
(from different scopes) interact with each other?
It throws an error saying “redefinition of class ‘class name’”
for having same class name even though with different
scope calling from same object.

36. Can a class have a function named main()?


A class cannot have a function name “main”. The compiler
would throw error for this.
37. Is class a data type? If so, why it is preferred?
Yes, class is user defined data type. Class ensures good re-
usability. Also, the name of the class can be decided by the
programmer (though few restrictions like main cannot be
the class name).

38. Can an access specifier be defined twice (i.e., can a class


have two ‘public’ or ‘private’ or ‘protected’ part)?
Yes, a class can have access specifier defined twice. The
program execution takes place correctly without any error.
But, this does not serve any purpose and can be avoided.

39. How many header files are present in C++ standard and
how many of them are borrowed from C standard?

33 header files are specific to C++ and 18 files are borrowed


from C standard.

40. Is it possible to create a header file by a user? If so how?


Yes, it is possible to create a header file. One can include the
created header file by using # include “yourfile.h”.
Standard header files as iostream will be included as #
include <iostream>.

41. Can a ‘this’ pointer of a class be used in another unrelated


class?
The “this pointer” of one class cannot be used by other class.
The other class is totally unaware of this keyword called
‘this’ hence, is restricted.
42. What is pointer to an object? How can the members be
accessed using this pointer to the object?
Pointer is a variable that holds address of any given object or
data types. The member of class is accessed by “this”
pointer as follows:
this->pfun()
(*this).pun()

->is also called array of pointer

43. What is the restriction imposed on the programmer while


using the “this” pointer?
“this” pointer cannot be used with static members of class. It
will flash a linker error!!

44. Who all can access the protected members of a class?


Protected members can be assessed by their own class and any
derived class but cannot be accessed outside the derived
class.

45. What is a ‘this pointer’? How to use it?


‘this pointer’ is a pointer that points the current object to its
own address space. It is used by using a keyword called
‘this’. Suppose that there are 5 objects
(ob1,ob2,ob3,ob4,ob5) for a class named “Area_Volume”.
The class has methods for calculating volume of cone and
area of circle. The five objects keep accessing the member
function one after the other for various purposes. the
“Area_Volume” class wants to keep track of the objects
that currently access the member functions. This is
possible with the help of a pointer called “this” in C++. It
holds the address of the object that called the member
functions. Whenever a method call occurs, the address of
the object is passed to ‘this’ pointer automatically.

46. Can a constructor of one class be present in a different


class? Will there be some errors in this?
The constructor of base class is getting automatically available
in the derived class due to the very property of inheritance
and it would not throw any error.

47. Can a subclass contain the constructor of the outer class?


The subclass contains the constructor of the outer class and it
very obvious.

48. How many overloaded constructors can a class have?


There is no such limit. Overloading can happen any number of
times. One should make sure that the parameters are
different in terms of number or type or order.

49. Can an overloaded function be called explicitly from


another member function?
Overloaded function is nothing but a member function. Hence,
a member function can call other member function.

50. How many parameters can a constructor have? Can these


be of different types?
A constructor can have any number of parameters. It can also
be different in type and order of parameters.
51. Even when there is an explicit simple constructor defined,
will the implicit constructor be called and then the
explicitly defined constructor is called?
Implicit constructor gets called only when there is no explicit
constructor defined.

52. Does the implicit constructor initiate all object variables


value to 0 or NULL?
Depending on the data type the implicit constructor would
initiate the object variables to 0 or NULL.

53. What is the primary work of a constructor and destructor?


Constructor is called by compiler when an object is
instantiated. Destructor is called when the object gets
deleted or the object gets out of scope. Both the
constructor and destructor behaves like a normal member
function of the class. As the name suggest, the compiler
allocates memory for the object while calling constructor,
whereas the memory is refreshed or cleaned while
destructor is called.

54. Can a destructor be recursed?


No. It is not possible.

55. Can a destructor be called explicitly by an object?

Yes it can be called. But it has no significance.

56. What the amount of memory required to have int pointer


and float pointer?
Any pointer in C and C++ will need only 4 bytes of the
memory. Be it integer or float or character, it does not
matter.

57. Why destructors are not used in Java while it has found lot
of usage in C++?

Since garbage collection feature is enabled in Java, there is no


need for someone to use destructors.

58. C++ is always spotted as object driven while C is seen as


function driven. Explain this.

C++ is fully object driven i.e. objects are the fundamental


building blocks. But, in the case of C language, it is fully
function driven. Functions act as the fundamental blocks
in C.

59. What happens in an object declaration?

When an object is declared, the constructor in the class will be


called that will be performing the initialization of data
members.

60. Can an object be passed as an argument to functions?


(Yes/No).

Yes, very well. (Few examples are covered in the sections


earlier.)

61. How to call the static members of the class? Can objects be
used for doing so?

Static members can be called using the class name itself. It is


done with scope resolution operator. For example, let fun()
be a static member of the class c1. Then call the function
like c1::fun(). Never try using the object to call static
functions. It will throw compile time error.

62. Explain the mechanism of passing and returning objects to


and from the functions.

When an object is passed and returned, a copy of the object is


passed to and from the function. Call-by-value is the
mechanism followed in this scenario.

63. What is inheritance?

Inheritance is the ability of one class to inherit properties from


another class.

For example: A derived class inherits the properties of a base


class.

Here, CAR is base class or super class or parent class. From


that base the inheritance will happen and will create the
derived classes SEDAN and SUV.

64. What are all the types of classes?

There are five types of classes. They are:


9 Base class
9 Derived class
9 Nested class
9 Local class and
9 Incomplete class

65. What is a local class?

Local class is a class type declared with in a function


definition. A local class type name can only be used in the
enclosing function. All the methods of the local class have
to be declared only within the class.

66. How is scope resolution operator useful?

Scope will allow a program to refer an identifier which is


declared in the global space with having the same
identifier hidden in the local scope.

67. How will you compile a C++ program in gcc?


g++ -o <executable_file_name><cpp_file_name.cpp>

68. How is Inline function useful?

In case a function is getting called so many times in a


particular program it has to waste a lot of time in passing
the control, exchanging values, etc. Instead of wasting
time in this way, if an inline function is called, the
compiler inserts the full code (function) at the calling
place and the time will be saved.

69. What is the difference between inline function and macro?

Inline functions are seen as a request which may or may not be


respected by the compiler and all the inline requests are
handled by the compiler. But, macro is handled by
preprocessor and it gets expanded even before the
compilation.

70. What is the role of a constructor in a C++ program?

The sole aim of a constructor is to initialize the objects and


destructor stands exactly opposite to it.

71. Can any other member function of a class have ‘~’


operator as prefix?

No it cannot be used. If it is used there wont be any errros, but


when calling it errors come. It throws “expected class-
name before ‘(’”. This treats the call as a call for
destructor.

72. Can a subclass contain the outer class’ destructor or


constructor?

No. Actually when trying so, it is treated as a new function


without return type. So throws appropriate errors.

73. Is there any change in internally calling a destructor and


explicit call of a destructor?

No. Both implicit and explicit calling of destructor de-


allocates the memory of the associated object.

74. Can a variable have multiple storage classes?


No. It gives error “conflicting specifiers in declaration”.

75. What is the significance of using ‘auto’ storage class?


There is no significance for the ‘auto’. Actually, all local
variables are by default ‘auto’ so it has no significance in
usage. The significance of being ‘auto’ is to release the
unwanted memory held after usage.

76. What is ‘register’ used for?

Using ‘register’ in declaration requests the compiler to store


the variable in CPU register instead of RAM. So it stays in
memory even after completion of program and is faster.
But allocating register completely depends on the
processor.

77. How is ‘static’ significant?

It helps in creating a variable that acts as a common attribute


for all objects of the class. Additionally it helps in having a
‘count’ of objects and constant valued attributes.

78. How will encapsulation of a class take place when it has


‘static’ members?

When an object its created, it gets initial 1 byte memory. Then


the compiler allocates memory for all non-static members
of the class and links it to the memory of the object. Also
the remaining ‘static’ member’s memory is also associated
to the particular object.

79. Can a static function use a non-static global variable?

Yes it can use any variable outside class scope. But inside
class scope should use only static variables.

80. Can a ‘private’ static member be called outside? Will the


same syntax work?
Consider this code:
#include<iostream>
using namespace std;
class base
{
static int b;
}S;
int base::b = 8;
int main()
{ cout<<base::b;}

It throws error ‘int base::b’ is private. Private static members


cannot be accessed.

81. How is storage class different from modifiers?

Storage classes are used to modify the storage characteristics


of the variable. While modifiers are used only to modify
the usage characteristics of the variable. All variables with
or without modifiers have the same storage property. All
are ‘auto’ by default.

82. Can a variable have a storage class and modifier together?

Yes. It can have both storage class and modifier. As they


change independent properties, it is allowed.

83. Can a variable declaration have a storage class and


variable name alone skipping the data type?

No. In declaration after storage class compiler expects a type


name. On such usage variable name will be considered
type name and appropriate errors will be thrown.
84. Can a storage class be specified after the data type in
declaration?

Yes. The compiler automatically maps the keywords and


competes the declaration. It doesn’t have any change in the
default way of declaration.

85. What are the access specifiers supported in C++?

There are three access specifiers supported in C++. They are:


9 Public – The members that are declared as public are fully
accessible from outside that class through an object of that
class.
9 Protected - The members that are declared as protected are
accessible from outside the class, but only in a class
derived from it.
9 Private - These members are only accessible from within
the class. No outside access is allowed.

86. Differentiate between call by value and call by reference.

In call by value, the original values will remain the same even
after the function is called because the copy of the
variables is being passed. But in the case of call by
reference, the original values will be altered after the
function is called because address is being passed.

87. How can references be used in C++?


References can be used to refer one address with multiple
names. For an example, one person can be called with
multiple names. This feature is referred aliasing.

88. What is a friend function? When will it be needed?

When a non-member function is declared as a friend it would


be easier for the function to access the private members.
Likewise, when a class itself is declared as a friend, the
friend class can then have access to the private data
members of the class which made a friend.

89. How will you allocate and deallocate memory in C++?

Allocation of memory can be carried out with new operator


and de-allocation can be carried out by delete operator.

90. What is the return value of new operator?

When the new operator is used to allocate memory, if it has


been allotted properly, address will be returned.

91. What is inheritance?

Inheritance is an object oriented feature. It is gaining features


from one class to other class. The features gained are the
data members and member functions of the base class. It is
the act of giving same properties to lower class.
92. Give some real-time examples of inheritance.

Son gaining business tactics from father.

Students gaining tricks and knowledge from teacher/master.

93. What are the modes of inheritance?

The modes of inheritance are:


9 Public
9 Private
9 Protected

94. What is the syntax for inheritance?

class derived_class : mode base_class1 , mode base_class2,


…..

95. In inheritance, when a derived class has a normal member


and another inherited member also has the same name, if
the derived class object calls the member then which will
be called? The base variable or derived variable?

Consider this program:


#include<iostream>
using namespace std;
class base
{ public:
int b; }S;
class dev : public base
{ public:
int b; }D;
int main()
{ D.b = 5;
cout<<D.b; }

Here D.b will access the original variable and not the inherited
variable. To access the inherited variable, the base class
name must be used.

96. What is the syntax for ‘this’ operator?

((class_name *)this)->member

97. In ‘public’ mode of inheritance, where will the ‘private’


members of the base class present in the derived class?

‘private’ members of the base class will not be derived into


derived class in any mode of inheritance.

98. How to inherit the ‘private’ members of a class?


‘private’ members of a class can never be inherited.

99. How to inherit ‘static’ members of a class?


‘static’ members are inherited as any normal variable. But for
normal variables a copy of it will be created in the derived
class, but here access to the original variables will be
given. It should be accessed with the appropriate class
name.

100. Will a ‘static’ function be inherited as a ‘static’ function?


Yes. A ‘static’ member will always be ‘static’.

101. Can an inherited ‘static’ function be called with ‘derived


class ::’ this syntax?
Yes. For ‘static’ functions it can be directly called from
derived class unlike ‘static’ data members.

102. What happens when the inheritance access specifier is not


specified in inheritance i.e, class derived_class :
base_class ?

The class will be inherited in ‘private’ mode. The mode of


inheritance is ‘private’ by default.

103. Can a class inherit an undefined class that is not even


declared?

No. Using unknown classes throws error “invalid use of


incomplete type ‘class class_name’”.
104. Can a class inherit an undefined class that is declared
alone?

No. Even though it is declared still it is incomplete. It throws


the same error.

105. Can inheritance be done with predefined or other user


defined data types?

No. Inheritance is an object-oriented feature. It is allowed only


among classes.

106. Explain the role of ‘::’ operator with respect to


inheritance.

When a local member and inherited member have the same


name collision occurs. To call the inherited member the
class name along with ‘::’ should be used. In general, it is
used for hierarchical access and variables in higher scopes.

107. Explain single inheritance. Give a real time example.

It is a single derived class inheriting from a single base class,


e.g., son learning business tactics from father.

108. Explain multiple inheritance. Give a real-time example.


It is a single derived class inheriting from more than one base
class simultaneously, e.g., Students gaining knowledge
from teachers.

109. Explain multilevel inheritance. Give a real-time example.

It is a derived class inheriting from one base class, which in


turn, has inherited from a super base class. Thus inheriting
in a chain, e.g., passing business across generations from
grandfather to father and from father to son.

110. Explain hierarchical inheritance. Give a real-time


example.

It is multiple derived class inheriting from one common base


class, e.g., family secrets passing from father to two sons.

111. Explain hybrid inheritance. Give a real time example.

Any combination of above inheritance types leads to hybrid


inheritance, e.g., school management assigning work from
top to bottom. It has multiple teachers under principle, but
one common assistant.

112. What is virtual inheritance?

Hybrid inheritance is also called virtual inheritance. It is called


so because of the usage of ‘virtual’ keyword in it. When
there is a chance of duplication of a super base class
attributes in any derives class ‘virtual’ should be used. It
makes only one copy attributes and skips other copies
based on the hierarchy of the attributes.

113. Is ‘virtual’ keyword mandatory in virtual inheritance?

No. When the conflicting base class is empty there is no


chance of duplication. So it can be skipped. ‘virtual’ is not
mandatory in the syntax. But it has no significance. So
indirectly ‘virtual’ keyword becomes mandatory.

114. What is the type of inheritance if it follows a pattern that


is combination of available inheritance methods.

Any abnormal inheritance pattern falls under the roof of


‘hybrid’ inheritance.

115. Is there any physical limit on the maximum number of


classes that a class can inherit? (How may base classes can
a derived class have?)

No. A class can inherit any number of classes provided the


memory (RAM) is available.

116. What is polymorphism?

Adding functionalities to the existing attributes is called


polymorphism. Polymorphism means ‘different forms’. It
involves operator overloading and functional overloading.
117. What is operator overloading?

Adding new functionalities to the existing operator is called


operator overloading. But the original functionality
remains unchanged.

118. Is it possible to remove the default functionality of an


operator using operator overloading?

No. There is no way to remove the original functionality of the


operator.

119. Can an overloaded operator be used by its inherited


classes?

Yes. If the operator definition is in ‘public’ scope, it will be


inherited by its derived classes also.

120. What is function overloading?

Giving multiple definitions to a class member function is


called function overloading.

121. What are the rules for overloading?


9 The name of the function should not be changed.
9 The return may or may not be varied.
9 The number of arguments may or may not be varied.
9 The type of the arguments may or may not be varied.
9 Either one or multiple from the following must be varied:
return type, type of arguments, number of arguments.

Changing the argument name doesn’t have an effect.

122. Does Redefining a function by just changing the name of


the arguments belong to function overloading?

No. Renaming the arguments doesn’t change the internal


signature of the function.

123. Does redefining a function by just changing the order of


types of the arguments belong to function overloading?

Yes. Changing the order of data types of the arguments creates


a new signature of the class. Hence, it is an overloaded
function.

124. Is it necessary to vary the number of arguments for an


overloaded function?

No. If any either return type of the function or type of


arguments are varied, then it is not necessary to change the
number of arguments.

125. Where do we use operator overloading? How is it


different from function overloading?
There are chances where a single operator may be used for two
different situations as follows.
95+3=8
9 Shri + ram = Shriram

Here + is the operator used to add two numbers and in the


second case, it is used as a concatenation operator. This is
the purpose of the operator overloading and function
overloading will let two different functions to have same
function name.

126. Can sizeof operator be overloaded? What are the other


operators which cannot be overloaded. List them all.

Sizeof cannot be overloaded. There are a few other operators


which can’t be overloaded and they are listed as follows:
9 . (Member Access or Dot operator)
9 ?: (Ternary or Conditional Operator )
9 :: (Scope Resolution Operator)
9 .* (Pointer-to-member Operator )

127. Define single inheritance with appropriate pseudocode.

When one derived class is inherited from one base class, it is


referred to be single inheritance.

Pseudocode:
class base_class // This is base class.
{
public:
––– // Code goes here.
};
class derived_class: public base_class
//Deriving class from the base and single inheritance is
achieved here.
{
public:
––– // Code goes here.
}

128. Explain multiple inheritance with an example.

When one derived class is derived (inherited) from multiple


base classes it is referred to be multiple inheritance.
class base_class_1 // Base class_1.One of the base classes.
{
public:
–— // Code goes here.
};
class base_class_2 // Base class_2. Second base class.
{
public:
–— // Code goes here.
};
class derived_class: public base_class_1, public
base_class_2
// 2 base classes are now used derive one derived class and it
is called multiple inheritance.
{
public:
–— // Code goes here.
}

129. Explain multilevel inheritance with an example.

A class will be used to create the derived class. For example A


B C D, where A is the base class, B being the first
derived class, C being the second derived class, but
derived from B and so on. This is called multi-level
inheritance.

class base_class_1 // Base class_1. It is to be inherited.


{
public:
int x, y;
};
class derived_class_1: public base_class_1 // deriving from
base class.
{
public:
int z;
}
class derived_class_2: public derived_class_1 // deriving
from derived class_1.
{
public:
int z;
}
class derived_class_3: public derived_class_2 // deriving
from base class_2.
{
public:
int z;
}

130. What is function overriding?

One can redefine a function derived in a base class to have the


same function with a different usage in a derive class.

131. What is the difference between function overriding and


function overloading?

For Function overriding:


1. The definition of the function being overridden must
have same method name.
2. The base class function and the overriding function
must have same data type.
3. The base class function and the overriding function
must have same argument list.

Whereas in function overloading the signature (argument type


and number of arguments) need not be the same. In fact,
they are expected to be different at least in the type or
number of arguments.

132. What is the use of templates in C++?


If a programmer is asked to write a function that can add two
integers can the same function be used for adding one
integer and one float? No. Eventually, the programmer will
end up in writing 2 different functions that can handle the
question raised. Templates will help the programmer to
avoid that problem. It is very generic and a single function
will be able to handle both the cases mentioned above with
templates.

133. What is a virtual function?

Simple, it is used to give different meanings for one function.


It might seem like calling one function, but the call could
have been raised for a different function. Virtual keyword
should be used for it.

134. Why cannot the constructors be declared virtual?

The virtual keyword will convey the compiler that the function
call shall be made only during the run time and not during
the compile time. So, when coming to constructor the
object creation itself is dependent on the constructor and
cannot wait. So, it would be inappropriate to make a
constructor virtual.

135. How is pure virtual function useful?

In a base class, if a function is declared as a pure virtual


function, the compiler will now make it mandated for the
derived class to override them.
136. What is an abstract class?

In other words, a class which has pure virtual function can


never be used to get objects out of them. The class is then
referred to be an abstract class.

137. Why should someone go for virtual base class?

When a class is derived out of two derived classes, then there


will be two copies of the base class components. Then
there will be an ambiguity to decide which copy is to be
used. So in this case virtual base class concepts are to be
used.

138. What is early binding? One simple example where it


could happen?

A function call, resolved at compile time, is called early


binding and any direct function call is a simple example
for the early binding.

139. Write on the access rights with all kinds of inheritances.

The following diagram is sufficient to get the clarity.


140. How can someone make a function pure virtual function?

a. Option one, the function can be assigned to 0 hence, it


becomes a pure virtual function.
#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show() = 0;
};

b. the below shown example is not a mostly preferred way. But


still, it would work like pure virtual function.
#include <iostream>
using namespace std;
class Base_class
{
public:
virtual void show()
{ // Nothing inside. Hence, it is also performing pure virtual
function’s functionality.
}
};

141. What are the restrictions one needs to understand when


making a function pure virtual with { } instead of
assigning the function to 0?

When one uses { } instead of assigning 0, creation of object is


permitted which is actually to be avoided. An object
cannot be created for an abstract class.

142. What are the classes involved in file handling?

The three major classes involved in file handling are:


9 ofstream: Class for writing into the files.
9 ifstream: Class for reading from the files.
9 fstream: class to both read and write from/to files.

143. What are the modes a file can be opened in C++?

A file can be opened in any of the following modes:


9 ios::app
9 ios::ate
9 ios::binary
9 ios::in
9 ios::out
9 ios::nocreate
9 ios::noreplace
9 ios::trunk

144. What is the usage of the following functions? A. seekg (),


B. seekp() C. tellg () D. tellp ()
9 seekg () will move the get pointer(input) to a specified
location
9 seekp ()will move the put pointer (output) to a specified
location
9 tellg () will fetch and give the current position of the get
pointer
9 tellp() will fetch and give the current position of the put
pointer

145. Brief on the following functions related to file handling.


A. eof () B. fail () C. bad() D. good.

Function Meaning

eof() Returns true with a non-zero value if end of file is encountered while
reading; otherwise return false(zero)

fail() Returns true when an input or output operation has failed

bad() Returns true if an invalid operation is attempted or any unrecoverable error


has occurred.

good() Returns true if no error has occurred.

146. What are the types of files one can list when asked?
9 Text file
It could be a typed document which could have series of
alphanumeric characters or symbols. One thing to
remember is, every line of a text file is terminated with an
EOL (End of Line) character.
9 Stream
Sequence of bytes is normally referred to be a Stream.
9 Binary files
A binary file will contain data encoded in binary form for
computer storage and processing purposes. Only the
processor can understand it and not a human. Because, it
would be in 1s and 0s.

147. What is the use of Void pointer in C++?

Let’s take a bottle; if you pour water into it, it is a water bottle.
If you pour juice into it, it’s a juice bottle. A pointer is also
similar. If a pointer holds the address of a float or int or
char, etc., it is referred to be a void pointer. When it holds
the address of a float only, it becomes float pointer. When
it holds the value of integer alone it becomes an integer
pointer. It is very flexible. One most important point to
remember is that casting has to be done to make the void
pointer a valid data type pointer
#include<iostream>
using namespace std;
int main()
{
int a = 9;
double b = 10.676;
void *p; //void pointer
p = &a;
// Here it is made as a integer pointer. Means p can hold
integer address.
cout <<”\n” << “Integer Pointer” << *(int *)p;
// Casting becomes inevitable. Making the void pointer as int
pointer.
p = &b;
cout << “\n” << “Double Pointer” << *(double *)p;
// Casting becomes inevitable. Making the void pointer as
double pointer.
getchar ();
return 0;
}

148. What is the use of Null pointer in C++?


When an uninitialized pointer is used, there could be a
possibility that it points to some garbage value. To avoid
that it is better to initialize the pointer to 0. A pointer when
initialized to 0 is referred to be a null pointer. It points to
nowhere.

A simple example as ever would do. Reader can refer to the


code below for getting a clear understanding.
#include<iostream>
using namespace std;
int main ()
{
int *p;
p = NULL; //NULL is the key word here.
cout <<p; // This pointer p is initialized to a NULL and it
will be pointing to 0.
getchar ();
return 0;
}
Execution Result:

149. What is friend class? How is it useful?

When there is a private data member in a class, access is


restricted for the other classes, i.e., no other class can
access them. So the best way to get this done is to make
the second class, which needs to access the private data
members of the first class, a friend. Since both the classes
are friends, it becomes easier. To enable the access easier,
we make a class friend to another class.

150. What are the storage qualifiers supported in C++?

There are four standard qualifiers supported in C++ as in C


programming. They are:
9 auto
9 static
9 register and
9 extern

151. How is auto storage qualifier used in C++? Enumerate the


usage.

Auto is a default storage qualifier and its region of use is


limited and it vanishes when the function gets complete!
One may or may not want to use the keyword as there is
no significant difference when used with keyword or
without it. If someone wants to declare it explicitly as
auto, then it can be done with a keyword auto.

auto int meters; // Explicitly defined as auto.

int meters; // implicitly defined as auto.

Since it is default, the keyword auto is used very rarely.

152. Explain the way the static is used in programming with


an example.

All the global variables fall under the category of static, by


default. Static variables can be declared even within a
block of codes. There is a significant difference between
static and auto. When it comes to static, the values of the
variables are retained and would not be reinitialized. 0 is
stored by default for static variables. A simple example to
show the default value stored for the static variable and
global variable is shown below.
#include <iostream>
using namespace std;
static int upper;
// Defining as static, so should be initialized to 0.
int lower;
// Global, so by default, static.
int main ()
{
cout <<”\n” << “Static” << upper;
cout <<”\n” << “Global” << lower;
getchar ();
return 0;
}

Execution Result:

153. How is register storage qualifier deployed in any code?


Identify the situation where register can be used as the
storage qualifier.

Whenever there is a need to store the local variables in the


CPU instead of RAM, register can be used.
{
register int upper;
}

Whenever the faster access is required, i.e., something like


embedded systems, usage of register is appreciated. One
should also understand that usage of ‘register’ is a
suggestion and not an order to the compiler. If no registers
are available to satisfy the query, register request may fail.

154. How is extern used in C++?


#include<iostream>
int count =10;
int main()
{
write
}
{return 0;}
code:2.cpp
#include <iostream>
using namespace std;
extern int count;
int main ()
{
cout <<”\n” << count;
return 0;
}

The “extern” qualifier defines a global variable that is visible


to all object modules, i.e., all the files in the same
directory. For an instance a.c file can get its variable’s
value from another file which is in the same directory and
the following small piece of code can help the reader in
understanding the concept. Also, within a file, extern can
be used. Second example reveals the way it can be done.
155. Give a brief note on near and far pointer.

All the terms as near and far pointers were used in the olden
programming days where the memory available was not
suffice. Now, it is not being used at most of the places and
in very few embedded systems it is being used. Near
pointers are 16 bits long and have capacity to address 64
KB range whereas far pointers are 32 bits long and has
capacity to address 1 MB range.

156. What is a namespace and how are they useful?

Entities like classes, objects and functions can all be grouped


under a name and it is referred to be as namespace.

157. What is a macro?

A macro is a statement that defines an expression for an


identifier. Before compilation, the pre-processor replaces
all the macros with their definitions.

158. What is ‘#’ called?

It is called pre-processor directive. It indicates a command to


pre-processor to be done before compiling.

159. What is exception handling?


Exception handling is the art of handling errors and by-passing
errors to continue compilation.

160. What is the syntax of exception handling?


Try
{
__________
__________
throw()
__________ }
catch()

161. What is multi catch?

A single try block with multiple ‘catch’ block is called multi


catch. Each catch block differs by the arguments it takes. It
acts like a switch case and a exception enters into the best
match. Finally, the ‘catch()’ without any arguments is
treated as default catch. If there is no match for the
exception it enters into the default catch block.

You might also like