Saturday, 25 April 2015

Formatted Console I/O operations

A Common requirement is to reserve an area of the screen for a field, without knowing the number of characters the data of that field will occupy. To do this there must be a provision for alignment of fields to left or right, or padded with some characters. C++ supports a wide variety of features to perform input or output in different formats.

They include the following:

? Ios stream class member functions and flags
? Standard manipulators
? User-defined manipulators

ios class functions and flags

width() function

specifies the required number of fields to be used while displaying the output value.

Syntax

Int width(void);
Int width(int );

The first form returns the current width setting whereas, the second sets the width to the
specified integer value and returns the previous width.

Precision() function

Specifies the number of digits to be displayed after the decimal point.

Syntax

Int percision(void);
Int precision(int );

By default, the precision size is six. This function must be accessed using objects of the ios class. It sets the precision and returns the previous setting. Unlike width() the precision() must be reset for each data item being output if new precision is desired.

Fill() function

Specifies a character to be used to fill the unused are of a field. By default, fills blank space character. It is member function of ios class and is used to specify the character to be displayed in the unused portion of the display width.

Syntax

Int fill(void);
Int fill(char);

By default, blank character is displaye d in the unused portion if the display width is larger than that required by the value.

Setf() function

C++ provides a mechanism to set the printing of results in the left-justified form, scientific notation etc.

The member function of the ios class, setf() is used to set flags and bit-fields that control the output. It has the following two forms.

Long setf(long setbits, long field);
Long setf(long setbits);

Where setbits is one of the flags defined in the class ios. It specifies the format action required for the output, and field specifies the group to which the formatting flag belongs. Both the forms return the previous settings. The flags, bit-fields when set with setf() and their actions is shown in table.



The following table shows that some of flag value without bit fields for the setf function.





Friday, 24 April 2015

Unformatted I/O Operations

The stream classes of C++ support two member functions get( ) and put( ). The function get( ) is a member function of the input stream class istream and is used to read a single character from the input device.

The function put( ) is a member function of the output stream class ostream and is used to write a single character to the output device.

Get() function

It has the following syntax:

Void get(char);

Int get(void);


Both the function can fetch a white-space character including the blank space, tab and newline character. It is well known that, the member functions are invoked by their objects using dot operators.


Put() function

It has the following syntax:

Void get(char);
Int get(void);


It is a member function of the output stream class ostream prints a character
representation of the input parameter. The parameter can also be a numeric constant.

Getline () function

The getline() function reads a whole line of text that ends with new line or until
the maximum limit is reached.

Write() function

The write() function displays the characters in the string array or displays the
character up to the given size.

The syntax for the two functions are

Getline (variable, size);
Write(variable, size);

Sample Program

#include <iostream.h>
void main()
{
char *str1;
cout<<”Enter the string”;
cin.getline(str1,50);
int len = strlen(str1);
for(int I = 0;I<len;I++)
{
cout.write(str1,I);
cout<<endl;
}
}





Hierarchy of Console Stream Classes

The C++ input-output system supports a hierarchy of classes that are used to manipulate both the console and disk files, called stream classes. The stream classes are implemented in a rather elaborate hierarchy.

The iostream facility of C++ provides an easy means to perform I/O. The class istream uses the predefined stream cin that can be used to read data from the standard input device. The extraction operator >>, is used to get data from a stream. The insertion operator <<, is used to output data into a stream.

A stream object must appear on the left side of the << or >> operator, however multiple stream operators can be concatenated on a single line, even when they refer to objects of different types.


Predefined Console Streams

C++ supports four standard streams cin, cout, cerr and clog are automaticallyopened before the function main() is executed, they are closed after main() has completed. These predefined stream objects have the following meaning:

Cin - standard input corresponding to stdin in C.
Cout - standard output corresponding to stdout in C.
Cerr - standard error output corresponding to stderr in C.
Clog - a fully-buffered version of cerr.

Mapping Console in C++

C++ uses the concept of streams and stream classes to perform I/O operations with console and disk files. The stream classes supporting console-based input and output. Streams are classified into input streams and output streams. Streams resemble the producer and consumer model.

The producer produces items to be consumed by the consumer. The producers and consumers are connected by the C++ operators >> or <<. In C++ the I/O system is designed to operate on a wide variety of devices including console, disks, printer, etc. It is designed to provide a consistent and device independent interface.

A stream is a series of bytes, which act either as source from which input and data can be extracted or as destination to which the output can be sent. The source stream provides data to the program called the input stream and the destination stream that receives data from the program is called the output stream.

The C++ language offers a mechanism, which permits the creation of an extensible and consistent input-output system in the form of streams library. It is collection of classes and objects, which can be used to build a powerful system, or modified and extended to handle the user-defined data types.

Tuesday, 21 April 2015

Rules for Virtual Functions

? When a virtual function in a base class is created, there must be definition of the virutal function in the base       class even if base class version of the function is never actually called. However pure virtual functions are       exceptions.
? They cannot be static members.
? They can be a friend function to another class.
? They are accessed using object pointers.
? A base pointer can serve as a pointer to a derived object since it is type-compatible whereas a derived          object pointer variable cannot serve as a pointer objects.
? Its prototype in a base class and derived class must be identical for the virtual function to work properly.
? The class cannot have virtual constructors, but can contain virtual destructor. It is possible to have virtual        operator overloading.
? More importantly, to realize the potential benefits of virtual functions supporting runtime polymorphism,          they should be declared in the public section of a class.

Virtual Destructors

