You are on page 1of 18

Assignment No.

01

Title of Assignment: Write C++ program for the following.


A bag consists of zero or more objects of the same type. Each object can be described by its color
and weight. Design C++ program to create a new object. This can be done in two ways. If the
user provides information about color and/or weight of the object to be created then this
information will be used to create the object otherwise the object will be created using default
values for these attribute(s). Provide a facility to keep track of total number of objects and total
weight of objects in the bag at a given time. Also provide facility to delete an object from a bag.
Use static variable and functions.
Theory :
As the program should make use of overloaded constructors and static variables,
functions, here is the concept of each.
Constructor Overloading :
Constructor : Automatic initialization is carried by special member function called
constructor. Executed automatically whenever an object is created.
Constructor has th same name as that of the class and has no return type.
Multiple constructors can be written for same class differing in argument type and no of
arguments.
Bag() { wt = 10; strcpy(color,”red”); } // default/zero argument constructor
Bag( int wt );
Bag( char col[]);
Bag( char col[], int wt);
These all constructors are to be written in Bag class to initialize the Bag object. Last 3 are
called parameterized constructors.
Depending upon the object declaration specific constructor gets called.

int main()
{
Bag b1, b2(20), b3(“purple”), b4(“green”, 18); // object declaration
}

Static members : Only one copy(value) for entire class maintained and it is shared by all
objects created. Visible only in the class, but its lifetime is entire program. It is called
class variable and not instance variable.
Use : To count no. of nodes in a linked-list, no. of times file accessed etc.
Example :
Class Counter
{
private : static int count;
public : Counter()
{ count ++; }
int getCount()
{ return count; }
};
int Counter::count = 0; // initializing static data

int main()
{
Counter c1, c2, c3;
cout<<”Count is :” << c1.getCount();
cout<<”Count is :” << c2.getCount(); // value 3 displayed for all 3 calls
cout<<”Count is :” << c3.getCount();
}

Static methods :
Similar to static variables static methods are also class methods and are not invoked with
object, but with class name and :: ( scope resolution operator ).
They can only call other static methods and static data. Can’t use this pointer.
Static method showCount() is used to display total objects and weight in this assignment.
In the above class to get count displayed we write showCount() method as follows :

static void showCount()


{
cout<< “Total count is : “ << count ;
}

int main()
{
Counter c1,c2;
Counter::showCount(); // calling static method with classname
return 0;
}

Problem should be solved with a single class Bag with the following details. Four
overloaded constructors are used to create object in any of the ways. Static members
functions such as total-weight and total objects give total weight of the objects which
have been added and total no of objects added.

Destructor :
Destructor gets called when object is deleted using delete operator and tot_obj and tot_wt
is decremented in the destructor accordingly.

Design Analysis / Implementation Logic:


(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)
Algorithms :
Data structure used : Linked List / Array of pointers

(I) Algorithm addObject()

This function adds one object to the bag with specific color and weight or default
values.

1 Accept weight and color of the object


2 Create a node for object to be added
3 Attach it to list of objects
4 Increase the weight of Bag by that of object added and increment count of objects
added.

(II) algorithm deleteObject()


This function deletes the object from the bag.
Ask for object to be deleted either by color or weight of object.
De-allocate the memory for object.(Object pointer).
If found in the list decrease the bag weight by object weight, decrement the object
count by 1.
(III) algorithm displayObject()
This function should display the object details.
Display its color and weight.
Go to next object and repeat 2 till end of the list.
(IV) algorithm displaytotal()
This is a static function which should display total no of objects and total weight of
the bag.
Display total weight and total no of objects added till now.

Testing:
Input : Add object : Enter data as Object1 : default(5, “red”)
Object2 : 10
Object3 : 12, “pink”
Object4 : 20,“green”
Output : Display : Obj1 : 5 , red
Obj2 : 10, red
Obj3 : 12, pink
Obj4 : 20, green
Display Total : Total objects: 4
Total weight : 47
Enter object no to delete : 3
Object deleted successfully
Display : Obj1 : 5 , red
Obj2 : 10, red
Obj4 : 20, green
Display Total : Total objects: 3
Total weight : 35

