0% found this document useful (0 votes)
96 views19 pages

C - Aptitude Book

Soft Skills Training provides various training programs including faculty development, aptitude training, corporate coaching, and technical and finance training. The programs are offered both online and in-person at their office in Coimbatore, India. They also provide study materials like their C++ Aptitude Book which contains sample questions and explanations to help students learn C++.

Uploaded by

vishnu vardhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views19 pages

C - Aptitude Book

Soft Skills Training provides various training programs including faculty development, aptitude training, corporate coaching, and technical and finance training. The programs are offered both online and in-person at their office in Coimbatore, India. They also provide study materials like their C++ Aptitude Book which contains sample questions and explanations to help students learn C++.

Uploaded by

vishnu vardhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Soft Skills

Training

Faculty
Aptitude
Development
Training
Program

SIX
PHRASE
Corporate
Finance Training
Coaching

Technical
Training

C++ Aptitude Book

93A GKD Nagar P.N.Palayam Coimbatore – 641037


Prabhu - 99946 75750
Email - [email protected]
Website - www.sixphrase.in
C++ Aptitude Book

1. What is the output of the following program?

void main(){

char str[] = "String continued"

" at the next line";

cout << str;

Answer:

String continued at the next line.

Explanation:

C++ concatenates these strings. When a new-line or white spaces separate two adjacent strings,
they are concatenated to a single string. This operation is called as “stringization” operation. So str
could have initialized by the single string “String continued at the next line.”.

2. void main(){

int a, *pa, &ra;

pa = &a;

ra = a;

cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;

Answer :

Compiler Error: 'ra', reference must be initialized

Explanation :

Pointers are different from references. One of the main differences is that the pointers can be
both initialized and assigned, whereas references can only be initialized. So this code issues an
error.

3. ANSI C++ introduces new style of casts (const_cast, dynamic_cast, static_cast and
reinterpret_cast). For the following C style cast which of the new cast syntax should be applied?

pDerived = (Cderived *) pBase;

Answer:

1
C++ Aptitude Book

dynamic_cast.

Explanation:

dynamic_cast is used for traversing up and down in inheritance hierarchy. So it can be applied
here to cast pointer type from the base class to derived class. The cast in the new syntax will look
like this:

pDerived = dynamic_cast <Cderived*> (pBase);

4. const int size = 5;

void print(int *ptr){

cout<<ptr[0]; }

void print(int ptr[size]){

cout<<ptr[0];

void main(){

int a[size] = {1,2,3,4,5};

int *b = new int(size);

print(;

print(b);

Answer:

Compiler Error : function 'void print(int *)' already has a body

Explanation:

Arrays cannot be passed to functions, only pointers (for arrays, base addresses) can be passed. So
the arguments int *ptr and int prt[size] have no difference as function arguments. In other words,
both the functoins have the same signature and so cannot be overloaded.

5. In which of the following cases will the copy constructor of the class X be called?

A) X x1,Y Y!:

foo(&x1,&y2); //function foo already defined

B) X x1,x2, Y y1;

x2 = bar(x1,y1); // function bar already defined

2
C++ Aptitude Book

C) X x1(0.2) ,x2;x2 =x1;

D) X x1; X x2 =x1;

Answer:

B, C and D

Explanation:

In the function call foo, the address of the x1 is passed. So there is no need for the copy
constructor. But in the other cases there is an assignment of X, which calls for a copy constructor.

6. class Sample{

public:

int *ptr;

Sample(int i){

ptr = new int(i);

~Sample(){

delete ptr;

void PrintVal(){

cout << "The value is " << *ptr;

};

void SomeFunc(Sample x){

cout << "Say i am in someFunc " << endl;

int main(){

Sample s1= 10;

SomeFunc(s1);

s1.PrintVal();

3
C++ Aptitude Book

Answer:

Say i am in someFunc.

Null pointer assignment(Run-time error)

Explanation:

As the object is passed by value to „SomeFunc‟ the destructor of the object is called when the
control returns from the function. So when PrintVal is called, it meets up with ptr that has been
freed.The solution is to pass the Sample object by reference to SomeFunc:

void SomeFunc(Sample &x){

cout << "Say i am in someFunc " << endl;

because when we pass objects by refernece that object is not destroyed. while returning from the
function.

7. What is the output of the following program?

void Sample(int x=6,int y,int z=34){

cout << "Say i am in sample with the values " <<x<<y<<z;

void main(){

int a,b,c;

cin >>a>>b>>c;

Sample(a,b,c);

Answer:

Compile Time error: Missing default parameter for parameter 2.

Explanation:

The program wouldn‟t compile because, as far as default arguments are concerned, the right-most
argument must be supplied with a default value before a default argument to a parameter to it‟s
left can be supplied.

8. class base{

4
C++ Aptitude Book

public:

int bval;

base(){ bval=0;}

};

class deri:public base{

public:

int dval;

deri(){ dval=1;}

};

void SomeFunc(base *arr,int size){

for(int i=0; i<size; i++,arr++)

cout<<arr->bval;

cout<<endl;

int main(){

base BaseArr[5];

SomeFunc(BaseArr,5);

deri DeriArr[5];

SomeFunc(DeriArr,5);

Answer:

00000

01010

Explanation:

The function SomeFunc expects two arguments.The first one is a pointer to an array of base class
objects and the second one is the sizeof the array.The first call of someFunc calls it with an array
of base objects, so it works correctly and prints the bval of all the objects. When SomeFunc is
called the second time the argument passed is a pointer to an array of derived class objects and not

5
C++ Aptitude Book

the array of base class objects. But that is what the function expects to be sent. So the derived class
pointer is promoted to base class pointer and the address is sent to the function. SomeFunc()
knows nothing about this and just treats the pointer as an array of base class objects. So when
arr++ is met, the size of base class object is taken into consideration and is incremented by
sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >=
sizeof(int)+sizeof(int) ).

9. class some{

public:

~some(){

cout<<"some's destructor"<<endl;

};

void main(){

some s;

s.~some();

Answer:

some's destructor

some's destructor

Explanation:

Destructors can be called explicitly (constructors can not be). Here 's.~some()' explicitly calls the
destructor of 's'. When main() returns, destructor of s is called again, hence the result.

10. class base{

public:

void baseFun(){ cout<<"from base"<<endl;}

};

class deri:public base{

public:

void baseFun(){ cout<< "from derived"<<endl;}

};

void SomeFunc(base *baseObj){

6
C++ Aptitude Book

baseObj->baseFun();

int main(){

base baseObject;

SomeFunc(&baseObject);

deri deriObject;

SomeFunc(&deriObject);

Answer:

from base

from base

Explanation:

As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer
to a derived class object is passed, it treats the argument only as a base class pointer and the
corresponding base function is called.

11. class base{

public:

virtual void baseFun(){ cout<<"from base"<<endl;}

};

class deri:public base{

public:

void baseFun(){ cout<< "from derived"<<endl;}

};

void SomeFunc(base *baseObj){

baseObj->baseFun();

int main(){

base baseObject;

7
C++ Aptitude Book

SomeFunc(&baseObject);

deri deriObject;

SomeFunc(&deriObject);

Answer:

from base

from derived

Explanation:

Remember that baseFunc is a virtual function. That means that it supports run-time
polymorphism. So the function corresponding to the derived class object is called.

12. What is the output of the following code?

class base

public:

int n;

virtual void foo(){n=1;}

void print(){cout <<n<<endl;}

};

class derived: base

public:

void foo(){n=2;}

void print(){cout <<n<<endl;}

};

void main()

derived y;

8
C++ Aptitude Book

base *bp =dynamic_cast<base *>(&y);

bp->foo();

bp->print();

Answer:

Undefined behavior : dynamic_cast used to convert to inaccessible or ambiguous base;

Explanation:

In this program private inheritance is used (by default the inheritance is private). There is no
implicit conversion from the derived to base due to this. An explicit dynamic cast is used to
overcome this. But at runtime environment may impose the restrictions on access to the code,
resulting in an undefined behavior.

13. class fig2d{

int dim1, dim2;

public:

fig2d() { dim1=5; dim2=6;}

virtual void operator<<(ostream & rhs);

};

void fig2d::operator<<(ostream &rhs){

rhs <<this->dim1<<" "<<this->dim2<<" ";

class fig3d : public fig2d{

int dim3;

public:

fig3d() { dim3=7;}

virtual void operator<<(ostream &rhs);

};

void fig3d::operator<<(ostream &rhs){

fig2d::operator <<(rhs);

9
C++ Aptitude Book

rhs<<this->dim3;

void main(){

fig2d obj1;

fig3d obj2;

obj1 << cout;

obj2 << cout;

Answer :

56

Explanation:

In this program, the << operator is overloaded with ostream as argument. This enables the 'cout'
to be present at the right-hand-side. Normally, operator << is implemented as global function, but
it doesn't mean that it is not possible to be overloaded as member function. Overloading << as
virtual member function becomes handy when the class in which it is overloaded is inherited,
and this becomes available to be overrided. This is as opposed to global friend functions, where
friend's are not inherited.

14. class opOverload{

public:

bool operator==(opOverload temp);

};

bool opOverload::operator==(opOverload temp){

if(*this == temp ){

cout<<"The both are same objects\n";

return true;

cout<<"The both are different\n";

return false;

void main(){

10
C++ Aptitude Book

opOverload a1, a2;

a1== a2;

Answer :

Runtime Error: Stack Overflow

Explanation :

Just like normal functions, operator functions can be called recursively. This program just
illustrates that point, by calling the operator == function recursively, leading to an infinite loop.

15. class complex{

double re;

double im;

public:

complex() : re(1),im(0.5) {}

operator int(){}

};

int main(){

complex c1;

cout<< c1;

Answer :

Garbage value

Explanation:

The programmer wishes to print the complex object using output re-direction
operator,which he has not defined for his class.But the compiler instead of giving an error
sees the conversion function and converts the user defined object to standard object and
prints some garbage value.

16. class complex{

double re;

double im;

11
C++ Aptitude Book

public:

complex() : re(0),im(0) {}

complex(double n) { re=n,im=n;};

complex(int m,int n) { re=m,im=n;}

void print() { cout<<re; cout<<im;}};

void main(){

complex c3;

double i=5;

c3 = i;

c3.print();

Answer:

5,5

Explanation:

There is no operator= function taking double as an argument is defined. So the compiler creates a
„complex‟ object using the single argument constructor that takes double as an argument. This
temporary object is assigned to c3.

17. Consider the following piece of code.

String s(“hello!”);

String s2 = s1+ “how are You”;

Will this code compile for this class declaration:

class String {

public:

String(char *);

String & operator=(String &);

String operator+(String);

friend operator+(String,String);

};

Answer:

12
C++ Aptitude Book

No, this code will not compile.

Explanation:

Because there is an ambiguity between the overloading of the + operator as a member function
and friend function. Given the statement:

String s2 = s1+ “how are You”;

the compiler doesn‟t know to which function should it resolve to and call.

18. What is the output of the following code?

class base {/*....*/};

class derived :public base{/*....*/};

void foo()

{ try

throw derived();

catch (base b)

cout<<"Received exception, but can't handle\n";

throw;

};

void main()

try

foo();

catch (derived d)

cout<<"In derived handler";

13
C++ Aptitude Book

catch (base b)

cout << "In Base handler";

Answer:

Received exception, but can't handle

In derived handler

Explanation:

When the function foo is called, the exception object of type derived is thrown. Now the catch
block for that „derived‟ exception object is searched but it is found that there is a catch block for
„base‟ is available. Since exception objects of type „base‟ can handle all such exceptions in its
hierarchy, this exception is caught.

A plain „throw‟ inside a catch indicates a re-throw of the exception caught. So the „derived‟
exception object is again thrown and is caught by the catch block in main(). Although both the
catch blocks are eligible to handle the exception, this time the derived which is defined first will
catch the exception.

19. What is the output of the following program?

void main(){

vector<int> vec1,vec2;

vec1.push_back(12);

vec1.push_back(13);

vec2.push_back(12);

vec2.push_back(13);

cout << (vec1<vec2);

Answer:

Explanation:

14
C++ Aptitude Book

The values contained in both the containers are equal. Therefore the comparison returns 0. Each
container supports a set of comparison operators. The comparison is based on a pair-wise
comparison of the elements of the two containers. If all the elements are equal and if both the
containers contain the same number of elements, the two containers are equal; otherwise, they
are unequal. A comparison of the first unequal element determines the less-than or greater-than
relationship of the 2 containers.

20. Consider the following lines of code:

list<int> aList;

list<int>::iterator anIterator(&aList);

what can you say about the relationship between „aList‟ and „anIterator‟?

Answer:

The class iterator is a friend of class list.

Explanation:

Iterators are always friend functions.

21. #include <list>

#include <algorithm>

#include <iostream>

using namespace std;

void main()

list<int> ilist;

list<int>::iterator iiter;

for (int i=0;i<10;i++) ilist.push_back(i);

iiter = find(ilist.begin(),ilist.end(),3);

if ( *(iiter+1) ==4) cout <<"yeah ! found";

Output:

Compile –time error:

Explanation:

15
C++ Aptitude Book

The code won‟t compile because , iterators associated with list containers do not support the
operator + used in the expression (*(iter+1) ==4 ), because iterators associated with list are of type
bi-directional iterator, which doesn‟t support the + operator.

22. What‟s the output of the following program? Why?


#include <stdio.h>
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;

Union x,y = {100};


x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;

printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)

23. Will the following program execute?


void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}
Answer
in C++
voidp.c: In function `int main()‟:
voidp.c:4: error: invalid application of `sizeof‟ to a void type
voidp.c:4: error: `malloc‟ undeclared (first use this function)
voidp.c:4: error: (Each undeclared identifier is reported only once for each function it appears in.)
voidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*‟

24. void main()


{
char *cptr = 0?2000;
long *lptr = 0?2000;
cptr++;

16
C++ Aptitude Book

lptr++;
printf(” %x %x”, cptr, lptr);
}
Will it execute or not?

Answer
Not Execute.
Compile with VC7 results following errors:
error C2440: „initializing‟ : cannot convert from „int‟ to „char *‟
error C2440: „initializing‟ : cannot convert from „int‟ to „long *‟

17
Soft Skills Training Corporate Coaching
Survival of the Fittest Critical Thinking
English Grammar Gym Organizational Excellence
Career Skills Seven Habits of Highly
Oral Communication Effective People
Written Communication Business Skills
Goal Setting Presentation Skills
Resume Writing Conflict Management
Group Discussion Search Engine Optimization
Interview Skills Selling Skills
Reading & Learning Skills Working with MS Excel
Questioning & Listening Skills MS PowerPoint & MS Word
Personality Development Branding
Creativity Supply Chain
Time Management Channel Sales
Leadership Skills Retailing
Team Management Business Analytics & ERP
Entrepreneurship Skills

Finance Training Faculty Development


Financial Market for Beginners Programs
Stock Trading Energizing your Classroom
Wealth Management Delivering Powerful Lectures
Taxation Case Studies as a Teaching
Financial Advisory Tool
Management Technology Tools for the
Personal Finance Management Classroom
Financial Services & Markets Personal Development
Banking Operations & Research Methodology
Management Stress Management
NCFM Certification Coaching Team Building Activities

Technical Training Aptitude/Verbal Training


Quantitative Aptitude
C, C++ & Data Structures
Reasoning Aptitude
Java & J2EE
Creativity Aptitude
Dot Net
Verbal Aptitude
LAMP Training
Data Sufficiency
PHP/MYSQL
Data Interpretation
Web Designing
Certification Courses (SCJP,
OCP, MCP etc…)

You might also like