Virtual destructors are controlled in the same way as virtual functions. When a derived obje ct pointed to by the base class pointer is deleted, destructor of the derived class as well as destructors of all its base classes are invoked. If the destructor is made non-virtual destructor in the base class, only the base class’s destructor is invoked when the object is deleted.

Sample Program

#include <iostream.h>
class Father
{
protected:
char *fname;
public:
Father(char *name)
{
name = new char[strlen[name]+1]
strcpy(fname,name);
}
virtual ~Father()
{
delete fname;
cout<<”Father destructor”<<endl;
}
virtual void show(void)
{
cout<<”Father’s name”<<fname<<endl;
}
};
class Son:public Father
{
protected:
char *sname;
public:
Son(char *sn, char *fn):Father(fn)
{
sn = new char[strlen(sn}+1]
strcpy(sname,sn);
}
~Son()
{
delete sname;
cout<<”~son() is invoked”<<endl;
}
void show(void)
{
cout<<”Father name”<<fname<<endl;
cout<<”Son name”<<sn<<endl;
}
};
void main()
{
Father *Bp;
Bp = new Father(“James”);
Cout<<”Base pointes to base object….”<<endl;
Bp->show();
delete Bp;
Bp = new Son(“kdvam”,”dav”);
cout<<”Base pointes to derived object….”<<endl;
Bp->show();
Delete Bp;
}
the base class destructor is declared as virtual and basep actually addresses the son’s object and hence, the destructors in the son’s class as well as the father’s class are invoked. Note that while constructing an object, the constructors are invoked from the top of a hierarchy upto the current class and while hierarchy.

Virtual Destructor is used in the following situations:

? A virtual destructor is used when one class needs to delete object of a derived class   that are addressed by the base-pointers and invoke a base class destructor to release   resource allocated to it.

? Destructors of a base class should be declared as virtual fucntions. When delete   operations in performed on the object by a pointer or reference, the program will first   call the object destructor instead of the destructor associated with the pointer or reference type.




Abstract Classes

Abstract classes can be used as a framework upon which new classes can be built to provide new functionality. A framework is a combination of class libraries with predefined flow of control.

It can be a set of reusable abstract classes and the programmer can extend them. For instance, abstract classes can be easily tune d to develop graphical editors for different domains like artistic drawing, music composition, and mechanical CAD.

Abstract classes with virtual functions can be used as an aid to debugging

Pure Virtual functions

Virtual functions defined inside the base class normally serve as a framework for future design of the class hierarchy, these functions can be overridden by the methods in the derived classes.

In most of the cases, the pure virtual functions are defined with the null-body, it has no definition. Such functions in the base class are similar to do-nothing or dummy functions and in C++, they are called pure virutal functions. The syntax for defining the pure virtual function is

Virtual return_type function_name(arguments) = 0;

? A pure virtual function declared in a base class has no implementation as far as the
  base class is concerned.
? The classes derived from a base class having a pure virtual function have to define
   such a function or redeclare it as a pure virtual function.
? A class containing pure virtual functions cannot be used to define any objects of its
   own and hence such classes are called pure abstract classes or abstract classes.
? Where all other classes without pure virtual functions and which are instantiated are
   called as concrete classes.

Properties of Pure virtual function

1. A pure virtual function has no implementation in the base class hence, a class with
    pure virtual function cannot be instantiated.
2. It acts as an empty buc ket that the derived class is supposed to fill.
3. A pure virtual member function can be invoked by its derived class.

Definition of Virtual Functions

C++ provides a solution to invoke the exact version of the member function, which has to be decided at runtime using virtual functions. They are the means by which functions of the base class can be overridden by the functions of the derived class.

When declaring the base class member functions, the keyword virtual is used with those functions, which are to be bound dynamically. The syntax of defining a virtual function in a class is

Virtual return_type Function_name(arguments)
{
………….
………….
}

Virtual functions should be defined in the public section of a class to realize its full potential benefits. When such a declaration is made, it allows to decide which function to be used at runtime, based on the type of object, pointed to by the base pointer, rather than the type of the pointer.

Need For Virtual Functions

When objects of different classes in a class hierarchy, react to the same message in their own unique ways, they are said to exhibit polymorphic behavior. The following demonstrate the need for virtual functions.

It has the base class Father and the derived class Son and has a member function with the same and prototype. Note that, in C++ a pointer to the base class can be used to point to its derived class objects.

Sample Program

#include <iostream.h>
class Father
{
char name[40];
public:
Father(char *fname)
{
strcpy(name, fname);
}
void show(void)
{
cout<<”Father Name is “<<name<<endl;
}
};
class Son : public Father
{
char name[20];
public:
Son(char *sname, char *fname) : Father(fname)
{
strcpy(name, sname);
}
void show(void)
{
cout<<”Son Name is”<<name<<endl;
}
};
void main()
{
Father *Fp;
Father f1(“Thomas”);
Fp = &f1;
Fp->show();
Son s1(“Thomas”, “Martin”);
Fp = &s1;
Fp->show();
}

when executing this program the output will be same as “Thomas” for both of the show functions. There must be a provision to use the member function Show() to display the state of objects of both the Father and Son classes the same interface. This decision cannot be taken by the compiler, since the prototype is identical in both the cases.

In C++ a function call can be bound to the actual function either at compile time or at runtime. Resolving a function call at compile time is known as Compile-Time or Early or Static Binding whereas, resolving a function call at runtime is known as Runtime or Late or Dynamic Binding.

Runtime Ploymorphism allows to postpone the decision of selecting the suitable member functions until runtime. In C++, this is achieved by using Virtual Functions.

