You are on page 1of 45

Name Course Year Level

OOP 1

TABLE OF CONTENTS
PHYSICS 1: OBJECT ORIENTED PROGRAMMING.
PRELIM
Chapter 1: Introduction of OOP
Activity 1..........................................................................................................................1

Chapter 2: Function in c++ &Object and classes


Activity 2..........................................................................................................................3

Chapter 3: Constructors and Destructors,Operator Overloading and Type Conversions


Activity 3..........................................................................................................................5

CHAPTER 4: Inheritance(Extending Classes),Pointers, Virtual Functions and Polymorphism


Activity 4..........................................................................................................................7

MIDTERM
CHAPTER 5: M a n a g i n g c o n s o l e i n p u t / o u t p u t o p e r a t i o n s

Activity 5...........................................................................................................................10

CHAPTER 6: Working with C++ files


Activity 6...........................................................................................................................13

CHAPTER 7: OO System Development


Activity 7..........................................................................................................................17

FINALS
CHAPTER 8: Template
Activity 8................................................................................................................. 19

CHAPTER 9: Exception Handling


Activity 9................................................................................................................. 21

CHAPTER 10: ENCAPSOLATION


Activity 10................................................................................................................ 23

OBJECT ORIENTED
OOP 2

CHAPTER 1: INTRODUCTION OF OOP

OBJECTIVES:

represent real-life entities of problems in system design


design system with open interfaces
develop modules that are tolerant of any changes in future
improve software productivity and decrease software cost
improve the quality of software

Identifying INTODUCTION OF OOP


INTRODUCTION
Now that we know some of the causes, what exactly was the software crisis? It is a period of
time marked by bungled software projects, whose common problems included:

 Projects that ran over-budget


 Projects that ran over-time
 Software that made inefficient use of calculations and memory
 Software was of low quality
 Software that failed to meet the requirements it was developed to meet
 Projects that became unmanageable and code difficult to maintain
 Software that never finished development

ACTIVITY 1.1
Answer the following Questions

1. When was the time that many software project failed?(answer 1960’s)

2. This ambitious project was undertaken by IBM to create a single operating system

that would run on all mainframes manufactured by IBM.(answer IBM OS/360

PROJECT (1963-1965)

3.  the most chilling software failure in the history of Computer Science (Answer The

therac-25

4. was designed to be the most advanced baggage system in the world (Answer The

Denver International Airport Baggage System)

OBJECT ORIENTED
OOP 3
5. This was the sad culmination of a decade-long project costing $7 billion ( Answer

Ariane 5 rocket )

6. This project was slated to open in August 2003 (Answer German Toll Collect

System)

7. A website where Americans without access to employer-based health insurance

could enroll in a competitively-priced insurance plan.( Answer Healthcare.gov launch)

8. Was discovered in the open-source library OpenSSL (Answer Heartbleed)

9-10. Are processor-based vulnerabilities found in 2018 .(Answer Meltdown and

spectre exploits)

OBJECT ORIENTED
OOP 4

ACTIVITY 1.2
Fill in the blank
1. _______restricting the growth of computing field due to huge gap between hardware developments
and making use of it through non availability of software systems and competent software development
staff.( Answer Abstract software Crisis)
2. This term was given by F. L. Bauer at the first NATO Software Engineering Conference
in_________( Answer 1968)
3. During the 1990's, the cost of ownership and maintenance increased by_____(Answer 30% over
the 1980's)
4. The average software project overshoots its schedule by_______(Answer half)
5. Project planning means______(Answer creating work breakdown)

ACTIVITY 1.3

Direction: Defined the following reason Responsible for Software Crisis:

1. The problem of scale


2. Software is expensive
3. Software is late:
4. Software is unreliable:
5. Inconsistent productivity:

OBJECT ORIENTED
OOP 5

CHAPTER 2: Function in c++ &Object and classes


OBJECTIVES:

 Illustrate the representation of Software Evaluation


 Demonstrating the Software Evaluation
INTRODUCTION

Functions are the building blocks of C++ programs where all the program activity occurs. Function is a
collection of declarations and statements. .
ACTIVITY 2.1

Answer the following Questions:

1) what is a function ? How will you define a function in C++ ?

2) How are the argument data types specified for a C++ function? Explain with

Suitable example.

3) What types of functions are available in C++ ? Explain.

4) What is recursion? While writing any recursive function what thing(s) must be taken care of ?

5) What is inline function? When will you make a function inline and why ?

OBJECT ORIENTED
OOP 6

