Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

CSE 2018 -2015

Click to jump:
2018 :: Ques1 Ques2 Ques3 Ques4
a,b,c,d a,b,c,d a,b,c a,b,c,d
2017 :: Ques1 Ques2 Ques3 Ques4
a,b,c,d a,b,c a,b,c,d a,b,c,d
2016 :: Ques1 Ques2 Ques3 Ques4
a,b,c a,b,c a,b,c,d a,b,c
2015 :: Ques1 Ques2 Ques3
a,b,c,d a,b,c a,b,c,d

#1703078
CSE 2018
Ques 1
a.
i.

#include <iostream>
using namespace std;
class student
{
private:
int Marks[3];

public:
student()
{
Marks[0] = 1;
Marks[1] = 2;
Marks[2] = 3;
}
};

int main()
{
student student_obj1, student_obj2;
return 0;
}

ii)

#include <iostream>
using namespace std;
class student
{
private:
int Marks[3];

public:
student()
{
Marks[0] = 1;
Marks[1] = 2;
Marks[2] = 3;
}
};

int main()
{
student student_obj1, student_obj2;
student_obj2 = student_obj1;

return 0;
}

iii)

#include <iostream>
using namespace std;
class student
{
private:
int Marks[3];

public:
student()
{
Marks[0] = 1;
Marks[1] = 2;
Marks[2] = 3;
}
void disp()
{
for (int i = 0; i < 3; i++)
cout << "Marks " << i + 1 << ": " << Marks[i]<<endl;
}

student operator ++ (int)


{
student temp;
for (int i = 0; i < 3; i++)
temp.Marks[i] = Marks[i]++;
return temp;
}

int main()
{
student student_obj1, student_obj2;
student_obj2 = student_obj1;

student_obj1.disp();
student_obj1=student_obj2++;
student_obj2.disp();
}

b.
Pointers: A pointer is a variable that holds memory address of another variable. A
pointer needs to be dereferenced with * operator to access the memory location it points
to.

References : A reference variable is an alias, that is, another name for an already existing
variable. A reference, like a pointer is also implemented by storing the address of an
object.
A reference can be thought of as a constant pointer (not to be confused with a pointer to
a constant value!) with automatic indirection, i.e the compiler will apply the * operator
for you.

int i = 3;

// A pointer to variable i (or stores


// address of i)
int *ptr = &i;

// A reference (or alias) for i.


int &ref = i;
Differences :

Initalisation: A pointer can be initalised in this way:

int a = 10;
int *p = &a;
OR
int *p;
p = &a;
we can declare and initalise pointer at same step or in multiple line.
While in refrences,

int a=10;
int &p=a; //it is correct
but
int &p;
p=a; // it is incorrect as we should declare and initialise references at single step.
NOTE: This differences may vary from compiler to compiler. Above differences is with
respect to turbo IDE.

Reassignment: A pointer can be re-assigned. This property is useful for implementation


of data structures like linked list, tree, etc. See the following examples:

int a = 5;
int b = 6;
int *p;
p = &a;
p = &b;
On the other hand, a reference cannot be re-assigned, and must be assigned at
initialization.

int a = 5;
int b = 6;
int &p = a;
int &p = b; //At this line it will show error as "multiple declaration is not allowed".

However it is valid statement,


int &q=p;
Memory Address: A pointer has its own memory address and size on the stack whereas
a reference shares the same memory address (with the original variable) but also takes
up some space on the stack.
NOTE However if we want true address of reference, then it can be found out in turbo
IDE by writing the following statement,
int &p = a;
cout << &(&p);
NULL value: Pointer can be assigned NULL directly, whereas reference cannot. The
constraints associated with references (no NULL, no reassignment) ensure that the
underlying operations do not run into exception situation.

Indirection: You can have pointers to pointers offering extra levels of indirection.
Whereas references only offer one level of indirection,

In Pointers,
int a = 10;
int *p;
int **q; //it is valid.
p = &a;
q = &p;

Whereas in refrences,

int &p = a;
int &&q = p; //it is reference to reference, so it is an error.
Arithmetic operations: Various arithmetic operations can be performed on pointers
whereas there is no such thing called Reference Arithmetic.(but you can take the address
of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).)

c.
(i)

#include<iostream>
using namespace std;

class base {
int arr[10];
};

class b1: public base { };


class b2: public base { };

class derived: public b1, public b2 {};

int main(void)
{
cout << sizeof(derived);
return 0;
}

No Error in (i)
Output: 80

arr[i]takes 4 byte. So 4*10=40. This is size for base, b1, b2. Size of derived doubles as it
takes two base class.

(ii)

#include<iostream>
using namespace std;

class Base
{
public:
int fun() { cout << "Base::fun() called"; }
int fun(int i) { cout << "Base::fun(int i) called"; }
};

class Derived: public Base


{
public:
int fun() { cout << "Derived::fun() called"; }
};

int main()
{
Derived d;
d.fun(5);
return 0;
}
It’ll give compilation error. If a derived class writes its own method, then all functions of
base class with same name become hidden, even if signaures of base class functions are
different.