Sample Program

#include <iostream.h>

class Father
{
char name[20];
public:
Father(char *fname)
{
strcpy(name,fname);
}
virtual void show(void)
{
cout<<”Father name”<<name<<endl;
}
};
class Son:public Father
{
char name[30];
public:
Son(char *sname, char *fname):Father(fname)
{
strcpy(name,sname);
}
void show(void)
{
cout<<”Son name is”<<sname<<endl;
}
};
void main()
{
Father *fp;
Father f1(“James”);
fp = &f1;
fp->show();
Son s1(“James”,”Vasanth”);
fp = &s1;
fp->show();
}

the knowledge of pointers to base class and derived classes is essential to understand and to explore full potential of virtual functions.



Pointers to Derived Class

Pointers can be used with the objects of base classes or derived classes. Pointer to objects of a base class are type -compatible with pointers to objects of a derived class, thus allowing a single pointer variable to be used as pointer to objects of a base class and its derived classes.

C++ makes polymorphism possible through a rule that one should memorize: a base class pointer may address an object of its own class or an object of any class derived from the base class.

The use of a pointer to the objects of a base class with the objects of its derived class raises a new problem. It does not allow access even to public members of a derived class. That is, it allows access only to those members inherited from the base class but not to the members which are defined in the derived class.

Types of Polymorphism

Function Overloading is realized by invoking a suitable function whose signature matches with the arguments specified in the function call statement.

Operator Overloading is realized by allowing operators to operate on the user defined data-types with the same interface as that of the standard data types.

In both cases, the compiler is aware of the complete information regarding the type and number of operands. Hence it is possible for the compiler to select a suitable function at the compile-time.


Polymorphism

Polymorphism in biology means the ability of an organism to assume a variety of forms. In C++, it indicates the form of a member function that can be changed at runtime. Such member functions are called Virtual Functions and the corresponding class is called Polymorphic Class.

The objects of the polymorphic class, addressed by pointers, change at runtime and respond differently for the same message. Such a mechanism requires postponement of binding of a function call to the member function until runtime.


Friday, 17 April 2015

Pointer to Class Members


#include <iostream.h>
Class X
{
int y;

public:
int a,b;
int init(int z)
{
a = z;
return z;
}
};
void main()
{
X obj;
Int X::*ip;
ip = &X::a;
obj.*ip = 10;
cout<<”A in object, after obj.*ip”;
cout<<obj.*ip;
X *pobj;
Pobj = &obj;
Pobj->*ip = 20;
Cout<<”A in object, after pobj->*ip”;
Cout<<”pointer to member function\n”;
Int (X::*ptr)(int);
ptr = &X::init;
(obj.*ptr)(5);
(pobj->*ptr)(6);
}

this Pointer


C++ has a keyword this to address this substrate. The keyword this is a pointer variable, which always contains the address of the object in question.

The member function of every object has access to a pointer named this, which points to the object itself. When a member function is invoked, it comes into existence with the value of this set to the address of the object for which it called. The this pointer can be treated like any other pointer to an object.

Using a this pointer, any member function can find out the address of the object of which it is a member. Method of accessing a member of a class from within a class using this pointer.

Sample Program

#include <iostream.h>
class test
{
int a;

public:
void setdata(int ia)
{
a = ia;
this-> = ia;
}
void showdata(void)
{
cout<<”Data accessed in normal way”<<a;
cout<<”Data accessed through this”<<this->a;
}
};
void main()
{
test my;
my.setdata();
my.showdata();
}

Accessing Member Function using Object


The pointer to an object member can be obtained by applying the address of operator & to a fully qualified class member-name. The general format for accessing member functions using the object is

(Object_name.*pointer_to_Member_Function)(arguments)

Accessing Member Function using Object Pointer

The general format is

(Object_name->*pointer_to_Member_Function)(arguments)


Pointers to Object Members (Member Functions)

The general format for defining pointer to member function is as follows

Return_type (Class_name :: * pointer_to_function)(arguments)

To get the address of the member function is as follows

Pointer_to_function = & Class_name :: member_function_name


Accessing Data Members Through Object Pointer


C++ provides another operator ->* for use exclusively with pointers to members called member dereferencing operator. This operator is used to access a member using a pointer to it with pointer to the object. For example

Class X
{
int y;
public:
int a;
int b;
}
void main()
{

X *PO;
int X::*ptr; //
ptr = &PO::a; // int X::*ptr = &X::a;
PO->*ptr = 20;
int k = PO->*ptr;
}

Accessing Data Members Through Objects


C++ provides .* exclusively for use with pointers to members called member deference operator. This operator is used to access class members using a pointer to members and it must be used with the objects of the class. For example

Class X
{
int y;
public:
int a;
int b;
}
void main()
{
X Obj;
int X::*ptr; //
ptr = &X::a; // int X::*ptr = &X::a;
Obj.*ptr = 20;
int k = Obj.*ptr;
}

Pointers to Object Members (Data Members)


Whenever an object is created, memory is allocated to it. The data defining the object is held in the space allocated to it, i.e., the data and member functions of the object reside at specific memory locations subsequent to the creation of the object.

The pointer to an object member can be obtained by applying the address of operator & to a fully qualified class member-name.


Members of a class can be accessed using either pointer to an object, or pointer to members itself. A pointer to a class members is declared using the operator ::* with the class name. The syntax for defining the pointer to class members is


Data_type Class_name :: * Pointer_name

Pointer_name = &Class_name :: Member_name




