0% found this document useful (0 votes)
121 views38 pages

Oops Mock 1st

The document contains sample C++ code and explanations for: 1) A program to calculate the average marks of n students by taking input for each student's name, three subject marks, computing the average of the best two subjects, and outputting the results. 2) Explanations and sample code demonstrating constructors and inheritance in C++. 3) The differences between overloading and overriding along with sample code examples.

Uploaded by

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

Oops Mock 1st

The document contains sample C++ code and explanations for: 1) A program to calculate the average marks of n students by taking input for each student's name, three subject marks, computing the average of the best two subjects, and outputting the results. 2) Explanations and sample code demonstrating constructors and inheritance in C++. 3) The differences between overloading and overriding along with sample code examples.

Uploaded by

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

C++ mock paper solution

Section c:

Que1. Write a program in c++ to compute the average marks of n students in


the class. Take necessary assumptions.

Ans. #include<iostream>

Using namespace std;

Class student

{ Private:

Char name[10];

float s1, s2,s3;

float average;

Public:

Void read_data ();

void compute();

void write_data();

};

void student::read_data()

cout<<"\n enter the student name"<<"\n";

cin>>name;

cout<<"\n enter themarks in three subjects \n";


cin>>s1>>s2>>s3;

void student::compute()

if(s1<s2&&s1<s3)

average = (s2 +s3)/2.0;

else if(s2<s3)

average = (s1+s3)/2.0;

else

average = (s1+s2)/2.0;

void student::write_data()

cout<<"\n-------------------------------\n";

cout<<"\n name is"<<name;

cout<<"\n marks1 is "<<s1;

cout<<"\n marks2 is "<<s2;

cout<<"\n marks3 is "<<s3;

cout<<"average of best of two subjects is"<<average;

cout<<"\n-------------------------------\n";
}

int main()

student s[10];

int n,i;

cout<<"\n enter the number of students\n";

cin>>n;

for(i=0;i<n;i++)

s[i].read_data();

for(i=0;i<n;i++)

s[i].compute();

for(i=0;i<n;i++)

s[i].write_data();

return 0;

Que2. What are constructors? Write a sample code to show the working of
constructors with inheritance.

Ans. Automatic initialization of objects is carried out using a special member


function called a constructor.

“A constructor is a member function that is executed automatically whenever an


object is created”.

Characteristics:
1) They should be declared as public.
2) They do not have any return type, not even void
3) By default they are treated as inline functions \, if defined inside the class
definition.
4) They can have default arguments, if required.
5) They cannot be inherited, through any derived class.
6) They cannot be declared as virtual.

Constructor definition:

The name of the constructor function should be same as the class name

Syntax: constructor_name ([arguments])

// function body

Example: distance (int f, float i)

Feet = f;

Inches =I;

Calling a constructor: A constructor can be called in two ways- either implicitly or


explicitly.

Distance obj = Distance (5, 2.3); // explicit call

Distance obj (5, 2.3); // implicit call

// working of constructors along with the inheritance

#include<iostream>

Using namespace std;

Class parent
{

Public:

Parent ()

Cout<<”inside base class”<<endl;

};

// sub class

Class child: public parent

Public:

Child ()

Cout<<”inside the sub class”<<endl;

};

Int main()