In the above question, when fun() is rewritten in Derived, it hides both fun() and
fun(int) of base class.

d.
A destructor can never be overloaded. An overloaded destructor would mean that the
destructor has taken arguments. Since a destructor does not take arguments, it can
never be overloaded.

Ques 2
a.
#include <iostream>

using namespace std;

class XYZ
{
private:
int y = 10;

public:
int num = y;
};

class ABC
{
private:
int x = 6;

public:
int num = x;
friend void swap(ABC &, XYZ &);
};

void swap(ABC &s1, XYZ &s2)


{
int temp;
cout << "\nBefore Swapping: " << s1.num << " " << s2.num;
temp = s1.num;
s1.num = s2.num;
s2.num = temp;
cout << "\nAfter Swapping: " << s1.num << " " << s2.num;
}

int main()
{
ABC s1;
XYZ s2;
swap(s1, s2);
return 0;
}

b.
In C++, stream insertion operator << is used for output.
cout is an object of ostream class which is a compiler defined class. When we
do cout<<obj where obj is an object of our class, the compiler first looks for an operator
function in ostream, then it looks for a global function. One way to overload insertion
operator is to modify ostream class which may not be a good idea. So we make a global
method and if we want to allow them to access private data members of class, we must
make them friend.

Let’s see the following example.

#include <iostream>
using namespace std;

class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};

ostream & operator << (ostream &out, const Complex &c)


{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}

istream & operator >> (istream &in, Complex &c)


{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}

int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}

We are asked why ostream& is being used instead of just ostream.


Returning a copy of the stream object is not allowed because copy-constructor (and
copy-assignment as well) of the all stream classes in C++ is disabled by having them
made private.

Since you cannot make a copy of an stream object, you're required to return it by
reference.

c.
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself. Thus any member function can find out the address of
the object of which it is a member.

#include <iostream>
using namespace std;
class what
{
private:
int alpha;
public:
void tester()
{
this->alpha = 11;
};
int main()
{
what w;
w.tester();
cout << endl;
return 0;
}

We can also return values by using this.

alpha &operator=(alpha &a)


{
data = a.data;
cout << “\nAssignment operator invoked”;
return *this;
}

d.
Though C++ is an object-oriented programming language, it is very much inspired by
procedural language. A program in C++ is executed sequentially line by line. Each line of
the source program after translation is in the form of machine language. Each line in the
machine language is assigned a unique address. Similarly, when a function call is
encountered by the complier during execution, the function call is translated into
machine language, and a sequential address is provided. Thus, refers to the process that
is to be used for converting functions and variables into machine language addresses.
The C++ supports two types of binding: static or early binding and dynamic or late
binding.

• Static polymorphism is also known as early binding and compile-time


polymorphism.

#include<iostream>
using namespace std;
class Base
{
public:
void show() { cout<<" In Base \n"; }
};
class Derived: public Base
{
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show();
return 0;
}

Output:
In Base

• Dynamic polymorphism is also known as late binding and run-time polymorphism.

class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base


{
public:
void show() { cout<<"In Derived \n"; }
};

int main(void)
{
Base *bp = new Derived;
bp->show();
return 0;
}
Output:
In Derived

• Function Overloading : Function overloading is an example of static polymorphism.


More than one function with same name, with different signature in a class or in a
same scope is called function overloading.
• Operator Overloading : Another example of static polymorphism is Operator
overloading. Operator overloading is a way of providing new implementation of
existing operators to work with user-defined data types.
• Virtual function : Virtual function is an example of dynamic polymorphism. Virtual
function is used in situation, when we need to invoke derived class function using
base class pointer. Giving new implementation of derived class method into base
class and the calling of this new implemented function with base class's object is
done by making base class function as virtual function. This is how we can achieve
"Runtime Polymorphism".

Ques 3:
a.
#include<iostream>
using namespace std;

class base {
private: int a;
public:void disp(){cout<<"FROM BASE, a: "<<a<<endl;}};

class derived: public base {};

int main()
{
derived D;
D.disp();
return 0;
}

b.
Abstract Classes and Pure Virtual Functions

When we will never want to instantiate objects of a base class, we call it an abstract
class. Such a class exists only to act as a parent of derived classes that will be used to
instantiate objects. It may also provide an interface for the class hierarchy.

How can we make it clear to someone using our family of classes that we don’t want
anyone to instantiate objects of the base class? We could just say this in the
documentation, and count on the users of the class to remember it, but of course it’s
much better to write our classes so that such instantiation is impossible. How can we
can do that? By placing at least one pure virtual function in the base class. A pure virtual
function is one with the expression =0 added to the declaration. This is shown in the
VIRTPURE example.

#include <iostream>
using namespace std;

class Base {public: virtual void show() = 0; /*pure virtual function*/ };

class Derv1 : public Base {public: void show() { cout << “Derv1\n”; } };

class Derv2 : public Base {public: void show() { cout << “Derv2\n”; } };

int main() {
/*Base bad; If Executed Error--> Can’t make object from abstract class */
Base* arr[2];
Derv1 dv1;
Derv2 dv2;
arr[0] = &dv1;
arr[1] = &dv2;
arr[0]->show();
arr[1]->show();
return 0;
}
Here the virtual function show() is declared as virtual void show() = 0; // pure virtual
function

The equal sign here has nothing to do with assignment; the value 0 is not assigned to
anything. The =0 syntax is simply how we tell the compiler that a virtual function will be
pure. Now if in main() you attempt to create objects of class Base,the compiler will
complain that you’re trying to instantiate an object of an abstract class. It will also tell
you the name of the pure virtual function that makes it an abstract class. Notice that,
although this is only a declaration, you never need to write a definition of the base class
show(),although you can if you need to.

Once you’ve placed a pure virtual function in the base class, you must override it in all
the derived classes from which you want to instantiate objects. If a class doesn’t
override the pure virtual function, it becomes an abstract class itself, and you can’t
instantiate objects from it (although you might from classes derived from it). For
consistency, you may want to make all the virtual functions in the base class pure.

As you can see, we’ve made another, unrelated, change in VIRTPURE:The addresses of
the member functions are stored in an array of pointers and accessed using array
elements. This works in just the same way as using a single pointer. The output of
VIRTPURE is the same as VIRT: Derv1 Derv2

c.
i)