ACTIVITY 2.2

Define a class student with the following specifications: (20 Pts.)

ACTIVITY 2.3

FILL IN THE BLANK


1. _______(a large single list of instructions) becomes difficult to understand. For this reason functions
are used. (ANSWER: Monolethic program)

2. ________the data that the function receives when called/invoked from another function. (ANSWER
Arguments of a function)

3. C ++ allows a function to assign a parameter the default value in case no argument for that
parameter is specified in the function call. (ANSWER: Default Arguments)

4._________A C++ function may have constant arguments(s). These arguments(s) is/are treated
as constant(s). These values cannot be modified by the function. (ANSWER: Constant Argument)

5._________In this method the values of the actual parameters (appearing in the
function call) are copied into the formal parameters (appearing in the function definition), i.e., the
function creates its own copy of argument values and operates on them. (ANSWER: Call by value)

OBJECT ORIENTED
OOP 7

CHAPTER 3: Constructors and Destructors,Operator Overloading


and Type Conversions
OBJECTIVES:

 Focus on constructors , destructors, variants in them, operator overloading, type conversions.


INTRODUCTION:

A constructor (having the same name as that of the class) is a member function which
is automatically used to initialize the objects of the class type with legal initial values.
Destructors are the functions that are complimentary to constructors. These are used to deinitialize
objects when they are destroyed. A destructor is called when an object of the class
goes out of scope, or when the memory space used by it is de allocated with the help of delete
operator.

ACTIVITY 3.1

Answer the following questions below

1.How can we restrict dynamic allocation of objects of a class using new?


By overloading new operator
A
By making an empty private new operator.
B

By making an empty private new and new[] operators (Answer)


C

By overloading new operator and new[] operators


D

2.Which of the following operators cannot be overloaded?

. (Member Access or Dot operator)


A
?: (Ternary or Conditional Operator )
B
:: (Scope Resolution Operator)
C
.* (Pointer-to-member Operator )
D
All of the above (Answer)
E

OBJECT ORIENTED
OOP 8

3.Which of the following operators are overloaded by default by the compiler in every user defined
classes even if user has not written?
1) Comparison Operator ( == )
2) Assignment Operator ( = )

Both 1 and 2
A
Only 1
B
Only 2 (Answer)
C
None of the two
D

4.Which of the following operators should be preferred to overload as a global function rather than a
member method?
Postfix ++
A
Comparison Operator
B
Insertion Operator << (Answer)
C
Prefix++
D

5.How does C++ compiler differs between overloaded postfix and prefix operators?
C++ doesn't allow both operators to be overloaded in a class
A
A postfix ++ has a dummy parameter (Answer)
B
A prefix ++ has a dummy parameter
C
By making prefix ++ as a global function and postfix as a member function.
D
 

OBJECT ORIENTED
OOP 9

ACTIVITY 3.2

Direction: Run the following program, and choose the correct answer Below. (20 pts.)

 Predict the output


#include<iostream>
using namespace std;
class A
{
    int i;
public:
    A(int ii = 0) : i(ii) {}
    void show() {  cout << i << endl;  }
};

class B
{
    int x;
public:
    B(int xx) : x(xx) {}
    operator A() const {  return A(x); }
};

void g(A a)
{
    a.show();
}

int main()
{
    B b(10);
    g(b);
    g(20);
    return 0;
}

Run on IDE

Compiler Error
A
10 (Answer)
B 20 (Answer)
20
C 20
10
D 10

OBJECT ORIENTED
OOP 1

ACTIVITY 3. 3

Direction: Run the following program, and choose the correct answer Below. (20 pts.)

 What is the Output of following program?


#include <iostream>
using namespace std;
class Test2
{
    int y;
};

class Test
{
    int x;
    Test2 t2;
public:
    operator Test2 ()  { return t2; }
    operator int () { return x; }
};

void fun ( int x) { cout << "fun(int) called"; }


void fun ( Test2 t ) { cout << "fun(Test 2) called"; }

int main()
{
    Test t;
    fun(t);
    return 0;
}

Run on IDE

fun(int) called
A
fun(Test 2) called
B
Compiler Error: Ambiguous call to fun() (Answer)
C

OBJECT ORIENTED
OOP 1

CHAPTER 4: Inheritance(Extending Classes)


Pointers, Virtual Functions and Polymorphism
Virtual Functions and Polymorphism
OBJECTIVES:

 The main use of virtual function is to achieve Runtime Polymorphism.


 to create a list of base class pointers and call methods of any of the derived