{ // creating of the sub class

Child obj;

Return 0;

Output:
Inside base class

Inside sub class

Que3. What is the difference between overloading and overriding? Write a code
to show how overriding is achieved.

Ans. Comparison chart of overloading and overriding

Basis for the comparison overloading Overriding


Prototype Prototype will be In overriding all the
different as number of aspects of the function
arguments and type of should be same
arguments changes
Keyword Specific function while Function that is going to
writing function be overridden uses a
overloading definition is keyword ‘virtual’ in its
not required base class
Distinguishing factor The versions of the Assigning a class’s object
function that is called can decides which function is
be determined on the called.
basis of no. of
parameters.
Defining pattern Function is redefined Function defined in the
multiple times with base class will have
identical names but ‘virtual’ keyword and
numbers of parameters other definitions of
with their types are function do not have any
different. keyword.
Accomplishment time Compile time Run time
Constructor/virtual Constructor can be Virtual function can be
function overloaded overridden.

// show the working of overriding

#include<iostream>

Using namespace std;


Class Animal

Public:

Void makesound()

{ cout<<”animal sound”;

};

Class Dog: public Animal

Public:

Void makesound()

{ cout<<”Dogs bark”;

};

Class cat : public Animal

{ public:

Void makesound()

{ cout<<”cats meow”;

};

Int main ()

{
Animal a1;

A1.makesound ();

Cout<<endl;

Dog d1;

D1.makesound ();

Return 0;

Output:

Animals sound

Dogs bark

Cats meow

Que4. Write a program to overload unary ++ and unary –- operator.

Ans.

// program to overload unary ++ operator

#include<iostream>

Using namespace std;

Class NUM

Int n1, n2, n3;

Public:

NUM (int x, int y, int z)

{
N1 = x;

N2 = y;

N3 = z;

Void show ();

Void operator ++ ();

};

Void NUM::show ()

Cout<<”n1 =”<<n1<<endl<<”n2 = “<<n2<<endl<<”n3 = “<<n3<<endl;

Void NUM::operator ++ ()

n1 =n1+5;

n2 = n2+10;

n3 = n3+15;

Void main()

NUM obj (10, 20, 30);

Cout<<”the entered numbers are bellow.”<<endl;

Obj. Show ();


Obj. Operator ++ ();

Cout<<”after execution of operator function “<<endl;

Obj. Show ();

Output:

The entered numbers are as below:

N1 = 10

N2 = 20

N3 = 30

After execution of operator function

N1 = 15

N2 = 30

N3 = 45

// program to overload unary – operator

#include<iostream>

Using namespace std;

Class weight

Private:

Int kg;

Public:
Weight ()

K=0;

Weight (int x)

Kg =x;

Void printweight()

Cout<<”weight in kg: “<<kg<<endl;

Void operator -- (int)

Kg--;

};

Void main ()

Weight obj;

Obj.printweight ();

Obj--;
Cout<<”decrement weight”;

Obj.printweight ();

Output:

Que5. What do you mean by exception handling? Write a program to show how
it is achieved in c++.

Ans. The main objective of programming is to create error free programs. Errors
remain in the program due to mainly due to poor understanding of programming.
Error may be categorized into following two types.

a) Syntax error
b) Logical error

Errors which happen during compile time are known as syntax error or compile
time errors. On the other hand, errors which happen during execution of program
are known as run time error. Syntax error is not a problem as it can be easily
rectified. The main problem arises in case of run time error as it may cause minor
or major damage to the system.

Formally, an exception is defined as a run time error which may cause abnormal
termination of the program. C++ supports a mechanism known as exception
handling to control exceptions in a program.

Exception handling in c++

In c++ exception handling mechanism consists of following three components.

A) Try
B) Throw
C) Catch

the syntax is below:

try
{

…………………………………………………..

…………………………………………………………

…………………………………………………………

Throw (exception type);

Catch (exception type)

……………………………………………….

……………………………………………..

…………………………………………….

// program to illustrate the concept of exception handling mechanism

#include<iostream>

Using namespace std;

Void main ()

Int n1,n2;

Cout<<”enter two integers”;

Cin>>n1>>n2;

Int x = n1 – n2;

Int result =0;


Try

If(x!=0)

Result = n1/x;

Cout<<”result is “<<result<<endl;

Else

Throw(x);

Catch (int y)

Cout<<”exception caught as x becomes 0”<<endl;

Cout<<”kindly enter two different values as input”<<endl;

Output: 1

Enter two integers

4 2

Result is 2

Output: 2

Enter two integers

4 4
Exception caught as x becomes 0

Kindly enter two different values as input

Section B

Que1. Write a sample code to difference between c and c++.

Ans. Code in c

#include<stdio.h>

Int main ()

Printf (“hello world”);

Return 0;

Output:

Hello world

Explanation:

#include<stdio.h>: it is a preprocessor command. The stdio.h file contains


functions such as printf () and scanf () to take input and display output
respectively.

If we use printf () without using #include<stdio.h> the program will not be


compiled.

Main (): the execution of a c program starts from the main () function.

Printf (): it is library function to send formatted output to the screen. In this
program the printf () function display hello world text on the screen.
Code in c++

#include<iostream>

Using namespace std;

Int main ()

Cout<<”hello world”;

Return 0;

Output:

Hello world

Explanation:

#include<iostream>: this statement tells the compiler to include iostream file.


This file contains pre defined input/output functions that we can use in our
program.

Using namespace std: A namespace is like a region, where we have functions,


variables, etc, and their scope is limited to that particular region. Here std is a
namespace name, this tells the compiler to look into that particular region for all
the variables, functions, etc.

Cout<<”hello world”: the cout object belongs to the iostream file and the
purpose of the object is to display the content between quotes as it is on the
screen.

Que2. Write a code to compute factorial of a number, use of constructors shall


be done.

Ans. Using copy constructor


Copy constructor is a special type of constructor which takes an object as an
argument. It is used for creating the second object.

Following program is calculating the factorial of a number using copy constructor.

#include<iostream>

Using namespace std;

Class fact

Int n, I, facti;

Public:

Fact (int x) // copy constructor

n =x;

Facti = 1;

Fact (fact &x)

n = x.n;

facti = 1;

Void calculates ()

For (i=1;i<n;i++)
{

Facti = facti *I;

Void display ()

Cout<<”\n Factorial “<<facti;

};

Int main()

Int x;

Cout<<”\n enter value”;

Cin>>x;

Fact f1(x);

F1.calculates ();

F2.dispaly ();

Fact f2 (f1); // cpy constructor takes an object as an argument

F2.calculates ();

F2.dispaly ();

Return 0;

}
Output:

Enter value: 5

Factorial: 120

Factorial: 120

Que3. What is polymorphism? Write a code to show the use of polymorphism .

Ans. Polymorphism is made of two Greek words “poly” and “morph”. Poly means
many and morph means several forms. So formally polymorphism can be defined
as below:

Definition: the process in which various forms of a single function can be defined
and utilized by different objects to perform similar types of operation. The
process of polymorphism is categorized into following hierarchy:

Polymorphism

Compile time
Run time
Polymorphism
Polymorphism

Virtual function
Function Operator Overloading
Overriding

Compile time polymorphism


#include<iostream>

Using namespace std;

Class Add

Public:

Int sum (int num1, int num2, int num3)

Return (num1 + num2 + num3)

Int sum (int num1, int num2)

Return num1 + num2;

};

Int main ()

Add obj;

// this will call the first function

Cout<<”output: “<<obj.sum (10, 20)<<endl;

// this will call the second function

Cout<<”output: “<<obj.sum (11,22,33);

Return 0;
} output:

Output: 30

Output: 66

Example of run time polymorphism

#include<iostream>

Using namespace std;

Class A

Public:

Void disp ()

{ cout<<”super class function”<<endl;

};

Class B: public A

Void disp ()

Cout<<”sub class function”;

};