Array of Pointers to Objects


An array of pointers to objects is often used to handle a group of objects, which need not necessarily reside contiguously in memory, as in the case of static array of objects. The syntax for defining an array of pointers to objects is the same as any of the fundamental types.

Sample Program

#include <iostream.h>
class ap
{
int data;
static int count;
public:
ap(void)
{
data = ++count;
}
void show(void)
{
cout<<”Data “<<endl;
}
};
void main()
{
ap *obj[10];
cout<<”Enter the number of objects to create”<<endl;
int no;
cin>>no;
for(int i=0;i<no;i++)
obj[i]->setcount();
for(int i=0;i<no;i++)
obj[i]->show();
}

Live Objects


Objects created dynamically with their data members initialized during creation are known as Live Objects. To create a live object, constructor must be invoked automatically which performs initialization of data members. Similarly the destructor for an object must be invoked automatically before the memory for that object is deallocated.

A class whose live object is to be crated must have atleast one constructor. The syntax for
creating a live object is as follows.

Pointer_to_Object = new Class_name(Parameters)


Sample Program

#include <iostream.h>
#include <string.h>
class student
{
int rno;
char *name;
public:
studen(void)
{
char flag, str[50];
cout<<”Do u want to initialize the object y/n”;
cin>>flag;
if(flag == ‘y’)
{
cout<<”Enter the student number”;
cin>>rno;
cout<<”Enter the student name”;
cin>>name;
}


else
{
rno =0;
name = NULL;
}
}
student(int rn)
{
rno = rn;
name = NULL;
}
student(int rn, char *n)
{
rno = rn;
name = n;
}
~student()
{
if(name)
delete name;
}
void show(void)
{
if(rno)
cout<<”Roll number is”<<rno<<endl;
else
cout<<”Number not initialized”<<endl;
if(name)
cout<<”Student name is “<<name<<endl;
else
cout<<”Name not initialized”<<endl;
}
};
void main()
{
student *s1, *s2, *s3;
s1 = new student;
s2 = new student(1);
s3 = new student(1,”Magesh”);
cout<<”Live objects contents………….”<<endl;
s1->show();
s2->show();
s3->show();
delete s1;
delete s2;
delete s3;
}




Dynamic Objects


The dynamic object can be created by the execution of a new operator expression. The syntax for creating a dynamic object is shown above. It returns the address of a newly created object. The returned address of an object can be stored in a variable of type pointer to object.

While creating a dynamic object, if a class has the default constructor, it is invoked as a part of object creation activity. Once a pointer is holding the address of a dynamic object, its members can be accessed by using -> operator. 

The syntax of delete operator releasing memory allocated to dynamic object is as
follows:

delete pointer_to_object


it destroys the object pointed to by pointer_to_object variable. It also invokes the destructor of the class if it exists as a part of object destruction activity before releasing memory allocated to an object by the new operator.


Sample Program

#include <iostream.h>
class de
{
public:
int data1;
char data2;
de(void)
{
cout<<”Constructor”<<endl;
data1 = 1;
data2 = ‘A’;
}
~de()
{
cout<<”Destructor”<<endl;
}
void show(void)

{
cout<<data1<<data2<<endl;
}
};
void main()
{
de *ptr_obj;
ptr_obj = new de;
cout<<”Accessing through dynamic object”<<endl;
ptr_obj->show();
cout<<”Destroying the dynamic object”<<endl;
delete ptr_obj;
}





Pointers to Objects


The allocation and deallocation of memory is done by new and delete operators in C++. A pointer to a variable can be defined to hold the address of an object, which is created statically or dynamically. Such pointer variables can be used to access data or function members of a class using the * or -> operators.

Pointer can be used to hold addresses of objects, just as they can hold addresses of primitives and userdefined data items. The need for using pointers to objects becomes clear when objects are to be created while the program is being executed, which is an instance of dynamic allocation of memory.

The new operator can also be used to obtain the address of the allocated memory area besides allocating storage area to the objects of the given class. The general format for defining a pointer to an object is

Class_name * pointer_to_object


The address operator & can be used to get the address of an object, which is defined statically during the compile time. The general form is as follows.

Pointer_to_object = &Object;

A pointer can be made to point to an existing object, or to a newly created object using new operator. The general form is as follows.

Pointer_to_object = new Class_name


Accessing Members of Objects


As in the case of pointers to structures, there are two approaches to referring and accessing the members of an object whose address resides in a pointer. The expression to access a class member using pointer is as follows:


Pointer_to_Object -> member_name;
                   
                     ( or )

*Pointer_to_Object . member_name



The member can be accessed through the object pointer can be either a data, or function member.


Sample Program

#include <iostream.h>
class de
{
public:
int data1;
char data2;
de(void)
{
cout<<”Constructor”<<endl;
data1 = 1;
data2 = ‘A’;
}
~de()
{
cout<<”Destructor”<<endl;
}
void show(void)
{
cout<<data1<<data2<<endl;
}
};
void main()
{

de *ptr1;
de obj;
ptr1 = &obj;
cout<<”Accessing members through object”<<endl;
obj.show();
cout<<”Accessing members through object pointer”<<endl;
ptr1->show();
}







POINTERS IN C++


Introduction

C++ takes the middle ground between languages, which support dynamic memory allocation, and languages in which all variables are dynamically allocated.

C++ supports creation of objects with scoped lifetimes and with arbitrary lifetimes. Stack-based objects are managed b the compiler implicitly, whereas heapbased objects are managed by the programmers explicitly.