classes without even knowing kind of derived class object.

INTRODUCTION
A virtual function is a member function which is declared in the base class
using the keyword virtual and is re-defined (Overriden) by the derived class.
The term Polymorphism means the ability to take many forms. It occurs if
there is a hierarchy of classes which are all related to each other by
inheritance

ACTIVITY 4.1

Direction: Run the following program, and choose the correct answer Below. (20 pts.)
 Predict output of the following program
#include<iostream>
using namespace std;

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();

    Base &br = *bp;


    br.show();

    return 0;
}

OBJECT ORIENTED
OOP 1

Run on IDE

In Base
A In Base
In Base
B In Derived
In Derived (Answer)
C In Derived (Answer)
In Derived
D In Base

ACTIVITY 4.2

Direction Choose the letter of the correct Answer (2pts. Each)

1. What is Inheritance in C++?


A. Wrapping of data into a single class
B. Deriving new classes from existing classes (Answer)
C. Overloading of classes
D. Classes with same names
2. How many specifiers are used to derive a class?
A. 1
B. 2
C. 3 (Answer)
D. 4
3. Which specifier makes all the data members and functions of base class inaccessible by the derived
class?
A. private (Answer)
B. protected
C. public
D. both private and protected

OBJECT ORIENTED
OOP 1

4. If a class is derived privately from a base class then ______________________________


A. no members of the base class is inherited
B. all members are accessible by the derived class
C. all the members are inherited by the class but are hidden and cannot be accessible
D. no derivation of the class gives an error
5. Which access specifier is used where one wants data members to be accessed by other classes but
not from outside objects?

A. private

B. Protected (Answer)

C. public

D. both protected and public

ACTIVITY 4.3

Direction: Run the following program, and choose the correct answer Below. (20 pts.)

 What will be the output of the following C++ code?

#include <iostream>#include <string>using namespace std;class Mammal{

public:

Mammal(){

cout<<"I'm a Mammal\n";

~Mammal(){}};

 class Human: public Mammal{

public:

Human(){

cout<<"I'm a Human\n";

~Human(){}};

OBJECT ORIENTED
OOP 1
 class Male: public Human{

public:

Male(){

cout<<"I'm a Male\n";

~Male(){}};

 class Female: public Human{

public:

Female(){

cout<<"I'm a Female\n";

~Female(){}};

 int main(int argc, char const *argv[]){

Male M;

return 0;}

A. I'm a Mammal I'm a Human I'm a Male (Answer)


B. I'm a Mammal I'm a Human I'm a Female
C. I'm a Human I'm a Male
D. I'm a Mammal I'm a Male

OBJECT ORIENTED
OOP 1

CHAPTER 5: Managing console input /output operations


OBJECTIVES:

 Understanding the console of input/ output operations.


 Applying concepts of managing console input/ output operations.
INTRODUCTION:

C++ supports two complete I/O systems: the one inherited from C and the object
oriented I/O system defined by C++ (hereafter called simply the C++ I/O system). Like
C-based I/O, C++'s I/O system is fully integrated. The different aspects of C++'s I/O
system, such as console I/O and disk I/O, are actually just different perspectives on the
same mechanism.Every program takes some data as input and generates processed
data as output following the input-process-output cycle.C++ supports all of C’s rich set
of I/O functions that can be used in the C++ programs.But these are restrained from
using due to two reasons ,first I/O methods in C++ supports the concept of OOP and
secondly I/O methods in c can not handle the user defined data types such as class
objects.C++ uses the concept of streams and stream classes to implement its I/O
operation with the console and disk fils..

ACTIVITY 5.1

Matching type :
Put the right response in the box provided.

1.Contains basic facilities that are used by all A


other input and output classes

2.It declares input functions such as put() and C


write()

3.It declares input functions such as get(), B


getline(), and read()
4.It acts as a base for filebuf class used ios file. E

5.Inherits the properties of ios stream and D


ostream through multiple inheritances and thus
contains all the input and output functions.

A. ios (General input/output stream class B. istream (Input stream)


B. ostream (Output Stream) D. iostream (Input/output stream)

E.Streambuf

OBJECT ORIENTED
OOP 1
ACTIVITY 5.2

Answer the following questions ,Choose the letter of the correct answer

1. Which header file is used with input and output operations of C in C++?

A. stdio.h
B. Cstdio (Answer)
C. iostream
D. Streamio

2.Which will be used with physical devices to interact from C++ program?

A. Programs
B. Library
C. Streams (Answer)
D. Iterators

3.How many streams are automatically created when executing a program?

A. 1
B. 2
C. 3 (Answer)
D. 4

4.What is the benefit of c++ input and output over c input and output?
A. Type safety ( Answer)
B. Exception
C. Both Type safety & Exception
D. Sequence container

5. How many indicators are available in c++?


A. 4
B. 3 (Answer)
C. 2
D. 1

OBJECT ORIENTED
OOP 1
ACTIVITY 5.3

Direction: Run the following program, and choose the correct answer Below. (20 pts.)

What is the name of the myfile2 file after executing the following C++ code?

1.
#include <stdio.h>

2.
3.
int main ()

4.
5.
{

6.
7.
int result;

8.
9.
char oldname[] = "myfile2.txt";

10.
11.
char newname[] = "newname.txt";

12.
13.
result = rename(oldname, newname );

14.
15.
if (result == 0)

16.
17.
puts ( "success" );

18.
19.
else

20.
21.

OBJECT ORIENTED
OOP 1
perror( "Error" );

22.
23.
return 0;

24.
25.
}

26.
A. name
B. new
C. newname (Answer)
D. Error

OBJECT ORIENTED
OOP 1

CHAPTER 6: WORKING WITH C++ FILES

OBJECTIVES:

 Knowing how to work with C++ files


 Applying the use of C++ files
INTRODUCTION
When a large amount of data is to be handled in such situations floppy disk or hard
disk are needed to store the data .The data is stored in these devices using the concept of
files. A file is a collection of related data stored in a particular area on a disk. Programs
can be designed to perform the read and write operations on these files.

ACTIVITY 6.1

Choose the letter of the correct answer:

1.By default, all the files in C++ are opened in _______ mode.
A) Text (Answer)
B) Binary
C) ISCII
D) VTC