#include <iostream>

using namespace std;

class X
{
int x;

public:
X(int a) { x = a; }
int Max(X a, X b)
{
if (a.x >= b.x)
return a.x;
else
return b.x;
}
};
int main()
{
X p(5), q(10);
cout << p.Max(p, q);
}

ii) A constructor is a special type of member function that initializes an object


automatically when it is created. Constructor has the same name as that of the class and
it does not have any return type. Also, the constructor is always public.

Analysis of syntax of constructor here.

iii) 1

Ques 4:
a.
pos = tellg(pos) → Return position (in bytes) of file pointer from start of file.

seekp(position) → Set distance in bytes of file pointer from start of file.

int = eof() → Returns true if EOF flag set

b.
c.
Prefix Decrement Operator Function:

ComplexNumber ComplexNumber::operator--()
{
--real;
--imaginary;
return *this;
}

Postfix Decrement Operator Function


ComplexNumber ComplexNumber::operator--(int)
{
ComplexNumber tempObj(this->real, this->imaginary);
real--;
imaginary--;

return tempObj;
}

d.
The constructors of inherited classes are called in the same order in which they are
inherited. For example, in the following program, B’s constructor is called before A’s
constructor.

#include<iostream>
using namespace std;

class A { public: A()


{ cout << "A's constructor called" << endl; } };

class B { public: B()


{ cout << "B's constructor called" << endl; } };

class C: public B, public A /*Note the order*/ { public: C()


{ cout << "C's constructor called" << endl; } };

int main()
{
C c;
return 0;
}

CSE 2017
Ques 1:
a.
Machine Language

A computer’s native language is called Machine Language. Machine language is the most
primitive or basic programming language that starts or takes instructions in the form of
raw binary code. So that if you wanted to give a computer an instruction in its native
or Machine language, you have to manually enter the instructions as binary code.

For example, adding two numbers together in machine language would look like this:
1101101010011010

Assembly Language

Programming in Machine language is tedious (you have to program every command


from scratch) and hard to read & modify (the 1s and 0s are kind of hard to work
with…). For these reasons, Assembly language was developed as an alternative to
Machine language.

Assembly Language uses short descriptive words (mnemonic) to represent each of the
Machine Language instructions.

For example the mnemonic add means to add numbers together, and sub means to
subtract the numbers. So if you want to add the numbers 2 and 3 in assembly language,
it would look like this:
add 2, 3, result

So Assembly Languages were developed to make programming easier. However, the


computer cannot directly execute the assembly language. First another program called
the assembler is used to translate the Assembly Language into machine code.

High-Level Language

High-Level languages are platform independent, meaning that you can write & run High-
Level Languages on different types of machines. High-Level Languages are English like
and therefore easier to learn and use. Note that instructions in a High-Level Language
are called statements.

Note that a program written in a high-level language is called the source code. Note that
the Source Code must be translated into machine code before the computer can execute
the source code. And the translations are done by programming tools called
an interpreter or compiler.

Here’s an example of a High-Level Language statement that calculates the area of a circle
with a radius of 5:
area = 5 * 5 * 3.14159;
b.
Object-oriented programming (OOP) is a programming language model in which
programs are organized around data, or objects, rather than functions and logic. An
object can be defined as a data field that has unique attributes and behavior. Examples
of an object can range from physical entities, such as a human being that is described by
properties like name and address, down to small computer programs, such as widgets

The characteristics of OOP are:


Class definitions – Basic building blocks OOP and a single entity which has data and
operations on data together

Objects – The instances of a class which are used in real functionality – its variables and
operations

Abstraction – Specifying what to do but not how to do ; a flexible feature for having a
overall view of an object’s functionality.

Encapsulation – Binding data and operations of data together in a single unit – A class
adhere this feature

