Cracking The C++ Programming Skills - IT Job Interview Series
Cracking The C++ Programming Skills - IT Job Interview Series
Cracking The C++ Programming Skills - 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
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
4 STORAGE CLASS 80
6 INHERITANCE 110
7 OPERATOR OVERLOADING 40
10 NAMESPACES 11
11 TEMPLATES 13
12 EXCEPTION HANDLING 40
13 FILES 35
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.
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 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.
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.
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.
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.
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’.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Unary plus +
Address-of &
Indirection *
Create object New
Destroy object Delete
Cast Cast: ()
Function call ()
Multiplication *
Division /
Modulus %
Addition +
Subtraction -
i. Encapsulation
ii. Inheritance
iii. Polymorphism
C C++
Function overloading is
Function overloading is not permitted in C
supported in C++
C++ Java
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.
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.
39. How many header files are present in C++ standard and
how many of them are borrowed from C standard?
57. Why destructors are not used in Java while it has found lot
of usage in C++?
61. How to call the static members of the class? Can objects be
used for doing so?
Yes it can use any variable outside class scope. But inside
class scope should use only static variables.
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.
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.
((class_name *)this)->member
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.
}
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.
Function Meaning
eof() Returns true with a non-zero value if end of file is encountered while
reading; otherwise return false(zero)
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.
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;
}
Execution Result:
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.