C++ Lab Manual - 2011
C++ Lab Manual - 2011
C++ Lab Manual - 2011
LAB MANUAL
SEMESTER : II/IV
BRANCH : CSE/ECE/ME/CE/BT
FACULTY :
DEEPAK GOUR
HARISH TIWARI
Table of contents
Topic Page No.
1. Objective 3
2. Assessment criteria 3
a. Internal Assessment 3
b. External Assessment 3
7. Module-4 Inheritance 11
11. Appendix A 16
12. Appendix B 19
Objective
This course examines practical programming techniques and issues, emphasizing object modeling and
simulation. The objectives of the course are to explore issues involved in developing large-scale object-oriented
systems and to teach fundamental techniques that can simplify software development. The course provides in
depth information on object oriented programming, issues, techniques, and methodologies.
Assessment criteria
All practical will be evaluated in the same manner of 1 credit carrying 50 marks.
This experiment introduces the compiling process and the manner in which your compiler
reports the errors that it finds. Error messages vary greatly from one system to another. Some
systems are very helpful to the programmer, and some are not. Most C++ compilers pinpoint the
line where the error has occurred and also display a short error message. It is then up to you to
play the part of detective, going back into the source program and searching for the error
yourself. Often one small error can spawn several misleading messages pointing to false errors.
A common procedure when trying to find and remove errors from a program (a process
called"debugging") is to try to compile the program each time an error has been corrected rather
than insisting on resolving all the error messages at once. It often happens that one correction
will cause other misleading error messages to dissipate.
Step 1. Using the editor in your particular software development environment, type the program
and save it for future reference. Be careful to include all of the punctuation marks and the
braces.
Step 2. Retrieve the program from Step 1 and compile it. If the compiler finds errors (which
would be typing errors), correct them and try again. Execute the final, correct program.
Step 3. In case you didn't have any typing errors on your first attempt, observe output.
is a comment. Comments have a variety of uses. They can be inserted to clarify a section of a
program that might otherwise be hard to understand. They can also be used to give information
about the creation of a program such as the date created and by whom. The statement
#include <iostream.h>
in our example program is an example of a preprocessing directive. These directives cause the
source program to be modified before the compiling process begins and are signified by beginning
with a # symbol. The directive in our example causes a copy of the standard header file named
iostream.h to be inserted at the beginning of the source code when compilation occurs. This file
contains information that the compiler will need to perform its task. In particular, our example
refers to the special object cout (which we will explain shortly) through which information can be
sent to the monitor screen. Our program does not contain the details of cout but merely
communicates with the object by means of the operator <<. The file iostream.h contains the
information needed by the C++ compiler to create the required link between our program and the
system library. Names of standard header files are enclosed by angle brackets, < and >, as in our
example. Names of nonstandard header files, such as those you may write yourself, are enclosed
in quotation marks, as in
#include "HomeMade.h"
A C++ program consists of units called functions. (We will learn about functions shortly.) Every
program contains at least one function called main. Execution of a C++ program always begins in
the function main. That is, the function main represents the beginning of the program even
though the function may appear much later in the written program. The line
int main()
in our example indicates the beginning of the function main. This opening line of a function is
known as a function header. We'll learn more about function headers in later laboratory sessions.
For now we note that such a header consists of three parts: a return type (in our example int),
the name of the function (in our example main), and a parameter list (in our example an empty
parenthetical expression). The fact that the function header in our example has a return type of
SPSU 4 School Of Engineering
Engineering
C++ Lab Manual CS102 CS209
int indicates that the operating system should expect to receive a numeric (integer) value when
our program terminates. This value is used to report whether our program executed successfully.
We'll return to this point shortly.
The actual "meat" of a function is placed between braces. Immediately following the opening
brace is the declarative part of the function. It is here the terminology relating to that particular
function is introduced. Our example program is so simple that it does not contain a declarative
part. Instead, the function main in our example consists of only a procedural part—the part
containing the instructions to be followed when the function is executed. The procedural part of a
function always follows the declarative part.
causes the characters that are enclosed in quotation marks to be printed on the monitor screen.
Thus, when executed, our example program will cause the two lines
Hello World
You are in the SPSU
to appear on the screen.
indicates that our program has finished its task and that control should be returned to the
operating. As indicated in the function's header, the operating system will be expecting to receive
a numeric value indicating whether our program executed successfully. This is the purpose of the
value 0 in the return statement. In general, returning the value 0 means that the program
executed successfully; other values are used to indicate various errors.
1. Aim : in this section write complete objective of the program you are going to make in
the lab. This section specifies the complete description of the including problem
analysis, input description, method used, fundamental concept and desired output
format.
2. Software used : in this section write what types of software will be used by the
student to develop source code of the given problem.
Compiler : Visual Studio c++ 6.0
Operating System : Windows Xp/Linux/Unix.
3. Source Code : in this section write the complete errorless source code, what you
have written in the editor of the IDE, with proper indentation and
also specify name of the file in the middle of the paper like
Example.cpp
4. Input : write input test data that are used to test program objective to see whether
program is achieving the given objective or not.
6. Conclusion : write complete conclusion that comprises what student learned from this
program.
2. DD/MM/YY DD/MM/YY
3. DD/MM/YY DD/MM/YY
Module -1
Classes & Objects
Specifying a class, creating class objects, accessing class members, access specifiers: public, private,
and protected, classes, objects and memory, static members, the const keyword and classes, the static
objects, empty classes, nested classes, local classes, abstract classes
List of programs:
S.No. Aim of the program
1 Write a program in C++ to display your name, Branch, Year on too the computer
screen without using classes and object. All information should be displayed in the
separate line.
2 Write a menu driven program in C++ to perform all basic arithmetic operation
addition, subtraction, multiplication, and division of two given values. Program
receives two values and required operation to be performed from the keyboard
and display particular result of the required operation.
3 Write a menu driven program in C++ that receives 4 digit integer value the
keyboard and perform following operations
1. Reverse of that no.
2. sum of number with it’s reverse
3. sum of alternative digits(1 digit+3 digit and 2 digit+4 digit)
4 Write a menu driven program in C++ to receive integer number and convert
equivalent binary, octal, hexadecimal number.
5 Write a menu driven program in C++ to perform all basic arithmetic operation
addition, subtraction, multiplication, and division of two given values using function
and switch case. Program receives two values and required operation to be
performed from the keyboard and display particular result of the required
operation.
6 Write a program in C++ to display mark sheet. Of the student. Define a class that
contains data members to store student information line name, Branch, semester,
marks in 6 different subjects, etc. Declare some member functions to get these
information from the key board, to calculate result and to display all gathered
information on to the computer screen in proper format.
Module-2
Constructors and Destructors
Need for constructors and destructors, copy constructor, dynamic constructors, destructors,
constructors and destructors with static members, initializer lists.
List of programs:
3 Create a class called Triangle that stores the length of the base and height of a
right triangle in two private instance variables. Include a constructor that sets
these values. Define two functions. The first is hypot( ), which returns the length
of the hypotenuse. The second is area( ), which returns the area of the triangle.
Module-3
Operator Overloading and Type conversion
Defining operator overloading, rules for overloading operators, overloading of unary operators and
various binary operators, overloading of new and delete operators, type conversion - basic type to
class type, class type to basic type, class type to another class type.
List of programs:
S.No. Aim of the program
1 Declare a class Number that contains two data member value1 and value2 of the
type of integer, define constructor to give initial value, and perform addition ,
subtraction, multiplication and division of these two numbers using operating
overloading of +,-,*,/ operator respectively
[hint- binary operator overloading using member function]
2 Declare a class Number1 that contains two data member value1 and value2 of the
type of integer, define constructor to give initial value, and perform addition,
subtraction, multiplication and division of these two numbers using operating
overloading of +,-,*,/ operator respectively
[hint- binary operator overloading using friend function]
3 Declare a class Number3 that contains a data member value of the type of integer,
define constructor to give initial value, and perform unary minus ,increment and
decrement this number using operating overloading of -,++,-- operator respectively
[hint- Unary operator overloading using member function]
4 Declare a class Number3 that contains a data member value of the type of integer,
define constructor to give initial value, and perform unary minus, increment and
decrement this number using operating overloading of -,++,-- operator respectively
[hint- Unary operator overloading using friend function]
5 Define a class complex that contains two data member to store real and imaginary
part of the complex number. Create a function to get values from the keyboard into
these complex numbers, overload binary + and – to calculate addition and
subtraction of two complex numbers respectively using member function.
6 Write a program to demonstrate explicit type conversion from basic type to user
defined data type.
7 Write a program to demonstrate explicit type conversion from User Defined data
type to Basic data type data type.
8 Write a program to demonstrate explicit type conversion from one user defined
data type to another user defined data type.
10 Write a program in C++ to find greater between two numbers using friend function.
12 Write a program in C++ to swap between two numbers using friend function.
Module-4
Inheritance
Introduction, defining derived classes, forms of inheritance, ambiguity in multiple and multi-path
inheritance, virtual base class, overriding member functions, order of execution of constructors and
destructors.
List of programs:
1. Create a class A with some private data members and some public member
function, now create a derived class B, that inherits A and having some data
members and member functions it’s own, in main( ) function access attributes of
base class with the help of derived class object to show inheritance concepts.
2. Create a class publication which has title of book and writers name. create another
class sales which accounts no. of sales for every month (upto 3 months) and then
calculate total sales.
STAFF
Regular Casual
Student
Result
Person
Student
Exam sports
Result
6 Write a program to solve the ambiguity problem in inheritance where two different
classes are inherited from single base class and a new class is derived from these
two derived classes. How this problem is solved with the help of virtual base class
concept.
Module-5
Virtual functions & Polymorphism
Concept of binding - early binding and late binding, virtual functions, pure virtual functions, virtual
destructors & polymorphism.
List of programs:
2. WAP a program to show how member of the class are accessed through the
pointer to class using arrow operator (->).
3. Write a program to show the concept of virtual function with the help of suitable
programming example.
4. Create a simple “shape” hierarchy: a base class called Shape and derived classes
called Circle, Square, and Triangle. In the base class, make a virtual
function called draw( ),and override this in the derived classes. Make an array of
pointers to Shape objects that you create on the heap (and thus perform upcasting
of the pointers), and call draw( ) through the base-class pointers, to verify the
behavior of the virtual function. If your debugger supports it, single-step through
the code.
6. Write a small program to show the difference between calling a virtual function
inside a normal member function and calling a virtual function inside a constructor.
The program should prove that the two calls produce different results.
Module-6
Managing Data Files:
Streams, hierarchy of file stream classes, error handling during file operations, reading/writing of
files, accessing records randomly, updating files.
List of programs:
1 Write a program that emulates the DOS COPY command. That is, it should copy
the contents of a text file (such as any .CPP file) to another file. Invoke the
program with two command-line arguments—the source file and the destination
file—like this:
C>copy srcfile.cpp destfile.cpp
In the program, check that the user has typed the correct number of command-
line arguments, and that the files specified can be opened.
2 In a loop, prompt the user to enter name data consisting of a first name, middle
initial, last name, and employee number (type unsigned long). Then, using
formatted I/O with the insertion (<<) operator, write these four data items to an
ofstream object. Don’t forget that strings must be terminated with a space or other
whitespace character. When the user indicates that no more name data will be
entered, close the ofstream object, open an ifstream object, read and display all
the data in the file, and terminate the program.
Module-7
Exception handling
Review of traditional error handling, basics of exception handling, Exception handling mechanism,
throwing mechanism, catching mechanism, re-throwing an exception, specifying exceptions
List of programs:
1. Create a class with a main( ) that throws an object of class Exception inside
a try block. Give the constructor for Exception a String argument. Catch the
exception inside a catch clause and print the String argument. Add a finally clause
and print a message to prove you were there.
2. Create your own exception class using the extends keyword. Write a constructor
for this class that takes a String argument and stores it inside the object with
a String reference. Write a method that prints out the stored String. Create a try-
catch clause to exercise your new exception.
3. Write a class with a method that throws an exception of the type created in
Exercise 2. Try compiling it without an exception specification to see what
the compiler says. Add the appropriate exception specification. Try out your class
and its exception inside a try-catch clause.
4. Define an object reference and initialize it to null. Try to call a method through this
reference. Now wrap the code in a try-catch clause to catch the exception.
5. Create a class with two methods, f( ) and g( ). In g( ), throw an exception of a new
type that you define. In f( ), call g( ), catch its exception and, in the catch clause,
throw a different exception (of a second type that you define). Test your code
in main( ).
6. Repeat the previous exercise, but inside the catch clause, wrap g( )’s exception in
aRuntimeException.
• Comments
// This is a single-line comment.
/* This comment spans across
more than one line. */
• Conditional Statements
if (boolean expression)
{
statement 1;
statement 2;
statement 3;
}
else if (boolean expression)
{
statement 1;
}
else
{
statement 1;
statement 2;
}
• While Loop
• For Loop
• Do Loop
do
{
statement 1;
// notice semicolon at the bottom
statement 2;
} while (condition);
• Arrays
int my_array[10];
// Declaring Array w/10 Integers
my_array[0]=4;
my_array[1]=55;
// Initializing Array elements
int my_array[10] = {6,5,4,3,2,1,7,8,9,0};
// Declaration & Initialization
• Strings
char my_string[3];
// Declaration
my_string[0]='H';
my_string[1]='i';
my_string[2]='\0';
// Initialization
char my_string[]="Hello Everybody!";
//Declaration & Initialization
• Functions
/* example *************************
int Cube (int);
int Cube (int n)
{
int cb=0;
cb = n*n*n;
return cb;
}********************************* */
• Structure
} [struct_name_t] [struct_instance];