Inheritance and class hierarchy – Reusability and extension of existing classes

Polymorphism – Multiple definitions for a single name - functions with same name with
different functionality; saves time in investing many function names Operator and
Function overloading

Generic classes – Class definitions for unspecified data. They are known as container
classes. They are flexible and reusable.

Class libraries – Built-in language specific classes

Message passing – Objects communicates through invoking methods and sending data to
them. This feature of sending and receiving information among objects through function
parameters is known as Message Passing.

c.
Typedef: C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef doest not actually create a new data class, rather it defines a new
name for an existing type. This can increase the portability of a programas only the
typedef statements would have to be changed.

The syntax of the typedef statement is :

typedef float amount;

amount loan, saving, instalment

#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
typedef int integer;
integer num1, num2, sum;
cout << "Enter two number: ";
cin >> num1 >> num2;
sum = num1 + num2;
cout << "Sum = " << sum;
getch();
}
Enumeration:

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.

enum days_of_week
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
int main()
{
days_of_week day1, day2;
day1 = Mon;
day2 = Thu;
int diff = day2 - day1;
}
d.
#include<iostream>
using namespace std;

class ADD {

int x, y;
double f;
string s;

public ADD(int a, double b)


{
x = a;
f = b;
}

public ADD(int a, string b)


{
y = a;
s = b;
}

public void show()


{
Console.WriteLine("1st constructor (int + float): {0} ",
(x + f));
}

public void show1()


{
Console.WriteLine("2nd constructor (int + string): {0}",
(s + y));
}
}

class GFG {

static void Main()


{
ADD g = new ADD(10, 20.2);
g.show();

ADD q = new ADD(10, "Roll No. is ");


q.show1();
}
}

Ques 2:
a.
Small function can slow the process

While this sequence of events may save memory space, it takes some extra time. There
must be an instruction for the jump to the function (actually the assemblylanguage
instruction CALL or something similar), instructions for saving registers, instructions for
pushing arguments onto the stack in the calling program and removing them from the
stack in the function(if there are arguments), instructions for restoring registers, and an
instruction to return to the calling program. The return value (if any) must also be dealt
with. All these instructions slow down the program.

Inline Functions can save excution time.


To save execution time in short functions, you may elect to put the code in the function
body directly inline with the code in the calling program. That is, each time there’s a
function call in the source file, the actual code from the function is inserted, instead of a
jump to the function

#include <iostream>
using namespace std;
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
int main()
{
float lbs;
cout << “\nEnter your weight in pounds : “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs) << endl;
return 0;
}

b.
Static variables have a property of preserving their value even after they are out of their
scope!Hence, static variables preserve their previous value in their previous scope and
are not initialized again in the new scope.
Syntax: static data_type var_name = var_value;

#include <stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