A class can be instantiated at runtime and objects created by such instantiation are called Dynamic Objects. The lifetime of dynamic objects in C++ is managed explicitly by the program. The program must be guarantee that each dynamic object is deleted when it is no longer needed, and certainly before it becomes garbage. The lifetime of an object in

C++ is interval of time exists by occupying memory. Creation and deletion of objects as and when required, offers a great degree of flexibility in programming.

Objects with scoped lifetimes are created in the stack memory. Stack memory is a store house which holds local variables or objects, and whenever they go out of scope, the memory allocated for them in the stack is released automatically.

Objects with arbitrary lifetimes are created in the heap memory. These dynamic objects can be created or destroyed as and when required, explicitly by the programmer. The operators new and delete used with standard data type variable’s management can also be used for creating or destroying objects at runtime respectively.

Advantages of Inheritance


? When inherited from anoterh class, the code that provides a behavior required in the derived class need not    have to be rewritten. Benefits of reusable code include increased reliability and a decresed maintenance cost because of sharing of the code by all its users.

? Code sharing can occur at several levels. For example, at a higher level, many users or projects can use the same class. These are referred to as software components. At the lower level, code can be shared by two or more classes within a project.

? When multiple classes inherit from the same superclass, it guarantees that the behavior they inherit will be the same in all cases.

? Inheritance permits the construction of reusable software components. Already several such libraries are commercially available and many more are expected to able available in the near future.

? When a software system can be constructed largely out of reusable components, development time can be concentrated on understanding the portion of a new system. Thus, software systems can be generated more quickly and easily by rapid prototyping.

Multipath Inheritance and Virtual Base Classes


The form of inheritance which derives a new class by multiple inheritance of bas clsses, which an derived earlier from the same base class, is known as multipath inheritance. It involves more than one form of inheritance namely multilevel, multiple and hiearchical as shown in figure.




The base classes parent1 and parent2 shows that the multiple inheritance , then the grandparent class with parent1 and parent2 shows that the hierarchical inheritance , then the dotted line with grandparent and child shows that the multilevel inheritance , whereas the grandparent is referred to as the indirect base class.

Multipath inheritance can pose some problems in compilation. The public and protected members of grandparent are inherited into the child class twice, first, via parent1 class and the via parent2 class. Therefore, the child class would have duplicate sets of members of the grandparent which leads to ambiguity during compilation and it should be avoided.

C++ supports another important concept called virtual base classes to handle ambiguity caused due to the multipath inheritance. It is achieved by making the common base class as a virtual base class while declaring the direct or intermediate classes as shown below.


Class A
{
public:
void func(void)
{
// body of function
}
};
Class B1 : public virtual A
{
body of class B1
};
Class B2 : public virtual A
{
//body of class B2
};
Class D: public B1, public B2
{
//body of class D
};
consider the statement


obj.func();

where obj is the object of class D and invokes the func() defined in the class A. if the keyword virtual does not exist in the declaration of classes B1 and B2, a call to func() leads to the following compilation error:

Error : Member is ambiguous : ‘A::func’ and ‘B::func’

C++ takes necessary care to see that only one copy of the base class is inherited, when a class is inherited as virtual irrespective of the number of paths that exist between the virtual base class and the derived class. The keyword virtual and public or protected may be used in any order.

Consider the following diagram and the program for that.


Sample Program

#include <iostream.h>
class person
{
protected:
int rno;
char branch[30];
public:
void readstudentdata(void)
{
cout<<”Roll Number ?”;cin>>rno;
cout<<”Branch ?”;cin>>branch;
}
void displaystudentdata(void)
{
cout<<”Roll Number”<<rno;
cout<<”Branch”<<branch;
}
};
class internalexam:virtual public student
{
protected:
int sm1, sm2;
public:
void readdata(void)
{
cout<<”Enter two subject marks”;
cin>>sm1>>sm2;
}
void displaydata(void)
{
cout<<”Marks in two subjects”;
cout<<sm1<<sm2;
cout<<”Internal total “<<internaltotal()<<endl;l
}
int internaltotal(void)
{
return sm1 + sm2;
}
};
class externalexam : virtual public student
{
protected:
int sm1, sm2;
public:
void readdata(void)
{
cout<<”Enter two subject marks”;
cin>>sm1>>sm2;
}
void displaydata(void)
{
cout<<”Marks in two subjects”;
cout<<sm1<<sm2;
cout<<”External total “<<externaltotal()<<endl;l
}
int externaltotal(void)
{
return sm1 + sm2;
}
};
class result : public internalexam, public externalexam
{
int total;
public:
int totalmarks(void)
{
return internaltotal() + externaltotal();
}
};
void main()
{
result stud1;
cout<<”Enter data for student”<<endl;
stud1.readdata();
cout<<”Enter the Internal Marks….”<<endl;
stud1.interna lexam::readdata();
cout<<”Enter the External Marks….”<<endl;
stud1.externalexam::readdata();
cout<<”Student Details”<<endl;
stud1.displaystudentdata();
stud1.internalexam::displaydata();
stud1.externalexam::displaydata();
}







Saturday, 11 April 2015

Hybrid Inheritance


There could be situations where we need to apply two or more types of inheritance to design a program. For instance, refer the following figure.



From the figure derivation of student, test and Result, forms the multilevel inheritance and the derivation of test, sports and result, forms the multiple inheritance. So this type of inheritance is also called multiple and multilevel inheritance.