Conclusion : Thus Bag created successfully with class, objects(color,weight) are added,
displayed and deleted successfully.
Assignment No. 03
Title of Assignment: Define two classes to store distance. One of the classes should store distance in
centimeters and meters and other should store distance in feet’s and inches. Read two distances, one for
each class and compute sum or difference between them as per the user's choice. Display answer in the
unit provided by user. Use friend function, function overloading, default values, constructors etc
Theory :
Problem Definition : Two classes store the distance in meter, centimeter and feet, inches as their
private members. Friend function is used to calculate addition and subtraction of the two
distances which is friend of the two classes above.
Constructors in distance classes can be initialized with default arguments for feet, inches / meter
centimeter.
Friend functions : If a function wants to operate on objects of two different classes, the function
will take objects of two different classes as arguments and operate on their private data. The
function which helps in such scenarios is a friend function. It acts as a bridge between two
classes. Because friend functions access private data of the class, they should be used only when
necessary otherwise program it leads to spaghetti code.
class beta ; // forward declaration
Eg. : class alpha
{
int data;
public : friend int funadd(alpha a , beta b) ;
};
class beta
{
int data;
public : friend int funadd(alpha a , beta b) ;
};
int funadd(alpha a , beta b) ;
{
return (a.data+b.data);
}
Default Arguments :
C++ allows a function to call without specifying all its arguments. Default values are specified
when function is declared as follows.
void add( int i= 10, int j = 20) ;
int main()
{
add(); // i=10, j=20 uses default values
add(80); // i=80, j=20 i gets new value as in function call
add(34,56); // i=34, j= 56 both i and j get new values as in function call
}
void add(int i, int j)
{
int res ;
res = i+j;
cout<< res;
}
Only trailing arguments can have default values i.e. default values are assigned right to left.

Function overloading : Overloading refers to the same thing for different purposes. C++ also
permits overloading of functions. Same function name is used to create functions that performs a
variety of different tasks. This is known as function polymorphism in Object Oriented
Programming. Depending upon argument list in function call function will perform different
work. Functions differ in number and type of arguments.
Eg.: Overloaded add function handles different types of data shown below:
int add( int a, int b);
int add( int a, int b, int c);
double add( double x, double y);
double add(double p, int q);
// function calls
cout<<add(5, 11);
cout<<add(15, 11.87);
cout<<add(5.34, 11.23);
cout<<add(0.35, 27);
A function call matches the prototype having the same number and type of arguments and then
calls the appropriate function for execution. A best match must be unique. The function selection
involves the following steps :
1. The compiler first tries to find an exact match in which the types of actual arguments are the
same and use that function.
2. If an exact match is not found, the compiler uses the integral promotions to the actual
arguments such as char to int, float to double to find a match.
3. Otherwise it uses built in conversions to the actual arguments and uses the function whose
match is unique.
long square(long n);
double square ( double x);
A function call such as square(10), which causes error because int can be converted either to long
or double creating an ambiguous situation.
4. If all above steps fail, compiler will try the user defined conversion.
Function overloading should be used generally for the functions which perform closely related
task.

Design Analysis / Implementation Logic:


(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)
Following two functions are declared friend of both the classes distM and distF.-
Algorithms and Requirement :
(I) Algorithm addDist (ref d1<distM>, ref d2<distF>)

Purpose :- Friend function in both the classes for subtraction of two different class objects.
Pre :- Two distances (feet/inches & meter/cm) should be accepted.
Post :- Addition of two distances
Return :- No return value

If user wants result in meter-cm, call this function.


Accordingly convert d1/d2 distance into other unit.
For conversion from meter-cm to inches use formula –
1meter = 39.372inches, 1cm = 0.3937inches
And for conversion from feet-inches to meter-cm use formula –
1feet = 30.48cm, 1 inch = 2.54cm

1. Convert d1 to cm
2. Convert d2 to cm
3. Add d1 and d2 and get result into totalcm
4. meter = totalcm/100
5. cm = totalcm – meter*100
6. Display result as meter and cm

(II) Algorithm addDist (ref d1<distF>, ref d2<distM>)

Purpose :- Friend function in both the classes for subtraction of two different class objects.
Pre :- Two distances (feet/inches & meter/cm) should be accepted.
Post :- Addition of two distances
Return :- No return value

if user wants result in feet-inches call this function.


