Saturday, January 30, 2016

INHERITANCE, SINGLE AND MULTIPLE INHERITANCE

Introduction to Inheritance

Reusability is another important feature of OOP. The mechanism of deriving a new class from an old one is called inheritance. Inheritance allows a class to include the members of other classes without repetition of members. There were three ways to inheritance means, “public parts of super class remain public and protected parts of super class remain protected.” Private Inheritance means “Public and Protected Parts of Super Class remain Private in Sub-Class”. Protected Inheritance means “Public and Protected Parts of Superclass remain protected in Subclass”.


CONCEPT OF INHERITANCE

Inheritance is a concept which is the result of commonality between classes. Due to this mechanism, we need not repeat the declaration as well as member functions in a class if they are already present in another class. For example, consider the classes namely “minister” and “prime minister”. Whatever information is present in minister, the same will be present in prime minister also. Apart from that there will be some extra information in class prime minister due to the extra privileges enjoyed by him. Now, due to the mechanism of inheritance, it is enough only to indicate that information which is a specific to prime minister in its class. In addition, the class prime minister will inherit the information of class minister.

BASE CLASS AND DERIVED CLASS


Let us take the classes, Employee and Manager. A Manager is an Employee with some additional information. when we are declaring the classes Employee and Manager without applying the concept of inheritance, they will look as follows:

class Employee

{
 public:
char* name;
int age;

char* address;
int salary; char*department; 
int id;

};

Now, the class Manager is as follows:

Class Manager {
 public:
char* name;

int age;
char* address; 
intsalary; char*department; 
int id;

employee* team_members; //He heads a group of employees int level; // his position in hierarchy of the organisation

.
.
.
.
};

Now, without repeating the entire information of class Employee in class Manager, we can declare the Manager class as follows:

class Manager: Public Employee

public: Employee*Team_members; int level;

.
.
.
.
};

The latest declaration of class Manager is the same as that of its previous one, with the exception that we did not repeat the information of class Employee explicitly. This is what is meant by the Application of inheritance mechanism. Please note that in the above example, Employee is called Base Class and Manager is called Derived Class.

Inheritance Visibility Mode
Depending on Access modifier used while inheritance, the availability of class members of Super class in the sub class changes. It can either be private, protected or public.


1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super class becomes protected members of sub class and public becomes public.
class Subclass : public Superclass


2) Private Inheritance
In private mode, the protected and public members of super class become private members of derived class.
class Subclass : Superclass   // By default its private inheritance


3) Protected Inheritance
In protected mode, the public and protected members of Super class becomes protected members of Sub class.
class subclass : protected Superclass



SINGLE INHERITANCE


In this Section, you will learn the ways of deriving a class from single class. So, there will be only one base class for the derived class.


Private Inheritance

Consider the following classes:

class A { /*......*/); class C: private A

{ /*
.
. .
.
*/
}

All the public parts of class A and all the protected parts of class A, become private members/parts of the derived class C in class C. No private member of class A can be accessed by class C. To do so, you need to write public or private functions in the Base class. A public function can be accessed by any object, however, private function can be used only within the class hierarchy that is class A and class C and friends of these classes in the above cases.



Public Inheritance

Consider the following classes: class A{/*........*/};
class E: public A
{
/*


:


:

};
:




Now, all the public parts of class A become public in class E and protected part of
A become protected in E

Protected Inheritance

Consider the following classes: class E: protected A

{ /*
.
.
.
*/
};

Now, all the public and protected parts of class A become protected in class E.

No private member of class A can be accessed by class E. Let us take a single example to demonstrate the inheritance of public and private type in more details.

Example:

#include <iostream.h>

class Value
{
protected:
int val;
public:
void set_values (int a)
{
val=a;
}
};

 class Cube: public Value
{
public:
int cube()
{
 return (val*val*val);
 }
};
int main ()
{
Cube cub;
cub.set_values (5);
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}

Output:
The Cube of 5 is:: 125

MULTIPLE INHERITANCE

A class can have more than one direct base classes.

Consider the following classes:

Class A {/*
.....*/};
Class B {/* .....
*/};
Class C : public A, public B

{   /*

.

.
.
.

*/

};

This is called Multiple Inheritance. If a class is having only one base class, then it is known as single inheritance. In the case of Class C, other than the operations specified in it, the union of operations of classes A and B can also be applied.

Example:
#include<iostream.h>
#include<conio.h>

class student
{
    protected:
       int rno,m1,m2;
    public:
                void get()
              {
                            cout<<"Enter the Roll no :";
                            cin>>rno;
                            cout<<"Enter the two marks   :";
                            cin>>m1>>m2;
              }
};
class sports
{
    protected:
       int sm;                   // sm = Sports mark
    public:
                void getsm()
              {
                 cout<<"\nEnter the sports mark :";
                 cin>>sm;

              }
};
class statement:public student,public sports
{
    int tot,avg;
    public:
    void display()
              {
                 tot=(m1+m2+sm);
                 avg=tot/3;
                 cout<<"\n\n\tRoll No    : "<<rno<<"\n\tTotal      : "<<tot;
               cout<<"\n\tAverage    : "<<avg;
              }
};
void main()
{
   clrscr();
   statement obj;
   obj.get();
   obj.getsm();
   obj.display();
   getch();
}

Output:

Enter the Roll no: 100
 Enter two marks
 90
 80
 Enter the Sports Mark: 90
 Roll No: 100
 Total    : 260