#include <iostream.h>
class student
{
protected:
int rno;
public:
void getnumber(int a)
{
rno = a;
}
void putnumber(void)
{
cout<<”Roll Number is “<<rno<<endl;
}
};
class test:public student
{
protected:
float p1, p2;
public:
void getmarks(float m, float n)
{
p1 = m; p2 = n;
}
void putmarks(void)
{
cout<<”Marks in two subjects”<<endl;
cout<<p1<<p2<<endl;
}
};

class sports
{
protected:
float score;
public:
void getscore(float s)
{
score = s;
}
void putscore(void)
{
cout<<”Sports “<<score<<endl;
}
};
class result : public test, public sports
{
float total;
public:
void display(void)
{
total = p1 + p2 + score;
putnumber();
putmarks();
putscore();
cout<<”Total score”<<total<<endl;
}
};
void main()
{
result student1;
student1.getnumber(123);
student1.getmarks(27.5,33.0);
student1.getscore(6.0);
student1.display();
}




Hierarchical Inheritance


Hierarchical model follows a top down approach by breaking up a complex class into
simpler constituent classes. In other words, in the hierarchical model, a complex class is
conceptualized as being made up of simpler classes, see figure.


In C++ hierarchical programs can be easily converted into class hierarchies. The
superclass (base class) includes the features that are common to all the subclasses
(derived classes). A subclass is created by inheriting the properties of the base class and
adding some of its own features. The sub can serve as a superclass for the lower level
classes again and so on.



#include <iostream.h>
class Vehicle
{
protected:
char name[25];
int WheelsCount;
public:
void GetData(void)
{
cout<<”Name of the Vehicle”;
cin>>name;
cout<<”Wheels”;
cin>>WheelsCount;
}
void DisplayData(void)
{
cout<<”Name of the Vehicle “<<name<<endl;
cout<<”Wheels “<<WheelsCount<<endl;
}
};
class LightMotor : public Vehicle
{
protected:
int SpeedLimit;
public:
void GetData(void)
{
Vehicle::GetData();
Cout<<”Speed Limit”;
Cin>>SpeedLimit;
}
void DisplayData(void)
{
Vehicle::DisplayData();
Cout<<”Speed Limit “<<SpeedLimit<<endl;
}
};
class HeavyMotor :public Vehicle
{
protected:
int LoadCapacity;
char permit[25];
public:
void Getdata(void)
{
Vehicle::GetData();
Cout<<”Load Carrying Capacity”;
Cin>>LoadCapacity;

Cout<<”Permit Type”;
Cin>>permit;
}
void DisplayData(void)
{
Vehicle::DisplayData();
Cout<<”Load Carrying Capacity”<<LoadCapacity<<endl;
Cout<<”Permit”<<permit<<endl;
}
};
class GearMotoe : public LightMotor
{
protected:
int GearCount;
public:
void GetData(void)
{
LightMotor::GetData();
Cout<<”No. of Gears”;
Cin>>GearCount;
}
void DisplayData(void)
{
LightMotor::DisplayData();
Cout<<”Gears”<<GearCount<<endl;
}
};
class NonGearMotor : public LightMotor
{
public:
void GetData(void)
{
LightMotor::GetData();
}
void DisplayData(void)
{
LightMotor::DisplayData();
}
};
class passenger: public HeavyMotor
{
protected:
int sitting;
int standing;
public:
void GetData(void)
{
HeavyMotor::GetData();

Cout<<”Maximum Seats”;
Cin>>sitting;
Cout<<”Maximum Standing”;
Cin>>standing;
}
void DisplayData(void)
{
HeavyMotor::DisplayData();
Cout<<”Maximum Seats”<<sitting<<endl;
Cout<<”Maximum Standing”<<standing<<endl;
}
};
class Goods : public HeavyMotor
{
public:
void GetData(void)
{
HeavyMotor::GetData();
}
void DisplayData(void)
{
HeavyMotor::DisplayData();
}
};
void main()
{
GearMotor vehi1;
Passenger vehi2;
Cout<<”Enter Data for Gear Motor Vehicle…….”<<endl;
Vehi1.GetData();
Cout<<”Enter data for passendger motor vehicle…”<<endl;
Vehi2.GetData();
Cout<<”data of gear motor vehicle…”<<endl;
Vehi1.DisplayData();
Cout<<”Data of passenger motor vehicle”<<endl;
Vehi2.DisplayData();
}



Constructors in Multiple Inheritance


The constructors in base classes can be no-argument constructors or multiple argument constructors.
No-argument Constructor

Sample Program

#include <iostream.h>


class A
{
public:
A()
{
cout<<”A”;
}
};


class B
{
public:
B()
{
cout<<”B”;
}
};
class C:public A, public B
{
public:
C()
{
cout<<”C”;
}
};
void main()
{
C obj;
}

the base class constructors are alw ays executed first, working from the first base class to the last and finally through the derived class constructor.



Overloaded Function in Base and Derived classes


#include <iostream.h>
class A
{
char ch;
public:
A(char c)
{
ch = c;
}
void show(void)
{
cout<<ch;
}
};
class B
{
char ch;
public:
B(char b)
{
ch = b;

}
void show(void)
{
cout<<ch;
}
};
class C:public A, public B
{
char ch;
public:
C(char c1, char c2, char c3):A(c1), B(c2)
{
ch = c3;
}
void show(void) // overloaded function in derived class
{
A::show();
B::show();
cout<<ch;
}
};
void main()
{
C obj(‘a’,’b’,’c’);
Cout<<”A class show”;
// Obj.A::show();
Cout<<”B class show”;
// Obj.B::show();
Obj.show //derived class show will be executed
}


