Professional Documents
Culture Documents
01
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 :
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.
This function adds one object to the bag with specific color and weight or default
values.
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.
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
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
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
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
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.
class string
char *p;
int len;
};
{ string temp;
return temp;}
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 .
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.
The keywords private, protected, public may appear in any order and in any number of
times in the class.
};
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.
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.