Accordingly convert d1/d2 distance into other unit.
For conversion from meter-cm to inches use formula –
1meter = 39.372inches, 1cm = 0.3937inches
And for conversion from feet-inches to meter-cm use formula –
1feet = 30.48cm, 1 inch = 2.54cm

1. Convert d1 to inch
2. Convert d2 to inch
3. Add d1 and d2 and get result into totalinch
4. feet = totalinch/12
5. inch = totalinch – feet*12
6. Display result as feet and inch

For subtraction only change in operation , use same conversion. Take absolute difference i.e.
result should be positive.

Testing:
(Input : Accept two distance objects in feet and inches and two distance objects in meter and cm
D1 = 1feet 1 inch D2 = 2m 55cm
Output : Results of each operation was tested.
Addition of D1 and D2 = 9 feet 5.4 inches / 2m 88cm
Subtraction of D1 from D2 = 7 feet 3.39 inches / 2m 22cm
Conclusion: All options stated above are tested and executed successfully.
Assignment No. 05

Title of Assignment: Write a C++ program to perform String operations


i. == Equality
ii. = String Copy
iii. + Concatenation
iv. << To display a string
v. >> To reverse a string
vi. Function to determine whether a string is a palindrome
vii. * string length
viii. – substring

Use Operator Overloading with operators as given above.


Theory : C++ tries to make user-defined data types to behave in same manner as built-in types. As
we can add two integers with + operator we can also add two objects of the string class or matrix
class. This is accomplished with the mechanism of operator overloading. Thus new definition for
most of the C++ operators can be given, but original meaning is not lost. With this we can change
the semantics of an operator but not its syntax. Write a special function called operator to describe
the actual task. Syntax of operator function –

return-type classname ::operator op ( argument list ){ function body }

Where op is the operator being overloaded preceded by keyword operator.So operator op becomes
the function name. It can be a member function or friend function.

Overloading binary operators –

friend vector operator+(vector, vector) ; // friend function

vector operator+( vector ); // member function

Overloading unary operator –

friend vector operator-(vector) ; // friend function

vector operator-( ); // member function

Calling overloaded operator function –

Vector v1,v2, v3;

v3 = v1 + v2; // this will call operator + function automatically


-v3; // this will call operator- function automatically

Implementing operator overloading for string class

class string

char *p;

int len;

public : string (const char *s)

string ( const string &s);

string& operator +( const string &s); // for s1+s2

int operator <=( const string &s); // for s1 <= s2

// declaration for other operations

};

String& string:: operator+( const string &s2)

{ string temp;

temp.len = len + s2.len;

temp.p = new char[temp.len+1];

strcpy( temp.p, p);

strcat( temp.p, s2.p);

return temp;}

Similarly overload the other operators as follows :

2) <, > and == operators for string comparison

3) – operator for substring


4) >> operator for string reverse

5) = for string copy

6) ^ for change case

7) * for string length

8) use comparison and reverse to check for string palindrome


Design Analysis / Implementation Logic:
(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)
Algorithms and Requirement :
(I) Algorithm operator + (ref s1<string>, ref s2<string>)

Purpose :- Member function of string class to subtract add two strings.


Pre :- Two strings should be accepted.
Post :- Concatenation of strings
Return :- Reference to concatenated string

1. Copy first string s1 to temp string


2. Concatenate second string s2 to temp
3. return temp

(II) Algorithm operator = (ref s1<string>, ref s2<string>)

Purpose :- Member function of string class to make a copy of a string.


Pre :- String to be copied should be accepted.
Post :- string copy
Return :- Reference to copied string

1. Copy first string s1 to s2 string


2. return s2

(III) Algorithm operator == (ref s1<string>, ref s2<string>)

Purpose :- Member function of string class to compare the two strings.


Pre :- Two Strings to be compared should be accepted.
Post :- string comparison
Return :- difference between two strings

1. Compare two strings using strcmp function


2. Get the difference between two
3. return diff

(IV) Algorithm operator ~ (ref s1<string>)

Purpose :- Member function of string class to reverse a string.


Pre :- String to be reversed should be accepted.
Post :- string reverse
Return :- reference to reversed string

1. Reverse the string using strrev function and get it in s2


2. return s2
(V) Algorithm operator ^ (ref s1<string>, ref s2<string>)