Ambiguity in Member Functions Constructors with parameters


Ambiguity is a problem that surfaces in certain situations involving multiple inheritance. Consider the following cases:

? Base classes having functions with the same name.
? The class derived from base basses is not having a function with the name as those of
   its base classes.
? Members of a derived class or its objects referring to a member, whose name is the
  same as those in base classes.

These situations create ambiguity in deciding which of the base class’s function has to be referred. The problem is resolved using the scope resolution operator. The syntax for handling ambiguity in multiple inheritance.

ObjectName.BaseClassName::MemberName(…)


Sample Program

#include <iostream.h>
class A
{
char ch;
public:
A(char c)
{
ch = c;
}
void show(void)
{
cout<<ch;
}
};
class B
{
char ch;
public:
B(char b)
{
ch = b;
}

void show(void)
{
cout<<ch;
}
};
class C:public A, public B
{
char ch;
public:
C(char c1, char c2, char c3):A(c1), B(c2)
{
ch = c3;
}
};
void main()
{
C obj(‘a’,’b’,’c’);
Cout<<”A class show”;
Obj.A::show();
Cout<<”B class show”;
Obj.B::show();
// obj.show //Error, Because it creates the ambiguity
}


Multiple Inheritance


A class can be derived by inheriting the traits of two or more base classes. Multiple inheritance refers to the derivation of a class from several i.e., two or more base classes. It allows the combination of the features of several existing, tested, and well proven classes as a starting point for defining new classes. Multiple inheritance model is as follows:



Sample Program


#include <iostream.h>
class ac
{
protected:
int cno;
char *name;
float amt;
public:
void newac(void)
{
cout<<”Enter the a/c number”;
cin>>cno;
cout<<”Enter the a/c name”;
cin>>name;
cout<<”Enter the initial amount”;
cin>>amt;
}
};
class dep
{
protected:
int dep;
public:
void depamt(void)
{
cout<<”Deposit amount is”<<dep;
}
};
class bank:public ac, public dep
{
float tot;
public:
void process(void)
{
newac();
depamt();
tot = amt + dep;
}
void showac(void)
{
cout<<”Number is “<<cno<<endl;
cout<<”Name is”<<name<<endl;
cout<<”Amount is”<<tot<<endl;
}
};
void main()

{
bank B;
B.process();
B.showac();
}



Thursday, 9 April 2015

Way of calling Constructors and Destructors

#include <iostream.h>
class B1
{
public:
B1()
{
cout<<”No-argument constructor of the base class B1”;
}
~B1()
{
cout<<”Destructor in the Base class B1”;
}
};
class B2
{
public:
B2()
{
cout<<”No-argument constructor of the base class B2”;
}
~B2()
{
cout<<”Destructor in the Base class B2”;
}
};
class D:public B1, public B2
{
public:
D()
{
cout<<”No-argument constructor of the derived class D”;
}
~D()
{
cout<<”Destructor in the Base class D”;
}
};
void main()
{
D obj;
}

Constructors in Inheritance

The constructors play an important role in initializing an object’s data members and allocating required resources such as memory. The derived class need not have a constructor as long as the base class has a no-argument constructor. However, if the base class has constructors with arguments then its is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. In the application of inheritance, objects of the derived class are usually created instead of the base class.

Hence, it makes sense for the derived class to have constructor and pass arguments to the constructor of the base class. When an object of a derived class is created, the constructor of the base class is executed first and later the constructor of the derived class.


In multiple inheritance, the constructors of base classes are invoked first, in the order in which they appear in the declaration of the derived class, whereas in the case of multilevel inheritance, they are executed in the order of inheritance.


It is responsibility of the derived class to supply initial values to the base class constructor, when the derived class objects are created. Initial values can be supplied either by the object of a derived class or a constant value can be mentioned in the definition of the constructor. The syntax for defining a constructor is

Derived_classname(argumentlist):base(argument),base(argument)….
{
body of derived class constructor
}

Constructors in Single Inheritance

Sample Program

#include <iostream.h>
class base
{
int a,b;
public:
base(int x, int y)
{
a = x;
b = y;
}
void showbase(void)
{
cout<<”Base value are”;
cout<<a<<b<<endl;
}
};
class deri:public base
{
int x,y;
public:
deri(int k, int l, int m, int n):base(m,n)
{
x = k;
y = l;
}
void showderi(void)
{
cout<<”derived values are”;
cout<<x<<y<<endl;
}
};
void main()
{
deri D(10,20,30,40);
D.showbase();
D.showderi();
}


Constructors in Multilevel Inheritance



Sample Program


#include <iostream.h>
class base
{
int rno;
char *name
public:
base(int no, char *n)
{
rno = no;
strcpy(name,n);
}
void showbase(void)
{
cout<<rno<<name<<endl;
}
};
class deri1:public base
{
int m1, m2;
public:
deri(int j, int k, int l, char *n):base(l,n)
{
m1 = j;
m2 = k;
}
void showderi1(void)
{
cout<<”derived1 values are”;
cout<<m1<<m2<<endl;
}
};
class deri2:public deri1
{
int tot;
public:
deri2(int i, int j, int k, int l, char *n):deri1(j,k,l,n)
{
tot = i;
}
void showderi2(void)
{
cout<<”derived2 values are”;
cout<<tot
}
};
void main()
{
deri D(100,50,50,101,”DKam”);
D.showbase();
D.showderi1();
D.showderi2();
}

Multilevel Inheritance