2.What is the use of ios::trunc mode?


A) To open a file in input mode
B) To open a file in output mode
C) To truncate an existing file to half
D) To truncate an existing file to zero (Answer)

3.Which of the following is the default mode of the opening using the ofstream class?
A) ios::in
B) ios::out (Answer)
C) ios::app
D) ios::trunc

4.What is the return type open() method?


A) int
B) char
C) bool (Answer)
D) float

OBJECT ORIENTED
OOP 2

5.Which of the following is not used to seek file pointer?


A) ios::set (Answer)
B) ios::end
C) ios::cur
D) ios::beg

6.Which header file is required to use file I/O operations?


A) <ifstream>
B) <ostream>
C) <fstream> (Answer)
D) <iostream>

7.Which of the following is used to create an output stream?


A) ofstream (Answer)
B) ifstream
C) iostream
D) fsstream

8-10 Write a C++ program to write number 1 to 100 in a data file NOTES.TXT

(Answer)

#include<fstream.h>

int main()
{
ofstream fout;
fout.open("NOTES.TXT");
for(int i=1;i<=100;i++)
fout<<i<<endl;
fout.close();
return 0;
}

OBJECT ORIENTED
OOP 2

ACTIVITY 6.2
DIRECTION: INSERT ALL THE CORRECT ANSWER BELLOW

File Mode Operation

PARAMETER MEANING
A (answer) Append to end-of-file
B (answer) Go to end-of-file on opening
C (answer) Binary file
D (answer) Open file for reading only
E (answer) Open fails if file the file does not exist
F (answer) Open fails if file the file does not exist
G (answer) Open file for writing only
H (answer) Delete the contents of the file if it exists

A. ios::app
B. ios::ate
C. ios::binary
D. ios::in
E. ios::nocreate
F. ios::noreplace
G. ios::out
H. ios::trunk

OBJECT ORIENTED
OOP 2

ACTIVITY 6.3

ANSWER THE FOLLOWING QUESTIONS BELLOW

1. What are input and output streams?

2. What are the various classes available for file operations.

3. What is a file mode ?describe the various file mode options available.

4.Describes the various approaches by which we can detect the end of file condition.

5.What do you mean by command line arguments?

OBJECT ORIENTED
OOP 2

CHAPTER 7: OBJECT ORIENTED SYSTEM


DEVELOPMENT
OBJECTIVES:
 In this chapter, we shall review some of the conventional approaches that are being
widely used in software development and then discuss some of the current ideas that
are
applicable to the object-oriented software developmen t.