Purpose :- Member function of string class to check for substring.


Pre :- Two Strings should be accepted.
Post :- Check for occurrence of sub-string
Return :- Boolean value returned

1. Check if s2 is substring of s1 string using strstr function


2. if strstr(s1, s2) returns NULL
3. return 0;
4. else
5. return 1;

(V) Algorithm operator ! (ref s1<string>)

Purpose :- Member function of string class to check for palindrome.


Pre :- String to be checked should be accepted.
Post :- result of string palindrome
Return :- Boolean flag for status

1. Reverse the string using strrev function and get it in s2


2. Now compare s1 with s2
3. If both are same
4. return 1
5. else
6. return 0
Testing: Accept the two strings and perform all the operations stated above by overloading
different operators.
Results for all operations match the standard results.
Conclusion: All options stated above are tested and executed successfully.
Assignment No. 07

Title of Assignment: Write C++ program using three classes as Student’s personal
information (name, address, phone, birth date etc) Student’s academic information (Xth,
XIIth and Graduation) Student’s other information (project done, seminar, hobbies, sports record)
Use multiple inheritance and print bio-data of a particular student.
Theory : The above problem can be solved using the principles of Inheritance.
The mechanism of deriving new class from an old existing one is called as Inheritance or
derivation. Parent class from which child inherits is called as Base class and the one
which derives is called as derived class.
Types of Inheritance are as follows :
1) Single Inheritance ( One base and one derived class )
2) Multiple Inheritance ( Many base classes and one derived class )
3) Multilevel Inheritance ( One base and one derived class and derived class
is derived again )
4) Hybrid Inheritance ( Combination of multiple and multilevel Inheritance )
In above problem the two base classes are declared as follows :
Multiple Inheritance
It is the process of creating a new class from more than one base class.

The syntax for multiple inheritance is similar to that for single inheritance.
For example
class Teacher
{ };
class Student
{ };
class Teaching_asst : public Teacher, public Student
The names of both the classes are provided separated by a comma. The rules of
inheritance and access for multiple inheritance are the same for single inheritance .

Visibility of public, private and protected members.

Private member of a base class cannot be inherited and therefore not available for derived
class directly. And if we make it public, this would make it accessible to all the other
functions of the program eliminating advantages of data hiding.
C++ provides third visibility modifier, protected, which serve a limited purpose in
inheritance. A member declared as protected in base class is accessible by the member
functions within its class and any class immediately derived from it.

Table for visibility of inherited members :


Base class Derived class visibility
Visibility Public derivation Private derivation
Private Not inherited Not Inherited
Protected Protected Private
Public Public Private

The keywords private, protected, public may appear in any order and in any number of
times in the class.

Constructors under multiple inheritance


The following example illustrate how constructors are handled in multiple inheritance .
class Academic
{
private :
int marks ;
public :
Academic(int m=0) { marks=m ;}
void displaym()
{
cout<<”Marks obtained:”<<m;
}
};
class Personal
{
private :
char name[20];
public :

Personal( char *n=”abc” ) { strcpy(name,n); }


void displayname()
{
cout<<”Name :”<<name;
}

};
class student : public Academic , public Personal
{
private :
char roll_no ;
public :
student (int r, int m, char *n) : Academic(m) , Personal(n)
{ roll_no=r ; }
};
When constructors are used in the base class and derived classes, the base class is
initialized before the derived class , using either a default constructor or a constructor
with arguments depending on the code of constructor of the derived class . The base
classes are initialized first, in the order they appear in the list of base classes in the
declaration of the derived class. If there are member objects in the class, they are
initialized next, in the order they appear in the derived class declaration. Finally the code
of the constructor is called.

Design Analysis / Implementation Logic:


(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)
Algorithm :
1) Three base classes containing student’s Personal, Academic and Other
information are created. Student class derives all the three classes above so that it
contains all type of information.
2) Initialize the base classes through constructors in derived class.
3) Derived class student can have methods to accept and display student data above
by calling accept and display methods of each of the base classes.
To maintain multiple student’s records array/ linked list of derived class objects can be
maintained

Testing:
Input : Student’s personal, academic and other information is accepted.
Output : Student’s complete bio-data is displayed with all information from base classes.

Conclusion:
All the operations have been tested and executed successfully.

You might also like