Pyqs - C++
Pyqs - C++
Pyqs - C++
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;
}
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;
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.
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".
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];
};
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"; }
};
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>
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 &);
};
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.
#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);
};
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
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;
}
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.
#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
class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show();
return 0;
}
Output:
In Derived
Ques 3:
a.
#include<iostream>
using namespace std;
class base {
private: int a;
public:void disp(){cout<<"FROM BASE, a: "<<a<<endl;}};
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 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>
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);
}
iii) 1
Ques 4:
a.
pos = tellg(pos) → Return position (in bytes) of file pointer from start of file.
b.
c.
Prefix Decrement Operator Function:
ComplexNumber ComplexNumber::operator--()
{
--real;
--imaginary;
return *this;
}
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;
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
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
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
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
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.
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.
#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;
class GFG {
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.
#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";
}
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.
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
};
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 −
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.
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.
• 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.
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.
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};
}
• 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;
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;
}
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.
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;
}
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;
delete p;
cout << "After Dellocation:" << endl;
cout << *p << endl;
return 0;
}
OUTPUT:
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";
delete[] q;
cout << endl
<< "After Dellocation: " << endl;
for (int i = 0; i < 5; i++)
cout << q[i] << " ";
return 0;
}
OUTPUT:
Before Dellocation:
1 2 3 4 5
After Dellocation:
2061656 2031808 3 4 5
Or
#include <iostream>
using namespace std;
int main()
{
delete r;
cout << "After Dellocation:" << endl;
cout << *r;
return 0;
}
OUTPUT:
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);
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);
}
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.
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
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:
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;
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; }
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.
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.
#include <iostream>
using namespace std;
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.
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.
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;
}
};
};
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 {};
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.
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};