Int main ()
{

// parent class object

A obj;

Obj. disp ();

// child class object

B. obj2;

Obj2. Disp();

Return 0;

Output:

Super class function

Sub class function

Section A

Que1. Define the term object and class.

Ans. Object: An object is a real world entity which has some features and
behaviors. An object has its own existence.

Class: A class is a collection of objects which posses similar features and behaviors

Ideally, class does not exist on its own. It exists due to the objects.

To understand this, consider the following examples.

1. Class: student
Object: Rahul, mukesh, priya etc…
Features:
 Name
 Branch
 Roll
 Semester
 Contact number

Behaviors:

 Academic performance
 Reading capacity
 Understanding level
2. Class: bike
Object: pulsar, shine. Active etc…
Features:
 Company name
 Model name and number
 Color

Behaviors:

 Speed
 Average
 Mileage
 Brake system
 Sound system
 Lamp

If we analyze the above two examples then we find that both class have some
objects. Objects of some student class possess similar properties whereas objects
of bike class possess similar properties. So, it is very important that the objects of
similar features must belong to the same class.

Que2. List the basic difference in c and c++

Ans. Comparison chart of c and c++


Basic of difference c C++
founded Developed by Dennis Developed by bjarne
Ritchie at AT & T bell stroustrup at bell labs
labs between 1969 and starting in 1979.
1973
language Procedure oriented Supports both
language procedural and object
oriented programming
paradigm; called a
hybrid language
Approach Follows top down Follows bottom up
approach approach
Drive Function-driven Object-driven language
language
Building blocks functions Objects
keyword Contain 32 keywords Contain 52 keywords
Oops concept As ‘c’ language is As an object oriented
procedure oriented language, c++ supports
language, it does not class, object, data
supports oops concepts hiding, polymorphism,
such as class, object, inheritance, abstraction
inheritance etc. etc.

Functions Does not support Support function and


function and operator operator overloading.
overloading. Supports exception
Does not support handling.
exception handling. Uses namespace.
Does not have
namespace feature
Memory functions Uses malloc () and Uses operators new and
calloc() and free() delete for the same
functions for allocating purpose.
and deallocating
memory.

File extension Has file extension .c Has file extension .cpp


Que3. What do you mean by inheritance?

Ans. Inheritance:

Inheritance is one of the most important and useful characteristics of object


oriented programming language. Basically inheritance means adopting features
by newly created thing from the existing one.

Formally, inheritance can be defined as the process of creating a new class from
one or more existing classes. The existing class is known as base class or parent
class or super class whereas the newly created class is known as derived class or
child class or sub class. Inheritance provides a significant advantage in terms of
code reusability. Consider the diagram show below:

(Base class)
Class A
Inherit

Class B (Derived class)

Due to this the derived class B inherits the features of base class A. however;
the derived class can also have its own features. Now the terms reusability means
that the derived class object can access the base class members also.

Que4. What is data hiding?

Ans. Data encapsulation led to the important oop concept of data hiding.

The wrapping of data and functions into a single unit (called class) is known as
encapsulation.

In c++, encapsulation can be achieved by using class.

By data encapsulation, data is not accessible to the outside the class. Only those
functions which are in the class can access.
Functions of the class provide the interface between the objects data and outside
objects/functions.

C++ supports the properties of encapsulation and data hiding through the
creation of user defined types, called classes.

#include<iostream>

Using namespace std;

Class myrank

Int a; // default accessibility is private

Public:

Void read ();

Void print ();

};

Void myrank:: read ()

Cout<<”enter any integer value”<<endl;

Cin>>a;

Void myrank::print ()

Cout<<”the value is “<<a<<endl;

}
Int main ()

Myrank k;

k.read ();

k.print ();

return 0;

Output:

Enter integer value 666

The value is 666

Que5. Differentiate between call by value and call by reference.

Ans.

Basis of comparison Call by value Call by reference


Basic A copy of the variable is A variable itself is passed
passed
Effect Change in a copy of Change in the variables
variable does not modify affects the value of
the original value of variable outside the
variable outside the function also.
function
Calling parameters Function-name (variable- Function_name
name1, variable-name2, (&variable_name1,
….); &variable_name2, ….);
// in case of object
Object.func_name
(object);

Receiving parameters Type function_name Type function_name