Average: 86.66




Wednesday, January 20, 2016

TYPE CONVERSION IN C++

TYPE CONVERSIONS

We have overloaded several kinds of operators but we haven’t considered the assignment operator (=). It is a very special operator having complex properties. We know that = operator assigns values form one variable to another or assigns the value of user defined object to another of the same type. For example,

int     x, y ;

x = 100;

y = x;

Here, first 100 is assigned to x and then x to y.

Consider another statement, t3 = t1 + t2;

This statement used in program 11.2 earlier, assigns the result of addition, which is of type time to object t3 also of type time.
So the assignments between basic types or user defined types are taken care by the compiler provided the data type on both sides of = are of same type.

But what to do in case the variables are of different types on both sides of the = operator? In this case we need to tell to the compiler for the solution.

Three types of situations might arise for data conversion between different types :

(i)            Conversion form basic type to class type.

(ii)           Conversion from class type to basic type.

(iii)          Conversion from one class type to another class type. Now let us discuss the above three cases :

(i) Basic Type to Class Type

This type of conversion is very easy. For example, the following code segment converts an int type to a class type.

class distance

{

int feet;

int inches;

public:

.....

.....

distance (int dist) //constructor

{

feet = dist/12;

inches = dist%12;

}

};

The following conversion statements can be coded in a function :

distance dist1; //object dist1 created

int length = 20;


dist1=length; //int to class type

After the execution of above statements, the feet member of dist1 will have a value of 1 and inches member a value of 8, meaning 1 feet and 8 inches.

A class object has been used as the left hand operand of = operator, so the type conversion can also be done by using an overloaded = operator in C++.

(ii) Class Type to Basic Type

For conversion from a basic type to class type, the constructors can be used. But for conversion from a class type to basic type constructors do not help at all. In C++, we have to define an overloaded casting operator that helps in converting a class type to a basic type.

The syntax of the conversion function is given below:

Operator typename()

{

.......

....... //statements

}

Here, the function converts a class type data to typename. For example, the operator float ( ) converts a class type to type float, the operator int ( ) converts a class type object to type int. For example,

matrix :: operator float ()

{

float sum = 0.0; for(int i=0;i<m;i++)

{

for (int j=0; j<n; j++) sum=sum+a[i][j]*a[i][j];

}

Return sqrt(sum); //norm of the matrix

}


Here, the function finds the norm of the matrix (Norm is the square root of the sum of the squares of the matrix elements). We can use the operator float ( ) as given below :

float norm = float (arr);

or

float norm = arr;

where arr is an object of type matrix. When a class type to a basic type conversion is required, the compiler will call the casting operator function for performing this task.

The following conditions should be satisfied by the casting operator function :

(a)  It must not have any argument

(b)  It must be a class member

(c)  It must not specify a return type.



(i)            One Class Type to Another Class Type

There may be some situations when we want to convert one class type data to another class type data. For example,

Obj2 = obj1; //different type of objects

Suppose obj1 is an object of class studdata and obj2 is that of class result. We are converting the class studdata data type to class result type data and the value is assigned to obj2. Here studdata is known as source class and result is known as the destination class.

The above conversion can be performed in two ways :

(a)  Using a constructor.

(b)  Using a conversion function.

When we need to convert a class, a casting operator function can be used i.e. source class. The source class performs the conversion and result is given to the object of destination class.

If we take a single-argument constructor function for converting the argument’s type to the class type (whose member it is). So the argument is of the source class and being passed to the destination class for the purpose of conversion. Therefore it is compulsory that the conversion constructor be kept in the destination class.

Example:
# include <iostream.h>
# include <conio.h>
class in1
{
    int code,items;
    float price;
    public:
        in1(int a,int b,int c)
        {
            code=a;
            items=b;
            price=c;
        }
        void putdata()
        {
            cout<<"CODE= "<<code<<endl;
            cout<<"ITEMS= "<<items<<endl;
            cout<<"VALUE= "<<price<<endl;
        }
        int getcode()
        {
            return code;
        }
        int getitems()
        {
            return items;
        }
        int getprice()
        {
            return price;
        }
        Operator float ()
        {
             return items*price;
        }
};

class in2
{
    int code;
    floatvalue;
    public:
    in2()
    {
        code=0;
        value=0;
    }
    in2(int x,float y)
    {
        code=x;
        value=y;
    }
    void putdata()
    {
        cout<<"CODE= "<<code<<endl;
        cout<<"VALUE= "<<value<<endl;
    }
    in2(in1 p)
    {
        code=p.getcode();
        value=p.getitems()*p.getprice();
    }
};

main()
{
clrscr();
    in1 s1(100,5,140.0);
    float tot_value;
    in2 d1;
    tot_value=s1;
    d1=in1(s1);
    cout<<"PRODUCT DETAILS INVENT-1 TYPES:->"<<endl;
    s1.putdata();
    cout<<"STOCK VALUE"<<endl;
    cout<<"VALUE= "<<tot_value<<endl;
    cout<<"PRODUCT DETAILS INVENT-2 TYPES:->"<<endl;
    d1.putdata();
}

OUTPUT:
PRODUCT DETAILS INVENT-1 TYPES:->
CODE= 100
ITEMS= 5
VALUE= 140
STOCK VALUE
VALUE= 700
PRODUCT DETAILS INVENT-2 TYPES:->
CODE= 100
VALUE= 700