SEM - 2 - MC0066 - OOPS Using C++
SEM - 2 - MC0066 - OOPS Using C++
1. Describe the steps in compiling and executing a C++ program with programmatic
illustration.
Ans:- There are three steps in executing a c++ program: Compiling, Linking and
Running the program. The c++ programs have to be typed in a compiler. All the
programs discussed in the book will be compiled on turbo c++ compiler. The turbo
c++ compiler comes with an editor to type and edit c++ program.
After typing the program the file is saved with an extension .cpp. This is known as
source code. The
source code has to be converted to an object code which is understandable by the
machine. This
process is known as compiling the program. You can compile your program by
selecting compile from
compile menu or press Alt+f9. After compiling a file with the same name as source
code file but with
extension .obj. is created.
Second step is linking the program which creates an executable file .exe (filename
same as
source code) after linking the object code and the library files (cs.lib) required for
the program. In a
simple program, linking process may involve one object file and one library file.
However in a project,
there may be several smaller programs. The object codes of these programs and
the library files are
linked to create a single executable file. Third and the last step is running the
executable file where the
statements in the program will be executed one by one.
When you execute the program, the compiler displays the output of the program
and comes
back to the program editor. To view the output and wait for user to press any key
to return to the
editor, type getch() as the last statement in the program. Getch() is an inbuilt
predefined library
function which inputs a character from the user through standard input. However
you should include
another header file named conio.h to use this function. Conio.h contains the
necessary declarations for
using this function. The include statement will be similar to iostream.h.
Compiling and Linking
During compilation, if there are any errors that will be listing by the compiler. The
errors may be any
one of the following
1.Syntax error
1
This error occurs due to mistake in writing the syntax of a c++ statement or wrong
use of
reserved words, improper variable names, using variables without declaration etc.
Examples are :
missing semi colon or paranthesis, type integer for int datatype etc. Appropriate
error message and
the statement number will be displayed. You can see the statement and make
correction to the
program file, save and recompile it.
2. Logical error
This error occurs due to the flaw in the logic. This will not be identified by the
compiler.
However it can be traced using the debug tool in the editor. First identify the
variable which you
suspect creating the error and add them to watch list by selecting Debug
->Watches->Add watch.
Write the variable name in the watch expression. After adding all the variables
required to the watch
list, go to the statement from where you want to observe. If you are not sure, you
can go to the first
statement of the program. Then select Debug ->Toggle Breakpoint (or press ctrl +
f8). A red line will
appear on the statement. Then Run the program by selecting Ctrl + f9 or Run
option from run menu.
The execution will halt at the statement where you had added the breakpoint. The
watch variables and
their values at that point of time will be displayed in the bottom in the watch
window. Press F8 to
execute the next statement till you reach the end of the program. In this way you
can watch closely
the values in the watch variables after execution of each and every statement in
the program. If you
want to exit before execution of the last statement press Ctrl + Break. To remove
the breakpoint in the
program go to the statement where you have added breakpoint select Debug
->Toggle Breakpoint (or
press ctrl + f8).Select Debug -> watch ->remove watches to remove the variables
in the watch list. This
tool helps in knowing the values taken by the variable at each and every step. You
can compare the
expected value with the actual value to identify the error.
3. Linker error
This error occur when the files during linking are missing or mispelt
4. Runtime error
This error occurs if the program encounters division by zero, accessing a null
pointer etc during
execution of the program.
2
2. Describe the theory with programming examples the selection control statements in
C++.
Ans:- The statements in the programs presented above have all been sequential, executed in the
order they appear in the main program.
In many programs the values of variables need to be tested, and depending on the result,
different statements need to be executed. This facility can be used to select among alternative
courses of action. It can also be used to build loops for the repetition of basic actions.
In C++ the testing of conditions is done with the use of Boolean expressions which yield bool
values that are either true or false. The simplest and most common way to construct such an
expression is to use the so-called relational operators.
Example:-
if(total != 0)
{
fraction = counter/total;
cout << "Proportion = " << fraction << endl;
}
3
789
-- 7 is Saddle_Pt. at position (3,1)
Write a program in C++ to check and print for saddle points in a matrix.
Ans:-
#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10],i,j,k,n,min,max,col;
clrscr();
printf("enter order m,n of mxn matrix");
scanf("%d %d",&m,&n);
printf("enter elements row-wise");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<m;i++)
{
min=a[i][0];
for(j=0;j<n;j++)
{
if(a[i][j]<=min)
{
min=a[i][j];
col=j;
}
}
max=a[0][col];
for(k=0;k<m;k++)
{
if(a[k][col]>=max)
{
max=a[k][col];
}
}
4
if(max==min)
printf("saddle pt.at (%d,%d)",i+1,col+1);
}
getch();
}
4. Describe and Demonstrate the concept of Pass by Value and Pass By Reference
using appropriate programming examples of your own.
Ans:-
Pass By Value:
void aMethod(aParameter p) { }
When passing by value a temporary COPY is made in memory taking up space and making
any changes to the variable useless outside of the aMethod scope. Once control returns to the
calling procedure any changes to the variable will not be recognized, and you will still have the
original variable.
Pass By Reference:
void aMethod(aParameter& p) { }
NOTE: the & can be place either against the parameter type, against the parameter name, or
there can be a space on either side.
This essentially passes a pointer, but not the same kind of pointer you would get when creating
a:
Variable* v;
That is why it is called by reference, since that is what you have, p now acts as if it were the
parameter just like in the by value way, but any changes affect the original and stay changed
outside of the aMethod scope.
*Now if that parameter was a structure, class, or template, etc. It will have fields that are
accesable by reference . or pointers ->
In both cases of the above passing, the parameter passed can be accessed using the . or dot
operator.
Examples:
*assuming fields within the class type.
Person person; //person is an object of class Person
person.name
person.Chlid.name
5
If the methods above were constructors or other member functions, accessed in a fasion like the
method call just above, then there is a this operator for accessing the object which called it.
Who’s fields can also be accessed, but only by pointers.
Ans:- Derivation:- Ordinarily when a function in a derived class overrides a function in a base class,
the function to call is determined by the type of the object. A given function is overridden when there
exists no difference, in the number or type of parameters, between two or more definitions of that
function. Hence, at compile time it may not be possible to determine the type of the object and therefore
the correct function to call, given only a base class pointer; the decision is therefore put off until
runtime. This is called dynamic dispatch. Virtual member functions or methods[17] allow the most
specific implementation of the function to be called, according to the actual run-time type of the object.
In C++ implementations, this is commonly done using virtual function tables. If the object type is
known, this may be bypassed by prepending a fully qualified class name before the function call, but in
general calls to virtual functions are resolved at run time.
Inheritance:- Inheritance allows one data type to acquire properties of other data types. Inheritance
from a base class may be declared as public, protected, or private. This access specifier determines
whether unrelated and derived classes can access the inherited public and protected members of the base
class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two
forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while
a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual inheritance.
Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph,
avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritance is a C++ feature not found in most other languages. Multiple inheritance allows a
class to be derived from more than one base class; this allows for more elaborate inheritance
relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal".
Some other languages, such as Java or C#, accomplish something similar (although more limited) by
allowing inheritance of multiple interfaces while restricting the number of base classes to one
(interfaces, unlike classes, provide only declarations of member functions, no implementation or
member data). An interface as in Java and C# can be defined in C++ as a class containing only pure
virtual functions, often known as an abstract base class or "ABC". The member functions of such an
abstract base classes are normally explicitly defined in the derived class, not inherited implicitly.
6. Describe the Friend functions and friend classes with programming examples.
Ans:-
Friend functions:- A friend function is used in object-oriented programming to allow access to private or
protected data in a class from outside the class. Normally a function which is not a member of a class cannot
access such information; neither can an external class. Occasionally such access will be advantageous for the
programmer; under these circumstances, the function or external class can be declared as a friend of the class using
the friend keyword. The function or external class will then have access to all information – public, private, or
protected – within the class.
This procedure should be used with caution. If too many functions or external classes are declared as friends of a
class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented
programming.
6
Example:
#include <iostream.h>
class B;
class A
{
private:
int a;
public:
A() { a=0; }
friend void show(A& x, B& y);
};
class B
{
private:
int b;
public:
B() { b=6; }
friend void show(A& x, B& y);
};
int main()
{
A a;
B b;
show(a,b);
}
Friend Class:- A friend class has full access to the private data members
of a class without being a member of that class.
Example:-
class A
{
private:
//...(statements)
public:
//...(statements)
friend class B;
}
7
Classes for the file stream operations :- The I/O system of C++ contains a set of classes that
define the file handling methods.These include ifstream, ofstream and fstream. These classes, designed
to manage the disk files, are declared in fstream.h and therefore we must include this file in any program
that uses files.
Opening and closing a file :-For opening a file, we must first create a file stream and than link it to
the filename. A filestream can be defined using the classes ifstream, ofstream, and fstream that are
contained in the header file fstream.A file can be opened in two ways:
Using the constructor function of the class. This method is useful when we open only one file in the
stream. Using the member function open() of the class. This method is used when we want to manage
multiple files using one stream.
Writing and reading Objects of a class :-
So far we have done I/O of basic data types. Since the class objects are the central elements of C++
programming, it is quite natural that the language supports features for writing and reading from the
disk files objects directly.The binary input and output functions read() and write() are designed to do
exactly this job.The write() function is used to write the object of a class into the specified file and
read() function is used to read the object of the class from the file.
Both these functions take two arguments:
1. address of object to be written.
2. size of the object.
8. Explain the concept of class templates in C++ with some real time programming
examples.
Ans:-
8
Declaring C++ Class Templates:
Declaration of C++ class template should start with the keyword template. A parameter should be
included inside angular brackets. The parameter inside the angular brackets, can be either the keyword
class or typename. This is followed by the class body declaration with the member data and member
functions. The following is the declaration for a sample Queue class.
If the functions are defined outside the template class body, they should always be defined with the
full template definition. Other conventions of writing the function in C++ class templates are the same as
writing normal c++ functions.
Example:-
#include <iostream.h>
#include <vector>
void main()
{
MyQueue<int> q;
q.Add(1);
q.Add(2);
9
q.Remove();
cout<<"After removing data"<<endl;
q.Print();
}
August 2010
Master of Computer Application (MCA) – Semester 2
MC0066 – OOPS using C++
Assignment Set – 2
10
constructor. A destructor will perform destroy any dynamic memory that was allocated in the
constructor or at some other point in the object life, as well as releasing any system resources that might
similarly have been assigned to the object during its life.
Constructors always have the same name as their class. Destructors take the name of their class
preceded by a tilde (~).
A class may have more than one constructor.A class may not have two constructors that agree in terms
of the number and type of their parameters.Constructor and destructors are usually defined as public
members of their class and may never possess a return value. They may however sometimes be
protected so that code outside the class heirarchy can not construct objects of that class.
Example:-
#include <string.h>
#include <iostream.h>
class MyClass
{
private:
int myInt;
char myText[20];
public:
MyClass()
{
myInt = 0;
myText[0]='\0';
}
MyClass(const MyClass &anObjectOfMyClass)
{
myInt = anObjectOfMyClass.myInt;
myText = anObjectOfMyClass.myText;
}
MyClass(const int thisint, const char* thattext = 0)
:myInt(thisint)
{
strcpy(myText,thattext);
}
~MyClass()
{
}
friend ostream& operator <<(ostream&, MyClass &);
};
ostream& operator <<(ostream & os,MyClass &anObjectOfMyClass)
{
os << anObjectOfMyClass.myInt << "+ " << anObjectOfMyClass.myText
<< "+";
return os;
}
void main(void)
{
MyClass mcObj1;
MyClass mcObj2(1,"abcde");
MyClass mcObj3(mcObj2);
MyClass mcObj4 = mcObj3;
cout << "mcObj1 : " << mcObj1 << endl;
cout << "mcObj2 : " << mcObj2 << endl;
cout << "mcObj3 : " << mcObj3 << endl;
11
cout << "mcObj4 : " << mcObj4 << endl;
return;
}
12
3. Describe the theory behind Virtual Functions and Polymorphism along with suitable
programming examples for each.
Ans:- There are nine ways that you can declare a virtual function: it can be plain, pure or pure-with-a-
body. Each of these three can be declared public, private or protected.Well, it's one of those lesser-
known facts of the language that a pure virtual function can have a definition (or body). After all, the
pure specifier (the "= 0" bit) only says that this class cannot be instantiated - it does not say "this
function cannot be implemented here". One of the simplest ways of making a class abstract (cannot be
instantiated) is to declare the destructor pure - but destructors simply have to have a body.
So, let's look at the various declarations and see what the programmer who uses each is saying. The first
thing to point out is that, since the virtual mechanism works down inheritance hierarchies, there is not
usually much difference in meaning between a public function and a protected one - it's just a matter of
outside visibility rather than "meaning" in the sense.
Example:-
#include <iostream>
#include "sale.h"
#include "discountsale.h"
using std::cout;
using std::endl;
using std::ios;
using namespace SavitchSale;
int main( )
{
Sale simple(10.00);
DiscountSale discount(11.00, 10);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
return 0;
}
4. Write a program in C++ for copying and printing the contents of files.
Ans:-
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
void copy_file(const std::string& name1, const std::string& name2)
13
{
std::ifstream in(name1.c_str());
std::ofstream out(name2.c_str());
std::copy( std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(out));
}
int main()
{
copy_file("test.txt", "test.out");
print_file("test.txt");
}
Declaration of C++ class template should start with the keyword template. A parameter should be
included inside angular brackets. The parameter inside the angular brackets, can be either the keyword
class or typename. This is followed by the class body declaration with the member data and member
functions. The following is the declaration for a sample Queue class.
The keyword class highlighted in blue color, is not related to the typename. This is a mandatory
keyword to be included for declaring a template class.
14
Defining member functions - C++ Class Templates:
If the functions are defined outside the template class body, they should always be defined with the
full template definition. Other conventions of writing the function in C++ class templates are the same as
writing normal c++ functions.
The Add function adds the data to the end of the vector. The remove function removes the first
element. These functionalities make this C++ class Template behave like a normal Queue. The print
function prints all the data using the iterator.
6. Discuss the theory of Exception specifications with suitable code snippets for each.
Ans:-
C++ provides a mechanism to ensure that a given function is limited to throwing only a
specified list of exceptions. An exception specification at the beginning of any function acts as
a guarantee to the function's caller that the function will throw only the exceptions contained in
the exception specification.
explicitly states that it will only throw exception objects whose types are unknown_word or
bad_grammar, or any type derived from unknown_word or bad_grammar.
>>-throw--(--+--------------+--)-------------------------------><
'-type_id_list-'
15
The type_id_list is a comma-separated list of types. In this list you cannot specify an
incomplete type, a pointer or a reference to an incomplete type, other than a pointer to void,
optionally qualified with const and/or volatile. You cannot define a type in an exception
specification.A function with no exception specification allows all exceptions. A function with
an exception specification that has an empty type_id_list, throw(), does not allow any
exceptions to be thrown.An exception specification is not part of a function's type.An exception
specification may only appear at the end of a function declarator of a function, pointer to
function, reference to function, pointer to member function declaration, or pointer to member
function definition. An exception specification cannot appear in a typedef declaration. The
following declarations demonstrate this:
The compiler would not allow the last declaration, typedef int (*j)() throw(int).
C::~C() throw();
The default constructor of C can throw exceptions of type int or char. The copy constructor of
C can throw any kind of exception. The destructor of C cannot throw any exceptions.
16
8. Write about the following with respect to:
For example, can use a sequence diagram to create your own context to understand existing behaviors
and interactions in an application, and develop and generate new ones. You can use a sequence diagram
to create a graphical representation of the behaviors and interactions between C/C++ classes or data
types in a C/C++ application and to understand how the system works to accomplish the interactions. In
the interaction frame, you position instances in the interaction in any order from left to right, and then
you position the messages between the instances in sequential order from top to bottom. Execution
occurrences appear on the lifelines and show the start and finish of the flow of control.
As the following table illustrates, you can indicate several behaviors in sequence diagrams.
Behavior Description
Creation You can create an instance during the interaction by using a create message. The
"created" lifeline repositions itself at the level of the create message. Otherwise, the
lifeline can start at the top of the diagram to indicate that it existed before the
interaction.
Communication You indicate messages between instances with arrows. The arrow originates from the
source lifeline that sends it and ends at the target lifeline that terminates it.
Execution An execution occurrence shows the time during which an instance is active, either
executing an operation directly or through a subordinate operation.
17
Destruction If you destroy an instance during the interaction with a destroy message or a stop node,
its stem ends at the level of the stop node. Otherwise, its lifeline extends beyond the
final message to indicate that it exists during the entire interaction.
In the Modeling perspective, a model must contain a collaboration and a composite structure diagram
must be open.
To create a collaboration occurrence in a composite structure diagram:
18