(type variable_name1, (type*variable_name1,
type variable_name2,…) type*variable_name2…)
Default calling Primitive types are Objects are implicitly
passed using “call by passed using “call by
value”. reference”.

Que5. What is aggregation?

Ans. In c++ aggregation is a process in which one class defines another class as
any entity reference. It is another way to reuse the class. It is form of association
that represents HAS-A relationship.

C++ Aggregation example:

Let’s see an example of aggregation where employee class has the reference of
address class as data members. In such way, it can reuse the members of Address
class.

#include<iostream>

Using namespace std;

Class Address

Public:

String addressline, city, state;

Address(string addressline, string city, string state)

This->addressline = addressline;

This->city = city;

This->state = state;
}

};

Class employee

Private:

address* Address; // employee HAS-A Address

public:

int id;

string name;

employee(int id, string name, Address* address)

This->id = id;

This->name = name;

This->address = address;

Void display()

Cout<<id<<””<<name<<””<<address->addressline<<””<<address-
>city<<””<<address->state<<endl;

};

Int main()
{

Address a1 = Address(“c-146, sec-15”, “Noida”, “UP”);

Employee e1 = employee (101, “nakul”, &a1);

e1.display();

Output:

101 nakul c-146, sec-15 noida UP

2nd mock paper solution

Que1. Explain the term abstraction.

Ans. Abstraction refers to showing only essential features of the application and
hiding the details. In c++ classes provide methods to the outside world to access
and use the data variables, but the variables are hidden from direct access. This
can be done by specifiers.

For example: human being’s can talk, walk, hear, eat but the details are hidden
from the outside world. And second example of abstraction the real life example
of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car.

#include<iostream>

Using namespace std;

Class implementAbstraction

{
Private:

Int a, b;

Public:

// method to set values of private members

Void set (int x, int y)

a = x;

b = y;

Void display ()

Cout<<”a = “<<a<<endl;

Cout<<”b = “<<b<<endl;

};

Int main ()

implementAbstraction obj;

obj.set (10, 20);

obj.display ();

return 0;
}

Output:

a = 10

b = 20
Que2. Explain overriding with example.

Ans. If derived class defines same function as defined in its base class, it is known
as function overriding in c++. It is used to achieve runtime polymorphism. It
enables you to provide specific implementation of the function which is already
provided by its base class.

#include<iostream>

Using namespace std;

Class Animal

Public:

Void eat ()

Cout<<”eating “;

};

Class dog: public Animal

Public:
Void eat ()

Cout<<”eating bread”;

};

Int main ()

dog d = dog ();

d.eat ();

return 0;

Section B

Que1. Write a sample code to show the structure of c++ program code.

Ans. General structure of a c++ program

C++ headers
Class definition
Member function definition
Main function
- Link section (c++ header)

Link section is where header files required for the program are included. Header
file consist function prototype and on program execution. They may predefined
like iostream, string, cmath etc. or user-defined.

Syntax: #include<header-filename> //predefined

#include<header-filename> //user defined


- Class definition

In this section class used in the program are declared and/or defined. Body of
class is enclosed by curly brackets and ends with a semicolon. Class consists of
attributes and functions which are the members of that

Syntax: class classname

Private:

Attributes;

Methods ();

Public:

Attributes;

Methods ();

Protected:

Attributes;

Methods ();

For example:

Class example

Private:

Int a, b;
Public:

Void input ();

Void displaysum ();

};

Member function definition

Member function can be defined inside or outside class. If the member function is
defined outside the class, we need to use class name to which the function and
scope resolution (::) before function name.

Syntax: return-type class name :: function_name (argument list)

Body of the function

Main function

Main is the most important function of c++ program. This is where the program
execution always begins. The main () function is compulsory in a c++ program.

Syntax:

Int main ()

Statement;

----------------------

Que2. Explain different types of inheritance with the help of a sample program.

Ans.

You might also like