Output:
12
But below program prints 1 1
#include <stdio.h>
int fun()
{
int count = 0;
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

Output:
11
c.
Go to 2017 Ques 2a

Ques 3:
A,
The main purpose of the class constructor in C++ programming is to construct an object
of the class. In other word, it is used to initialize all class data members.

For example, in below class, constructor Car () is initializing data members with default
values. And, when we create the object of a class, this constructor will always be called.

class Car
{ int id;
string model;
public:
Car(){
this->id = 11;
this->model = "Maruti";
}

void display(){ cout<< "Car Info:"<<" "<id<<"


"<model.c_str()<<"\n";}
};
int main(){
Car c;
c.display();

return 0;
}

Features of constructor:
• Constructors have the same name as that of the class they belong to.
• Constructors are executed when an object is declared.
• Constructors have neither return value nor void.
• The main function of constructor is to initialize objects and allocate appropriate
memory to objects.
• Though constructors are executed implicitly, they can be invoked explicitly.
• Constructors can have default values and can be overloaded.
• The constructor without arguments is called as default constructor.
b.
Public: All the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes
too. The public members of a class can be accessed from anywhere in the program using
the direct member access operator (.) with the object of that class.

Private: The class members


declared as private can be
accessed only by the functions
inside the class. They are not
allowed to be accessed directly
by any object or function
outside the class. Only the
member functions or the friend
functions are allowed to access
the private data members of a
class.

Protected: Protected access


modifier is similar to that of private access modifiers, the difference is that the class
member declared as Protected are inaccessible outside the class but they can be
accessed by any subclass(derived class) of that class.

class A
{
public:
int x;
protected:
int y;
private:
int z;
};

class B : public A
{ public:
int a=x// x is public
int b=y// y is protected
int c=z// z is not accessible from B
};

class C : protected A
{ public:
int a=x// x is protected
int b=y// y is protected
int c=z// z is not accessible from C
};

class D : private A // 'private' is default for classes


{ public:
int a=x// x is private
int b=y// y is private
int c=z// z is not accessible from D
};

If you run this code it’ll get compilation error, as data is not accessible. Commenting
inaccessible lines might be helpful.

c.
C++ allows specification of more than one function of the same name in the same scope.
These functions are called overloaded functions. Overloaded functions enable you to
supply different semantics for a function, depending on the types and number of
arguments.

For example, a print function that takes a std::string argument might perform very
different tasks than one that takes an argument of type double. Overloading saves you
from having to use names such as print_string or print_double. At compile time, the
compiler chooses which overload to use based on the type of arguments passed in by the
caller. If you call print(42.0), then the void print(double d) function will be invoked. If
you call print("hello world"), then the void print(std::string) overload will be invoked.

D.
Scope refers to the visibility of variables. In other words, which parts of your program
can see or use it.
A scope is a region of the program and broadly speaking there are three places, where
variables can be declared −

• Inside a function or a block which is called local variables,


• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.

Local Variables

Variables that are declared inside a function or block are local variables. They can be
used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own. Following is the example using local
variables −

#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}

Global Variables

Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. Following is the example
using global and local variables −

#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable
inside a function will take preference. For example −

#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;

return 0;
}
When the above code is compiled and executed, it produces the following result −

10

Another Example:
Ques 4:
a.
This type of non-member function will access the private member of class to get the job
done. So the function must be friend function.

using namespace std;


#include <iostream>
class Sample
{ private: int value;
public: Sample(){ value = 0;}
Sample(int c){ value = c;}

//making operator overloading declaration as friend function


friend Sample operator+(Sample &S1, Sample &S2);

void printValue(){cout<<"Value is : "<<value<<endl;}


};

//overator overloading function definition


Sample operator+(Sample &S1, Sample &S2)
{
Sample S;
S = S1.value+S2.value;
return S;
}

int main()
{
int i = 0;
Sample S1(100);
Sample S2(200);
Sample S3;
S3 = S1 + S2;

cout<<"S1 :"<<endl;
S1.printValue();

cout<<"S2 :"<<endl;
S2.printValue();

cout<<"S3 :"<<endl;
S3.printValue();
return 0;
}

Output

S1 :
Value is : 100
S2 :
Value is : 200
S3 :
Value is : 300

b.
Inheritance is one of the key features of Object-oriented programming in C++. It allows
user to create a new class (derived class) from an existing class(base class). The derived
class inherits all the features from the base class and can have additional features of its
own.

The capability of a class to derive properties and characteristics from another class is
called Inheritance.

Benefits of using inheritance:

• The most frequent use of inheritance is for deriving classes using existing classes,
which provides reusability. The existing classes remain unchanged. By reusability,
the development time of software is reduced.
• The derived classes extend the properties of base classes to generate more
dominant objects.
• The same base classes can be used by a number of derived classes in class
hierarchy.
• When a class is derived from more than one class, all the derived classes have
similar properties to those of base classes.

c.
Goto 2017 Ques 3b

d.
Private components do not get inherited by derive class.
A derived class doesn't inherit access to private data members. However, it does inherit
a full parent object, which contains any private members which that class declares.
Access public protected private
------------------------------------------------------------------------------
members of the same class yes yes yes
members of derived classes yes yes no
not members yes no no

CSE 2016
Ques 1:
a.
The problem is in constructor overloading. We can’t overload for same amount of
variable and same type of variable more than one time.

But instead we can have a overload when there is


• zero input
• one input
• two input

whenever there is a input variable missing, we can assign default values in them.

#include<iostream>
using namespace std;

class person{
private: int p,q;
public: person() : p(10), q(20) {cout<<p<<" "<<q<<"\n";}
person(int m, int n) : p(m), q(n) {cout<<p<<" "<<q<<"\n";}
person(int m) : p(m), q(30) {cout<<p<<" "<<q<<"\n";}

};

int main() {
person ob1;
person ob2(5);
person ob3(10,30);
}
b.
For fig 1,
The code is for finding maximum of two. Here, template has been overloaded. Template
is defined first for any type of data input.

template <class T>


T max (T &a, T &b) {
return (a>b)? a : b;
}

Then the second function is for specifically for int type data input.

template <>
int max <int> (int &a, int &b) {
cout<<"Called ";
return (a>b)? a : b;
}

As in main function, we have int type data it’ll automatically assigned to the second
function. The output will be: Called 20

For fig 2,
This is for finding minimum element of an array.

int main ()
{
int arr1[]= {10,20,15,12};
char arr2[]= {1,2,3};
}

Two array is declared, one int array, another char array.

int n1= sizeof(arr1)/sizeof(arr1[0]);


int n2= sizeof(arr2)/sizeof(arr2[0]);

Then number of element (stored in array) is determined by these lines.

cout<<arrMin <int,10000> (arr1,n1)<<endl;


cout<<arrMin <char,256> (arr2, n2);
Then two of arrays were sent to arrMin function and return data was printed.
In the arrMin function we have to input

• An array → arr[]
• Number of elements stored in corresponding array → n
• Data type of array element → int/char
• A threshold value of maximum which the array elements should not exceed →
256/10000

#include <iostream>
using namespace std;

template <class T, int max>


int arrMin(T arr[],int n)
{
int m=max;
for(int i=0; i<n; i++)
if (arr[i]<m)
m=arr[i];
return m;
}

int main ()
{
int arr1[]= {10,20,15,12};
int n1= sizeof(arr1)/sizeof(arr1[0]);
char arr2[]= {1,2,3};
int n2= sizeof(arr2)/sizeof(arr2[0]);
cout<<arrMin <int,10000> (arr1,n1)<<endl;
cout<<arrMin <char,256> (arr2, n2);
return 0;
}

The output will be 10 & 1.

Note: In the ques, the code is as below.

template <class T, int max>


int arrMin(T arr[],int n)
{
int m=max;
for(int i=0; i<n; i++)
if (arr[i]<<m)
m=arr[i];
return m;
}

if (arr[i]<<m) will shift whatever comes in arr[i] into m.

c.
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. Real
life example of polymorphism, a person at a same time can have different characteristic.
Like a man at a same time is a father, a husband, a employee. So a same person posses
have different behavior in different situations. This is called polymorphism.

In C++ polymorphism is mainly divided into two types:

• Compile time Polymorphism: This type of polymorphism is achieved by function


overloading or operator overloading. When there are multiple functions with same
name but different parameters then these functions are said to be overloaded.
Functions can be overloaded by change in number of arguments or/and change in
type of arguments. C++ also provide option to overload operators. For example, we
can make the operator (‘+’) for string class to concatenate two strings. We know
that this is the addition operator whose task is to add to operands. So a single
operator ‘+’ when placed between integer operands, adds them and when placed
between string operands, concatenates them.

• Runtime Polymorphism: This type of polymorphism is achieved by Function


Overriding. Function overriding on the other hand occurs when a derived class has
a definition for one of the member functions of the base class. That base function
is said to be overridden.

Ques 2
a.
#include <iostream>
using namespace std;
#include <string.h>

class String
{
private:
char str[200];

public:
String() { strcpy(str, ""); }
String(char s[]) { strcpy(str, s); }
void display() const { cout << str; }
String operator+(String ss) const
{
String temp;
if (strlen(str) + strlen(ss.str) < 200)
{
strcpy(temp.str, str);
strcat(temp.str, ss.str);
}
else
{
cout << "\nString overflow";
exit(1);
}
return temp;
}

bool operator==(String ss) const


{
bool res = strcmp(str, ss.str) == 0 ? true : false;
return res;
}
};

int main()
{
String s1;
String s2("Object oriented");
String s3;
s3 = s2 + s1;
s3.display();

if (s1 == s2)
cout << "\nS1 & S2 are unequal";
else
cout << "\nS1 & S2 are equal";
if (s2 == s3)
cout << "\nS2 & S3 are unequal";
else
cout << "\nS2 & S3 are equal";

return 0;
}
OUTPUT:

Object oriented
S1 & S2 are equal
S2 & S3 are unequal

b.
#include <iostream>
using namespace std;

int main()
{
int *p;
p = new int;
if (p)
cout << "Memory allocated to p --> Successful\n";
else
cout << "Memory allocated to p --> Failed\n";

*p = 29;

cout <<endl<< "Before Dellocation:" << endl;


cout << *p << endl;

delete p;
cout << "After Dellocation:" << endl;
cout << *p << endl;

return 0;
}
OUTPUT:

Memory allocated to p --> Successful

Before Dellocation:
29
After Dellocation:
15824216

Or,

#include <iostream>
using namespace std;

int main()
{
int *q = new int[5];
if (q)
cout << "Memory allocated to q --> Successful\n";
else
cout << "Memory allocated to q --> Failed\n";

for (int i = 0; i < 5; i++)


q[i] = i + 1;

cout << endl<< "Before Dellocation: " << endl;


for (int i = 0; i < 5; i++)
cout << q[i] << " ";

delete[] q;
cout << endl
<< "After Dellocation: " << endl;
for (int i = 0; i < 5; i++)
cout << q[i] << " ";
return 0;
}
OUTPUT:

Memory allocated to q --> Successful

Before Dellocation:
1 2 3 4 5
After Dellocation:
2061656 2031808 3 4 5

Or

#include <iostream>
using namespace std;
int main()
{

float *r = new float(75.25);


if (r)
cout << "Memory allocated to r --> Successful\n";
else
cout << "Memory allocated to r --> Failed\n";

cout << endl<< "Before Dellocation:" << endl;


cout << *r << endl;

delete r;
cout << "After Dellocation:" << endl;
cout << *r;
return 0;
}
OUTPUT:

Memory allocated to r --> Successful

Before Dellocation:
75.25
After Dellocation:
9.86556e-039

c.
cin.get() can tell you whether the input stream is end or not, this will happen when you
type Ctrl-D(or Ctrl-Z in windows) in the terminal. Except for this, cin.get() returns a
integer normally size 32 bits, which can be assigned to a char variable in most cases, but
when end of stream, cin.get() returns a -1 to tell you that no more characters exist.

The cin>>C; reads a single word, skipping over any leading space characters, and
stopping when it encounters a space character (which includes the end of the line).
The second cin.get(); reads a whole line, then consumes the end-of-line character so that
repeating this will read the next line.
The third cin.get(a,256) reads a whole line but leaves the end-of-line character in the
stream, so that repeating this will give no more input.
Ques 3
a.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<int> ques_onk_kothin;
ques_onk_kothin.push_back(9);
for (int i = 0; i < 98; i++)
ques_onk_kothin.push_back(1);
ques_onk_kothin.push_back(0);

cout << "Size: " << ques_onk_kothin.size() << "\n";


for (int i = 0; i < ques_onk_kothin.size(); i++)
cout << ques_onk_kothin.at(i) << " ";
return 0;
}
OUTPUT:

Size: 100
9 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0

b.
The code with friend function:

#include <iostream>
using namespace std;

class X
{
int x;
public:
X (int a) { x = a; }
friend int MAX(X a, X b)
{
if (a.x >= b.x)
return a.x;
else
return b.x;
}
};

int main()
{
X p(5), q(10);
cout << MAX(q, p);
}

i. Implementation of member function:


#include <iostream>
using namespace std;

class X
{
int x;
public:
X (int a) { x = a; }
int MAX(X p)
{
if (x >= p.x)
return x;
else
return p.x;
}
};

int main()
{
X p(5), q(10);
cout << p.MAX(q);
}

ii.
p & q both are X type data. Basically, these are integers. But as declared it store int type
data through X constructor.

Syntax is X (int a) { x = a; }

So, if an int type of data is pushed inside the brackets this constructor will be called.

It is done via following code:


X p(5), q(10);

iii.
The following code was used:

#include <iostream>
using namespace std;

class X
{
int x;

public:
X(int a) { x = a; }
int MAX(X p)
{
if (x >= p.x)
return x;
else
return p.x;
}
~X()
{cout << endl << "Destructor Called" ;}
};

int main()
{
X p(5), q(10);
cout << p.MAX(q);
}

OUTPUT:

10
Destructor Called
Destructor Called
Destructor Called