INTRODUCTION:
Software engineers have been trying various tools, methods, and procedures to control
the process of software development in order to build high quality software with
improved productivity. The methods provide “how to s” for building the software while
the tools provide automated or semi-automated support for the methods. They are used
in
all the stages of software development process, namely, planning, analysis, design,
development and maintenance. The software development procedures integrate the
methods and tools together and enable rational and timely development of software
systems. They provide guidelines as to apply the methods and tools, how to produce
the
deliverables at each stage, what controls to apply, and what milestones to use to
assess
the progress.
ACTIVITY 7.1

FILL IN THE BLANK:

1._________ covers a detailed study of the requirements of both the user and the
Software (Answer:ANALYSIS)

2._________deals with various concepts of system design such as data


structure, software architecture, and algorithms (Answer: DESIGN)

3.__________refers to the translation of the design into machine-readable form. The


more detailed the design, the easier is the coding, and better its reliability.(Answer:
CODING)
OBJECT ORIENTED
OOP 2

4._____________may involve the individual units and the whole systems. It requires a
detailed plan as to what, when and how to test. (Answer: TESTING)

5._____________ ensures that these changes are incorporated wherever necessary.


(Answer: MAINTENANCE)

6. The _______ developed in the 1960’s and 1970’s are called the traditional tools.
(Answer:FIRST GENERATION TOOLS)

7.The second generation tools introduced in the


late ___________ and early 1980’s are meant for the structured systems analysis and
design and therefore they are known as the structured tools (Answer: 1970’s)

8.The recent tools are the __________ones evolved since late 1980’s to suit the object-
oriented analysis and design.(Answer: THIRD GENERATION)

9.__________A graphical representation of the important inputs, outputs, and data


flow among the key points in the system.(Answer: SYSTEM FLOWCHARTS)

10.__________A narrative description of executing a procedure. (Answer:PLAY SCRIPT)

OBJECT ORIENTED
OOP 2

ACTIVITY 7. 2

THE SYSTEM DEVELOPMENT TOOLS

CHOOSE YOUR ANSWER INSIDE THE BOX BELOW

1. A graphical representation of the important inputs, outputs, and data


flow among the key points in the system.(A)

2. A graphical representation of program logic.(C)

3. A narrative description of executing a procedure.(B)

4. A format designed for putting the input data or displaying results.(D)

5. A chart showing the relationship between different modules of a system.(E)

6. A diagram showing the inputs and their sources and the outputs and
their destinations. (F)

7. They describe the flow of data between various components of a


system. It is a network representation of the system which includes processes and data
files.(G)

8. A structured repository of data about data. It contains a list of terms and


their definitions for all the data items and stores. (I)

9. A graphical representation of the control logic of functions (modules)


representing a system.(H)

10. A table of configurations for defining a problem and the actions to be


taken. It presents the logic that tells us what action to take when a given condition is true
or otherwise.(J)

11. A graphic representation of the condition and outcomes that resemble the
branches of a tree.(K)

.
A.System flowcharts
B.Play script:
C.Program flowcharts:
D.Layout forms:
E.Grid charts
F.Context diagrams:
G.Data flow diagrams:

OBJECT ORIENTED
OOP 2
H.Structure chart
I.Data dictionary:
J.Decision table:
K.Decision tree:

ACTIVITY 7.3

Name each box in the object-oriented software development Fountain model.

OBJECT ORIENTED
OOP 2
CHAPTER 8: TEMPLATE

OBJECTIVES:

 Understanding the concept of TEMPLATES

INTRODUCTION
Template is a new concept which enables us to define generic and functions and thus
provides support for generic programming. Generic programming as an approach where
generic types are used as parameters in algorithms so that they work for a variety of
suitable data types and data structures.
A template can be used to create a family of classes or functions. For example, a class
template for an array class would enable us to create arrays of various data types such as
int array and float array .similarly, we can define a template for a function, say mul(),hat
would help us create versions of mul() for multiplying int, float and double type values.
A template can be considered as a kind of macro. When an object of a specific type is
define for actual use, the template definition for that class is substitute with the required
data type. Since a template is defined with a parameter that would be replaced by a
specified data type at the time of actual use of the class or function, the templates are
sometimes called parameterized class or functions.
ACTIVITY 8.1

CHOOSE THE CORRECT ANSWER BELOW

1.Which of the following is true about templates.


1) Template is a feature of C++ that allows us to write one code for different data types.

2) We can write one function that can be used for all data types including user defined types. Like
sort(), max(), min(), ..etc.