Derivation of a class from another derived class is called multilevel inheritance. It is very common in inheritance that a class is derived from a derived class, from the figure, the class B is the base class for the derived class D1, which is in turn serves as a base class for the derived class D2. The class D1 provides a link for the inherit ance between B and D2, and is known as intermediate base class. The chain B, D1, D2 is known as the inheritance path.

#include <iostream.h>
class student
{
protected:
int rno;
public:
void getnumber(int);
void putnumber(void);
};
void student::getnumber(int a)
{
rno = a;
}
void student::putnumber(void)
{
cout<<”Roll Number is”<<rno<<endl;
}
class test:public student
{
protected:
float sub1;
float sub2;
public:
void get_marks(float, float);
void put_marks(void);
};
void test::get_marks(float x, float y)
{
sub1 = x; sub2= y;
}
void test::put_marks(void)
{
cout<<”marks in sub1 = “<<sub1<<endl;
cout<<”marks in sub2 = “<<sub2<<endl;
}
class result:public test
{
float total;
public:
void display(void);
};
void result::display(void)
{
total = sub1 + sub2;
putnumber();
put_marks();
cout<<”Total = “<<total<<endl;
}
void main()
{
result student1;
student1.getnumber(111);
student1.get_marks(56,45);
student1.display();
}

Wednesday, 8 April 2015

Overloaded Member Functions

The members of a derived class can base the same name as those defined in the base class. An object of a derived class refers to its own functions even if the y are defined in both the base class and the derived class. In the derived class there can also be functions with the same name as those in base class. It results in ambiguity. The compiler resolves the conflict by using the following rule :

If the same member exists in both the base class and the derived class, the member in the derived class will be executed.

If we want to invoke the base class member function, then the syntax is

Base_classname::memberfunction();

Sample Program

#include <iostream.h>
class B
{
protected:
int x;
int y;
public:
void read(void)
{
cout<<”X in class B”;
cin>>x;
cout<<”Y in class B”;
cin>>y;
}
void show(void)
{
cout<<”X in class B is “<<x<<endl;
cout<<”Y in class B is “<<y<<endl;
}
};
class D : public B
{
protected:
int y;
int z;
public:
void read(void)
{
B::read();
cout<<”Y in class D”;
cin>>y;
cout<<”Z in class D”;
cin>>z;
}
void show(void)
{
B::show();
cout<<”Y in class D is “<<y<<endl;
cout<<”Z in class D is “<<z<<endl;
}
};
void main()
{
D obj;
Cout<<”enter the data for object of class D”;
Obj.read();
Cout<<”Content of object of class D”<<endl;
Obj.show();
// or we can use Obj.B::show()
}

Protected Access Specifier

We have seen how to increase the capabilities of an existing class without modifying it. We have also seen that a private member of a base class cannot be inherited and therefore it is not available for the derived class directly. What do we do if the private data needs to be inherited by a derived class. This can be accomplished by modifying the visibility limit of the private member by making public.


C++ provides a third visibility modifier, protected, which serve a limited purpose in inheritance. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the function outside these two classes.


When a protected member is inherited in pubic mode, it becomes protected in the derived class too, and therefore is accessible by the member functions of the derived class. It is also ready for further inheritance. A protected member, inherited in the private mode derivation, become private in the derived class. Although it is available to the member functions of the derived class, it is not available for further inheritance.


Now let us review the control to the private and protected data, the member functions of a derived class can directly access only the prtected data.


Sample Program

#include <iostream.h>
class one
{
protected:
int rno;
char name[10];
public:
void showname(void)
{
cout<<”Student Number is “<<rno<<endl;
cout<<”Student Name is”<<name<<endl;
}
};
class two:public one
{
float tot;
public:
void setdata(void)
{
cout<<”Enter the Rno, name and total\n”;
cin>>rno>>name>>tot;
}
void showtot(void)
{
cout<<”Total mark is”<<tot;
}
};
void main()
{
two D;
D.setdata();
D.showname();
D.showtot();
}

Single Inheritance


A derived class inherits data members and member functions, but not the constructor or destructor from its base class. The inheritance will be two types they are

? Private inheritance
? Public inheritance

Public inheritance

Sample Program

#include <iostream.h>
class Bird
{
private:
int wlength;
int weight;
public:
void setbird(int w, int wt)
{
wlength = w;
weight = wt;
}
void showwing(void)
{
cout<<”My wing length is “<<wlength<<”inches”<<endl;
cout<<”My weight is<<weight<<”Kgs”<<endl;
}
};
class Parrot:public Bird
{
private:
char color[10];
public:
void showpro(void)
{
cout<<”I can talk”<<endl;
}
};
void main()
{
Parrot P1, P2;
P2.setbird(15,3);
P1.showwing();
P1.showpro();
P2.showwing();
P2.showpro();
}


Private Inheritance

Sample Program

#include <iostream.h>
Class B
{
int a;
public:
int b;
void get_ab(void);
int get_a(void);
void show_a(void);
};
class D : private B
{
int c;
public:
void mul(void);
void display(void);
};
void B::get_ab(void)
{
cout<<”Enter the values for a and b”;
cin>>a>>b;
}
int B::get_a(void)
{
return a;
}
void B::show_a(void)
{
cout<<”a = “<<a<<endl;
}
void D::mul(void)
{
get_ab();
c = b * get_a();
}
void D::display(void)
{
show_a();
cout<<”b = “<<b<<endl;
cout<<”c = “<<c<<endl;
}
void main()
{
D d;
d.mul();
d.display();
// d.b = 20 wront will not work
d.mul();
d.display();
}