So, destructor is called 3 times. [ For p, q, p.MAX ]


c.
The member functions of every object have access to a sort of magic pointer named this,

which points to the object itself. Thus any member function can find out the address of
the

object of which it is a member. Here’s a short example, WHERE, that shows the
mechanism:

#include <iostream>
using namespace std;

class where
{
private:
char charray[10];
public:
void reveal()
{cout << "\nMy object's address is " << this;}
};

int main()
{
where w1, w2, w3;
w1.reveal();
w2.reveal();
w3.reveal();
cout << endl;
return 0;
}

OUTPUT:

My object's address is 0x61ff06


My object's address is 0x61fefc
My object's address is 0x61fef2

d.
OUTPUT:

0.25 0.0625
0.5 0.25
0.75 0.5625
1 1

Ques 4:
a.
Function Purpose
ios:ate open and seek to end immediately after opening
or, sets the stream's position indicator to the end of the stream on opening
ios:in perform input on the file
tellg() returns the current position of the get pointer
seekp() sets the put pointer at certain position
eof() returns nonzero (meaning TRUE) when there are no more data to be read
from an input file stream

b.
#include <iostream>
using namespace std;

double Division(float x, float y)


{
if (y == 0)
{ throw runtime_error("Math error: Attempted to divide by
Zero\n"); }
return (x / y);
}

int main()
{
double x, y, z;
cout << "Input 2 double type data: ";
cin >> x >> y;
try { z = Division(x, y);
cout << x << "/" << y << " = " << z << endl; }

catch (runtime_error &e)


{ cout << "Exception occurred" << endl << e.what(); }
}
OUTPUT:

Input 2 double type data: 592.65 0


Exception occurred
Math error: Attempted to divide by Zero
c.
OUTPUT:

content of second derived class.


content of first derived class.

Here,

D4 d4;
b = &d4;
b->display();

D4 has no display function. It can show display function from D3. As it is derived from
D3 i.e. it has access to D3 public elements. But D3 also lacks of display function. D3 is
derived from D2 which has a display function.

So, “content of second derived class.” gets printed.

Again,

D1 d3;
b = &d3;
b->display();

D1 has a display function. So, “content of first derived class.” gets printed.

2015
Ques 1
a.
A bottom-up approach is the piecing together of module (or small program) to give rise
to more complex program, thus making the original modules of the emergent program. A
bottom-up approach begins with low level design or development and ends with high
level design. In bottom-up approach, code is developed from modules and then these
modules are integrated with main function.
In OOP, you first write a base class, and constantly derive new child classes from the
existing base one (like a Car class will probably derive from a class called Vehicle). So,
you start from the basic blocks and go on making it a more complex design.

Applications:

• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• Al and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

b.
Class: ~ is a user defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is
like a blueprint for an object.

Object: ~ is an instance of a Class. When a class is defined, no memory is allocated but


when it is instantiated (i.e. an object is created) memory is allocated.

Default Argument: ~ is a value provided in a function declaration that is automatically


assigned by the compiler if the caller of the function doesn’t provide a value for the
argument with a default value.

#include <iostream>
using namespace std;

int sum(int x, int y, int z = 0, int w = 0)


{ return (x + y + z + w); }

int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
OUTPUT:

25
50
80

c.
#include <iostream>
using namespace std;
class smallobj
{
private:
int somedata;

public:
void setdata(int d)
{
somedata = d;
}
void showdata()
{
cout << "Data is " << somedata << endl;
}
};
int main()
{
smallobj s1, s2;
s1.setdata(1066);
s2.setdata(1776);
s1.showdata();
s2.showdata();
return 0;
}

OUTPUT:

Data is 1066
Data is 1776

d.
C++ was derived from C, and is largely based on it, but there are some legal C constructs
which are not legal C++. Conversely, ANSI C inherited several features from C++,
including prototypes and const, so neither language is really a subset or superset of the
other; the two also define the meaning of some common constructs differently.

The most important feature of C++ not found in C is of course the extended structure
known as a class which along with operator overloading makes object-oriented
programming convenient. There are several other differences and new features:
variables may be declared anywhere in a block; const variables may be true compile-
time constants; structure tags are implicitly typedeffed; an & in a parameter declaration
requests pass by reference; and the new and delete operators, along with per-object
constructors and destructors, simplify dynamic data structure management. There are a
host of mechanisms tied up with classes and object-oriented programming: inheritance,
friends, virtual functions, templates, etc. (This list of C++ features is not intended to be
complete; C++ programmers will notice many omissions.)

Some features of C which keep it from being a strict subset of C++ (that is, which keep C
programs from necessarily being acceptable to C++ compilers) are that main may be
called recursively, character constants are of type int, prototypes are not required, and
void * implicitly converts to other pointer types. Also, every keyword in C++ which is not
a keyword in C is available in C as an identifier; C programs which use words like class
and friend as ordinary identifiers will be rejected by C++ compilers.

In spite of the differences, many C programs will compile correctly in a C++


environment, and many recent compilers offer both C and C++ compilation modes.

Ques 2
a.
Function Overloading: ~ is a feature in C++ where two or more functions can have the
same name but different parameters.

#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}

OUTPUT:

Here is int 10
Here is float 10.1
Here is char* ten

b.
A constructor is a special type of member function that initializes an object automatically
when it is created. Constructor has the same name as that of the class and it does not
have any return type. Also, the constructor is always public.

Default constructor: The constructor that accept no parameter is called default


constructor.

Features of Constructor:

• Constructors have the same name as that of the class they belong to.
• Constructors are executed when an object is declared.
• Constructors have neither return value nor void.
• The main function of constructor is to initialize objects and allocate appropriate
iate memoty to objects.
• Though constructors are executed implicitly, they can be invoked explicitly.
• Constructors can have default values and can be overloaded.
• The constructor without arguments is called as default constructor.

c.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;

public:
Distance() : feet(0), inches(0.0) {}
Distance(int ft, float in) : feet(ft), inches(in) {}

void showdist()
{
cout << feet << "\'-" << inches << "\"";
}
};

int main()
{
Distance dist1(11, 6.25);
Distance dist2(dist1);
Distance dist3 = dist1;
cout << "\ndist1 = ";
dist1.showdist();
cout << "\ndist2 = ";
dist2.showdist();
cout << "\ndist3 = ";
dist3.showdist();
cout << endl;
return 0;
}

OUTPUT:

dist1 = 11'-6.25"
dist2 = 11'-6.25"
dist3 = 11'-6.25"

d. A type cast is basically a conversion from one type to another. T type conversion or
typecasting refers to changing an entity of one datatype into another. There are two
types of conversion: implicit and explicit.

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;
int sum = (int)x + 1;
cout << "Sum = " << sum;

return 0;
}