3) We can write one class or struct that can be used for all data types including user defined types. Like
Linked List, Stack, Queue ..etc.
4) Template is an example of compile time polymorphism.
1 and 2
A
1, 2 and 3
B
1, 2 and 4
C
1, 2, 3 and 4 (ANSWER)
D

OBJECT ORIENTED
OOP 2
2.Which of the following provides the best description of an entity type?
A specific concrete object with a defined set of processes (e.g. Jatin with
A diabetes)
A value given to a particular attribute (e.g. height - 230 cm)
B
A thing that we wish to collect data about zero or more, possibly real world
C examples of it may exist
A template for a group of things with the same set of characteristics that may
D exist in the real world (ANSWER)

3. Which of the following is incorrect in C++ ?


(1)When we write overloaded function we must code the function for each usage.
(2)When we write function template we code the function only once.
(3)It is difficult to debug macros
(4)Templates are more efficient than macros
(1) and (2)
A
(1), (2) and (3)
B
(3) and (4)
C
All are correct. (ANSWER)
D
4-7.Predict the output
#include <iostream>
using namespace std;

template <typename T>


void fun(const T&x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

int main()
{
    fun<int> (1);
    cout << endl;
    fun<int>(1);
    cout << endl;
    fun<double>(1.1);
    cout << endl;
    return 0;
}

Run on IDE

OBJECT ORIENTED
OOP 2
x = 1 count = 0

x = 1 count = 1 (ANSWER)
A

x = 1.1 count = 0
x = 1 count = 0

x = 1 count = 0
B

x = 1.1 count = 0
x = 1 count = 0

x = 1 count = 1
C

x = 1.1 count = 2

Compiler Error
D

7-10.Output of following program?


#include <iostream>
using namespace std;

template <class T>


class Test
{
private:
    T val;
public:
    static int count;
    Test()  {   count++;   }
};

template<class T>
int Test<T>::count = 0;

int main()
{
    Test<int> a;
    Test<int> b;
    Test<double> c;
    cout << Test<int>::count   << endl;
    cout << Test<double>::count << endl;
    return 0;
}

OBJECT ORIENTED
OOP 3
Run n IDE

0
A 0
1
B 1
2 (ANSWER)
C 1
1
D 0

ACTIVITY 8.2

ANSWER THE FOLLOWING QUESTIONS: (5 POINTS EACH)

1-5.Output of following program? Assume that the size of char is 1 byte and size of int is 4 bytes, and
there is no alignment done by the compiler.

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T, class U>


class A  {
    T x;
    U y;
    static int count;
};

int main()  {
   A<char, char> a;
   A<int, int> b;
   cout << sizeof(a) << endl;
   cout << sizeof(b) << endl;
   return 0;
}

Run on IDE

6
A 12

OBJECT ORIENTED
OOP 3
2 (ANSWER)
B 8

Compiler Error: There can not be more than one template arguments.
C
8
D 8

5-10.Output of following program? Assume that the size of int is 4 bytes and size of double is 8 bytes,
and there is no alignment done by the compiler.

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T, class U, class V=double>


class A  {
    T x;
    U y;
    V z;
    static int count;
};

int main()
{
   A<int, int> a;
   A<double, double> b;
   cout << sizeof(a) << endl;
   cout << sizeof(b) << endl;
   return 0;
}

Run on IDE

16
A 24 (ANSWER)
8
B 16
20
C 28

Compiler Error: template parameters cannot have default values.


D

ACTIVITY 8.3
OBJECT ORIENTED
OOP 3

CHOOSE THE CORRECT ANSWER BELOW


1. Which of the following are correct in C++ ?
When we write overloaded function we must code the function for each
A usage
When we write function template we code the function only once.
B
It is difficult to debug macros
C
ALL OF THE ABOVE (ANSWER)
D

2. Which of the following provides the best description of an entity type?


A specific concrete object with a defined set of processes (e.g. Jatin with
A diabetes)
A value given to a particular attribute (e.g. height - 230 cm)
B
A thing that we wish to collect data about zero or more, possibly real world
C examples of it may exist
A thing that we wish to collect data about zero or more, possibly real world
D examples of it may exist (ANSWER)

3. Which of the following is true about templates.


Template is a feature of C++ that allows us to write one code for different
A data types.
We can write one function that can be used for all data types including user
B defined types. Like sort(), max(), min(), ..etc.
We can write one class or struct that can be used for all data types including
C user defined types. Like Linked List, Stack, Queue ..etc.
ALL OF THE ABOVE (ANSWER)
D

4-10.Output of following program? Assume that the size of char is 1 byte and size of int is 4 bytes, and
there is no alignment done by the compiler.

OBJECT ORIENTED
OOP 3

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T, class U>


class A  {
    T x;
    U y;
    static int count;
};

int main()  {
   A<char, char> a;
   A<int, int> b;
   cout << sizeof(a) << endl;
   cout << sizeof(b) << endl;
   return 0;
}

Run on IDE

6
A 12
2
B 8 (ANSWER)

Compiler Error: There can not be more than one template arguments.
C
8
D 8

OBJECT ORIENTED
OOP 3
CHAPTER 9: EXCEPTION HANDLING

OBJECTIVES:
 Explain the mechanism of exception handling
 Describe the role of keywords try,throw and catch in exception handling

INTRODUCTION
Usually there are mainly two type of bugs, logical errors and syntactic errors. The
logical errors occur due to poor understanding of problem and syntactic errors arise due
to poor understanding of language. There are some other problems called exceptions that
are run time anomalies or unused conditions that a program may encounter while
executing. These anomalies can be division by zero,access to an array outside of its
bounds or running out of memory or disk space. When a program encounters an
exceptional condition it is important to identify it and dealt with it effectively.An
exception is an object that is sent from the part of the program where an error occurs to
that part of program which is going to control the error
ACTIVITY 9.1
Direction: Run the following program, and choose the correct answer Below.

1-3. Will this code compile?


public class Test extends Exception{

public static void main(String[] args){

try{

System.out.println("My Custom Exception test");


throw new Test();

}catch(Exception e){
System.out.println("Test Exception");
}
}

A. Yes (ANSWER)
B. No

4-6.What will happen when you compile and run the following code?

public class Test extends Exception{

private String message;


OBJECT ORIENTED
OOP 3

public Test(String message){


this.message = message;
}

public static void main(String[] args){

int a = 5, b = 3;
try{

if( a % b > 0 )
throw new Test();

}catch(Exception e){
System.out.println("Test Exception");
}
}

}
A. No output
B. Test Exception
C. Run time error
D. Compilation error (ANSWER)

6-10.What will happen when you compile and run the following code?
public class Test{

public static void main(String[] args){

try{

Test t = new Test();


int d = t.getNum(2, 5);
System.out.println(d);

}catch(Exception e){
System.out.print("Exception 1 ");
}
}

public int getNum(int a, int b){

int c = 0;
try{

c = a * b;
if(c > 10)
throw new String("Cannot be more than 10 ");

OBJECT ORIENTED
OOP 3

}catch(Exception e){
System.out.print("Exception 2 ");
}

return c;
}

A. Exception 2
B. Exception 2 Exception1
C. 10
D. Compilation error (ANSWER)

ACTIVITY 9.2

Direction: Run the following program, and choose the correct answer Below.

1-3. What will happen when you compile and run the following code?

public class Test{

String className;

public static void main(String[] args){

try{

Test t = new Test();


if(t.className.equals("Test"))
System.out.print("Test ");
else
System.out.print("Other ");

}catch(Exception e){
System.out.print("Exception ");
}catch(NullPointerException ne){
System.out.print("Null ");
}

A. Test

OBJECT ORIENTED
OOP 3
B. Exception
C. Null
D. Compilation error (ANSWER)

4.Runtime Exception and its sub-classes can be caught by the catch block.

A. True (ANSWER)
B. False

5-10.What will happen when you compile and run the following code?

public class Test{

public static void main(String[] args){

try{

String[] names = {"Jack", "John", "Jill"};


printNames(names);

}catch(NameIsJohnException e){
System.out.print("NameIsJohnException ");
}
}

private static void printNames(String[] names) throws NameIsJohnException{


for(String name : names){
if(name.equals("John"))
throw new NameIsJohnException("Name cannot be John ");

System.out.print(name + " ");


}
}
}

class NameIsJohnException{
String message;

public NameIsJohnException(){

}
public NameIsJohnException(String message){
this.message = message;
}

public String getMessage(){


return this.message;
}

}
OBJECT ORIENTED
OOP 3

A. Jack Name cannot be John


B. Jack NameIsJohnException
C. NameIsJohnException
D. Compilation error (ANSWER)

ACTIVITY 9.3
Direction: Run the following program, and choose the correct answer Below.

1-5. What will happen when you compile and run the following code?

import java.io.IOException;

public class Test{

public static void main(String[] args){

try{

Test t = new Test();


t.doNothing();
System.out.println("I have done nothing");

}catch(IOException e){
System.out.println("Exception1");
}
}

OBJECT ORIENTED
OOP 3
private void doNothing(){
for(int i = 0 ; i < 10; i++){
}
}
}

A. No output
B. I have done nothing
C. Exception1
D. Compilation error (ANSWER)

6-10. What will happen when you compile and run the following code?

public class Test extends Exception{

public Test(){}
public Test(String str){
super(str);
}

int importantData = 5;
public static void main(String[] args){
Test t = new Test();
t.importantMethod();
}

private void importantMethod(){


if( importantData > 5)
throw new Test("Important data is invalid");
else
System.out.println(importantData);
}

A. No output
B. 5
C. Exception - Important data is invalid
D. Compilation error (ANSWER)

OBJECT ORIENTED
OOP 4

CHAPTER 10: ENCAPSULATION

OBJECTIVES:
 Describes bundling data and methods that work on that data within one unit, like
a class in Java.
INTRODUCTION

Encapsulation is a way to restrict the direct access to some components of an


object, so users cannot access state values for all of the variables of a particular object.
Encapsulation can be used to hide both data members and data functions or methods
associated with an instantiated class or object.

ACTIVITY 10.1

MULTIPLE CHOICE

1.In OO programming, a "blueprint" for an object is called


A. A sprite
B .A class (Answer)
C. A modifier
D. A variable

2.You can make changes to an object with


A. Methods (Answer)
B. attributes
C. modifiers

3.Attributes of an object are also known as


A. methods
B. Properties (Answer)
C. classes

4.Which one of the following are essential features of object oriented language? A. Abstraction and
encapsulation B. Strictly-typed C. Type-safe property coupled with sub-type rule D. Polymorphism in
the presence of inheritance
A. .A and B only
B. A, D and B only
C. A and D only (Answer)
D. A, C and D only

OBJECT ORIENTED
OOP 4

5. Abstraction and encapsulation are fundamental principles that underlie the object oriented approach
to software development. What can you say about the following two statements ? I. Abstraction allows
us to focus on what something does without considering the complexities of how it works. II.
Encapsulation allows us to consider complex ideas while ignoring irrelevant detail that would confuse
us.

A. Neither I nor II is correct. (Answer)


B. Both I and II are correct.
C. Only II is correct.
D. Only I is correct

ACTIVITY 10.2

Each question is worth Two points. Select the best answer for each question

The keyword private restricts the access of class or struct members to:
1.
Please select the best answer.
A
const functions
.
B
static functions
.
C. member functions (ANSWER)
D. clients

What is the difference between an object and a class?


2.
Please select the best answer.
An object is an extension of the class construct whose default access privilege is
A.
public.
B. The term object is just another way of referring to the public data members of a class.
C. An object is an initialized class variable.(ANSWER)
D. A class is an initialized object variable.

OBJECT ORIENTED
OOP 4

If we have
class card {
public:
int s;
};
3.
card a;
card* p;
we can use _________ to access int s:
Please select the best answer.
A
p.s
.
B
a.s (ANSWER)
.
C. p -> int
D. a -> s

In object-oriented software design, there is at least one extra step before you get to the
4. coding of algorithms. That step is the design of:
Please select the best answer.
A
classes that are appropriate for the problem at hand (ANSWER)
.
B
member functions
.
C. program control flow
D. the class's interface

An interface in C++ is a
5.
Please select the best answer.
A
program that allows easy conversion of another program's data
.
B
list of argument types in a function's parameter list
.
C. library for performing input and output
D. class's public members (ANSWER)

OBJECT ORIENTED
OOP 4

ACTIVITY 10.3

ANSWER THE FOLLOWING QUESTIONS BELOW TWO POINTS EACH

1.Encapsulation is supported by ___________

A. Objects

B. Methods

C. Classes (ANSWER)

D. None of the above

2.Encapsulation is supported by ___________

A. Objects (ANSWER)

B. Methods

C. Classes

D. None of the above

3.Encapsulation is also called as?

A. Data Hiding (ANSWER)

B. Data Hidding

C. Data Encapsulation
OBJECT ORIENTED
OOP 4

D. None of the above

4.Encapsulation is implemented by using__________

A. public

B. Private (ANSWER)

C. static

D. class

E. None of the above

5.The ability to define more than one function with the same name is called?

A. Inheritance

B. Encapsulation

C. Polymorphism (ANSWER)

D. Abstraction

OBJECT ORIENTED

You might also like