OUTPUT:

Sum = 2

Or,

#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
int b = static_cast<int>(f);

cout << b;
}

OUTPUT:

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

The mechanism of deriving a new class from an old one is called inheritance for
derivation). The old class is referred to as the base class and the new one is called the
derived class or subclass. The derived class inherits some or all of the traits from the
base class. A class can also inherit properties from more than one class or from more
than one level. A derived class with only one base class, is called single inheritance and
one with several base classes is called multiple inheritance. On the other hand, the traits
of one class may be inherited by more than one class. This process is known as
hierarchical inheritance. The mechanism of deriving a class from another 'derived class'
is known as multilevel inheritance.

b.
#include <iostream>
using namespace std;

class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

class Car: public Vehicle{

};

int main()
{
Car obj;
return 0;
}

OUTPUT:

This is a Vehicle

c.
Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.

#include <iostream>
using namespace std;

class A {
public:
int a;
A() { a = 10; }
};
class B : public virtual A {};

class C : public virtual A {};

class D : public B, public C {};

int main()
{
D object;
cout << "a = " << object.a << endl;

return 0;
}

OUTPUT:

a = 10
d.
A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class


template, in which case the entire class and all of its members are friends. To declare a
function as a friend of a class, precede the function prototype in the class definition with
keyword friend as follows –

class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

You might also like