You are on page 1of 50

OBJECT ORIENTED PARADIGM

USING C++

COMPILED BY:

TECHNOVATIVE AND TEAM

www.technovative.orgObject Oriented Paradigm 1

Technovative Pvt. Ltd.

www.technovative.org

Acknowledgements
We would like to acknowledge the following people for their kindness and support in making this book possible. Suresh KUMAR Mukhiya (Kathford) Prabin Shakya (St. Xavier) Saput Shrestha (New Summit) Nikesh Man Singh (St. Xavier) Madhu Pandey (Kathford) Rajkumar Bhandari (St. Xavier) Nitu Shrestha (Kathford)

www.technovative.org

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the NEPAL at (9849) 709357

website: http://www.technovative.org e-mail: anithub.technovative@gmail.com


No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Differences between procedural oriented programming (POP) language and object-oriented programming (OOP) language. We can compare the procedure-oriented programming with object-oriented programming in following ways: Procedure-oriented focus more on functions where as OOP focus on data. OOP deals with real world objects. In POP, error detection is difficult as we can't know which variable is associated with which function where as in OOP, we can specify with the object that which variable is associated with which function. Objects in OOP create many modules of program, which is flexible and easier to execute and also understand. OOP provides inheritance in which features can be added to existing classes without modification. In POP, importance is given for doing things. In OOP, importance is given on data rather than procedure. POP, most of function share global data. In OOP, data structures are designed such that the characteristics the object function that operate not the data of any object which are tied tighter in the data structure. POP, larger programs are divided into smaller programs known as function. OOP programs are divided into smaller programs known as objects. In POP, security is not provided for object. In OOP, security is provided to data. In POP, top down approach is used. OOP uses bottom up approach. Properties of OOP 1. 2. 3. 4. Class and objects Data encapsulation & data binding Inheritance & Polymorphism Generic programming

Classes and objects A CLASS is a group of related objects. An OBJECT is an entity that has behavior with which you can communicate. It may have data associated with it. It can also be used to implement an abstract data type, in which case it is a data type encapsulated by function. Classes contain functions that are MEMBERS of the class. If there are data items in the class, they can be restricted so that they can only be accessed through the member functions. Another name for the functions within a class that access the data is a METHOD. The process of insuring that you can only get at a data item through the class functions is called ENCAPSULATION. The operators used on the data within the class (via functions that define the operator's behavior) are PROTOCOLS. The values that are passed to and from the member functions to set, alter, and retrieve encapsulated data and are called MESSAGES.

www.technovative.org

A class is a way of controlling access to (encapsulating) data. What are encapsulated are a set of data declarations and a set of functions (methods) for accessing and updating the data. Functions within a class are divided into categories. - Public functions/operators can be accessed from "outside" - Private functions/operators can be accessed only from within the class Subclasses can be defined (derived) from other (base) classes. Subclasses can share (inherit) the operations from the base class (parent class) they were derived from. Classes and subclasses can be organized into hierarchies of inclusion, with the most general (abstract) class at the root of the hierarchy tree.
#include <iostream.h> class triangle { private: double side1, side2, side3; public: void set (double a = 1.0, double b = 1.0, double c = 1.0); double perimeter (); triangle operator + (triangle b); void print (); }; void triangle::set (double a, double b, double c) { side1 = a; side2 = b; side3 = c; }

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

double triangle::perimeter () { return ( side1 + side2 + side3); } triangle triangle::operator + (triangle b) { triangle temp; temp.side1 = side1 + b.side1; temp.side2 = side2 + b.side2; temp.side3 = side3 + b.side3; return temp; } void triangle::print () { cout << "(" << side1 << ", " << side2 << ", " << side3 << ")\n"; }

Data encapsulation & data binding Data encapsulation means combining data and functions into a single unit (called class) and hiding the implementation of the data from the user of the object. The data in an object are called its instance data field and the procedures that operate on the data are called its methods. The data is not accessible to the outer world and only those functions, which are wrapped in class, can access it. This insulation of the data from direct access by the program is called data hiding or information hiding. Data encapsulation and data hiding are synonymously used. Since, an object represents both data and functions that operate on data. While accessing this data, one cannot access the data directly. The only way to access the data is through member functions. So, the data is hidden for functions that are defined outside the object. This is actually data hiding. Features of data encapsulation 1. It restricts outside function to access data defined. 2. Data hiding assures accidental alternation of data. 3. A specific object that is an instance of a class will have specific values of its instance fields. The sets of those values is the current state of the object, its state may change. 4. The degree of data hiding and accessibility options are declared by member access specifiersprivate, public and protected. Example:
Class class_name { private: variable declaration; function declaration; public:

www.technovative.org

variable declarations; functions declarations; };

Private Area

Specific example, No Entry Allowed Dat a Functions

class item{ private: int number; float cost; public: void setdata(int b); void pntdata(void); }; Entry allowed to public area

a,

float
Public Area

Dat a Functions

Every declaration is private by default unless specified. Here, member function setdata and putdata can only access the private data number and cost. Any functions outside of class cannot access it unless it is a member function or a friend function. Program should interact with object data only through the objects method. Encapsulation is the way that gives the object its black box behavior. Advantage and disadvantages of OOP Advantages We perceive the world around us as being made up of objects and the brain arranges this information into chunks. OOP design use objects in programming language, which aids in trapping in existing pattern of human thought into programming. Since the objects are autonomous entities and share their responsibilities only by executing methods relevant to the received messages. Each object lends itself to greater modularity. Cooperation among different objects to achieve the system operation is done through exchange of messages. The independence of each object eases development and maintenance of the program. Information hiding and data abstraction increases reliability and help decouple the procedural and representational specification from its implementation. Dynamic binding increases flexibility by permitting the addition of new class of objects without having to modify the existing code. Inheritance coupled with dynamic binding enhances the reusability of a code. Thus increasing the productivity of a programmer.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Many OOP languages provide a standard class library that can be executed by the users, thus saving a lot of coding and debugging effort. Reducing, the amount of code simplifies understanding and thus allows building reliable programs. Code reuse is possible in conventional languages as well, but OOP, languages greatly enhance the possibility to reuse. Object orientation provides many other advantages in the production and maintenance of software; shorter development times, high degree of code sharing and malleability. These advantages make OOP an important technology for building complex software system. Disadvantages The runtime cost of dynamic binding mechanism is the major disadvantages of object-oriented languages. The following were, the demerits of adopting object-orientation in software developments in the early days of computing. Compiler overhead Runtime overhead Re-orientation of software develop to object-oriented thinking Require the mastery over the following areas: o Software engineering o Programming methodologies Benefits only on long run while managing large software projects, moderately at least moderately large ones.

Object oriented concepts are becoming important in many areas of computer science, including programming, graphics, CAD systems, database, user interface, application integration platforms, distributed systems and network management architectures. OOP technology is more than just a way of programming. It is a way of thinking abstractly about a problem using real world concepts rather than computer concepts. Although object orientation has been around for many years, it is only recently that it has received major attention vendors and methodologies. OOP is gradually picking up as an important technology for building complex software systems. For any programming languages to succeed. It must be easy to learn programmers must be able to master language constructs easily. They must be able to reuse code written by them earlier without much modification in a new software project, and above all. The programming language should be received well by application and system software developers. Inheritance & Polymorphism: Inheritance: Inheritance is the process by which objects of one class acquire the properties of object of another class. Inheritance supports the concept of hierarchical classification. The old class is referred as base class (super class) and the new class is called derived class (sub class). The process is called inheritance or derivation.

www.technovative.org

Base Class Data Members Data 1 Member Functions

Derived Class Data Members Data 1 Member Functions

Fig: UML diagram showing single Inheritance If a class is already defined, then we can create new class from it. The derived class consists of all characteristics of base class plus some refinement and improvement of its own. Why inheritance is fruitful? The main advantage of using inheritance is the reusability of code. When a class is written and debugged, it can be used in various situations with or without modifications. It not only saves time and money, but also, reduces frustration and increase reliability. It saves the effort of developing and testing the same program again and again. More than once class can be derived from a single class.

Types of inheritance 1. Single inheritance: If only one class is derived from a base class, it is known as single inheritance. Most of OOP support single inheritance. 2. Multiple inheritance: A derived class with multiple base classes is defined as multiple inheritance. Java doesnt support multiple inheritance and operator overloading. However, c++ compiler shows multiple inheritance. 3. Hybrid inheritance: Inheritance using more than one types of inheritances is called as hybrid inheritance.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

B
Fig: Single Inheritance

Fig: Multiple Inheritance

Fig: Hybrid Inheritance

Polymorphism Polymorphism is the ability of different functions to be invoked with the same name. There are two forms. Static polymorphism is the common case of overriding a function by providing additional definitions with different numbers or types of parameters. The compiler matches the parameter list to the appropriate function. Dynamic polymorphism is much different and relies on parent classes to define virtual functions, which child classes may redefine. When this virtual member function is called for an object of the parent class, the execution dynamically chooses the appropriate function to call - the parent function if the object really is the parent type, or the child function if the object really is the child type. This explanation is too brief to be useful without an example, but that will have to be written latter. Friend Functions and its importance Definition A friend function of a class is defined outside that classs scope, yet had the right to access the nonpublic members of the class.

www.technovative.org

Need We know private members of a function cannot be accessed from outside class. That is, a nonmember function cannot have an access to the private data of a class. However, there can be a situation where we would like two classes to share particular function. For such type of situation, C++ provides a mechanism to access private class by using a function called friend function. Thus, a friend class is a class whose member function can access another class private member. Declaration
class name{ -----public: . .. friend void function_name(void); //declaration };

Example
class Accumulator { private: int m_nValue; public: Accumulator() { m_nValue = 0; } void Add(int nValue) { m_nValue += nValue; } // Make the Reset() function a friend of this class friend void Reset(Accumulator &cAccumulator); }; // Reset() is now a friend of the Accumulator class void Reset(Accumulator &cAccumulator) { // And can access the private data of Accumulator objects cAccumulator.m_nValue = 0; }

In this example, weve declared a function named Reset() that takes an object of class Accumulator, and sets the value of m_nValue to 0. Because Reset() is not a member of the Accumulator class, normally Reset() would not be able to access the private members of Accumulator. However, because Accumulator has specifically declared this Reset() function to be a friend of the class, the Reset() function is given access to the private members of Accumulator. Characteristics of a friend function It is preceded by keyword friend. It is not in the scope of the class to which it has been declared as friend. A friend function is not a member function of the class. It cannot be called using object of that class. It can be invoked like normal function without the help of any object.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Unlike object function, it cannot access the member names directly and has to use an object name and dot membership operator with each member name. [e.g. A.x] It can be declared wither in public or private part of a class without affecting its meaning. Usually, it has the objects as arguments.

Merits of using friend function Friend function allows accessing private members of a class. Friend functions are used in operator overloading. Friend function declaration can be done anywhere in the class definition. Member function of one class can be declared as friend function of another class using scope resolution operator. [::]

Demerits of using friend function Some people in OOP community feel, friend function corrupts information hiding and weakens the value of the object-oriented paradigm. Objects according to the size of friend function will occupy maximum size of the memory. We cant do any runtime polymorphism concept in those members.

This pointer The this pointer is a special pointer that points to an object of the type of the class for which the member function currently is being executed. Each class member function contains a this pointer that addresses the objects for which the member function is called. Thus, this pointer is: A pointer to the class type in a non-const member function. A pointer to the const class in a const member function. A pointer to a volatile class in a volatile member function. The pointer this acts as an implicit argument to all the member function and is passed by compiler.

Let us consider an example:


class distance{ private: int meter; float cm; public: distance(); void getdata(int, float); void setdata(int, float); void display(); };

A question that arises here is, how does a member function which objects data members to manipulate? The answer to this is, use of this pointer. Actually, each member function is defined with one additional parameters: the this; pointer that remains hidden argument to every member function. For example, in above program, functions internally are treated as: www.technovative.org

void getdata(distance *this); void setdata(distance *this); void display(distance *this);

Explicit declaration
class abc { int a; }

This private variable a can be directly used inside a member function like a=123. However, we can also explicitly define, as
thisa=123;

Applications of this pointer The most important is, it allows member function to know which object is being called. During binary operator overloading, using a member function, only one argument is passed to the function. The other argument is passed using this pointer. This pointer allows returning object it points to. For example,
return *this;

This is used when we compare two or more objects inside a member function and returning invoking objects as results. Example:
person & person:: greater (person &x) { if (x.age>age) return x; //argument object else return *this; } //invoking object

If we invoked function call, max = a. greater (b), the function will return b if age of person b is greater than a, otherwise return the object a.
#include <iostream.h> #include <conio.h> class number{ int i, j; public: void seti(int x=0;int y=3) { i =x; //thisi=x; j=y; //thisj=y; }

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


void display() { cout<<endl<<i<< } void add(number n){ i = i+n.j; j = j+n.j; } }; void main() { number a,b; a.seti(10,20); b.seti(20,30); a.add(b); a.display(); }

www.technovative.org

<<j;

Operator overloaded to find sum of complex number.


#include<iostream> #include<stdio.h> #include<conio.h> using namespace std; struct complex { int real; int img; }; void getdata(complex &); complex sum(complex,complex); complex mult(complex,complex); void display(complex); int main() { complex c1,c2,c3,c4; getdata(c1); getdata(c2); c3=sum(c1,c2); cout<<"Sum= "; display(c3); c4=mult(c1,c2); cout<<"MULT= "; display(c4); getch(); return 0; } complex sum(complex c1,complex c2) { complex c; c.real=c1.real+c2.real;

www.technovative.org

c.img=c1.img+c2.img; return c; } void display(complex c) { cout<<c.real<<"+"<<c.img<<"i"<<endl; } complex mult(complex c1,complex c2) { complex c; c.real=c1.real*c2.real-c1.img*c2.img; c.img=c1.img*c2.real+c1.real*c2.img; return c; } void getdata(complex &c) { cout<<"Enter first complex number:"<<endl; cout<<"Enter real "; cin>>c.real; cout<<"Enter img "; cin>>c.img; }

Class access specifiers In a class specifiers, the members whether data or functions can be private, meaning they can be accessed only by member functions of that class, or public, meaning they can be accessed by any function in the program. The primary mechanism for hiding data is to put it in a class as a private. Data hiding with the security techniques used to protect computers database. The data is hidden so it will be safe from accidental manipulation, while the functions that operate on the data are public so they can be accessed from outside the class. To use a member function, the dot operator connects the object name and member function. The dot operator is also called the class member access operator. There are three access specifiers are given by C++. Public: The members declared as Public are accessible from outside the Class through an object of the class. Private: These members are only accessible from within the class. No outside Access is allowed. Protected: The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
class MyClass { public: int a; protected: int b;

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


private: int c; }; int main() { MyClass obj.a = obj.b = obj.c = }

www.technovative.org

obj; 10; 20; 30;

//Allowed //Not Allowed, gives compiler error //Not Allowed, gives compiler error

Access Member Specifiers

Public
Member functions Other functions

Private
Member functions Friend functions

Protected
Member functions Friend Functions

Fig: Access member specifiers and its visibility Importance Data hiding or encapsulation is an important property of object-oriented paradigm, which is achieved by these access member specifiers. Member access specifiers give the degree and visibility of class members. Access specifiers protected plays an important role during inheritance.

Member access specifiers during inheritance Inheritance is C++ can be one of the following types: Private Inheritance Public Inheritance Protected inheritance Public Inheritance: All Public members of the Base Class become Public Members of the derived class & All Protected members of the Base Class become Protected Members of the Derived Class. i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members. Code Example:
Class Base { public: int a; protected: int b;

www.technovative.org

private: int c; }; class Derived:public Base { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } }; int main() { Derived obj.a = obj.b = obj.c = }

obj; 10; //Allowed 20; //Not Allowed, Compiler Error 30; //Not Allowed, Compiler Error

Private Inheritance: All Public members of the Base Class become Private Members of the Derived class & All Protected members of the Base Class become Private Members of the Derived Class. An code Example:
Class Base { public: int a; protected: int b; private: int c; }; class Derived:private Base //Not mentioning classes it defaults to private { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } }; private is OK because for

class Derived2:public Derived { void doSomethingMore() { a = 10; /*Not Allowed, Compiler Error, a is private member of Derived now*/ b = 20; /*Not Allowed, Compiler Error, b is private member of Derived now*/

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


c = 30; } }; int main() { Derived obj.a = obj.b = obj.c = }


//Not Allowed, Compiler Error

www.technovative.org

obj; 10; //Not Allowed, Compiler Error 20; //Not Allowed, Compiler Error 30; //Not Allowed, Compiler Error

Protected Inheritance: All Public members of the Base Class become Protected Members of the derived class & All Protected members of the Base Class become Protected Members of the Derived Class. A Code Example:
Class Base { public: int a; protected: int b; private: int c; }; class Derived:protected Base { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } }; class Derived2:public Derived { void doSomethingMore() { a = 10; /*Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2*/ b = 20; /*Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2*/ c = 30; //Not Allowed, Compiler Error } }; int main() { Derived obj.a = obj.b = obj.c =

obj; 10; //Not Allowed, Compiler Error 20; //Not Allowed, Compiler Error 30; //Not Allowed, Compiler Error

www.technovative.org

Constructors and its types Definition: In simple terms, Constructor is a special kind of method with class name as method name and gets executed when its (class) object is created. A constructor is a class method that gets automatically executed whenever classs object is created or whenever class is initialized. Consider following bit of code:
public class MsDotNetHeaven { public MsDotNetHeaven() { //A default Constructor } //Class members }

In the above snippet, the method MsDotNetHeaven() is called the constructor of class MsDotNetHeaven, also called default constructor. Explanation Whenever you try to create an object of class or initialize a class, then the default constructor will be automatically invoked.
//Initializes the Class MsDotNetHeaven objMsDnH = new MsDotNetHeaven();

Features of constructors A constructor takes the same name as the class name. The programmer cannot declare a constructor as virtual or static, nor can the programmer declare a constructor as const, volatile, or const volatile. No return type is specified for a constructor. The constructor must be defined in the public. The constructor must be a public member. Overloading of constructors is possible. Constructors can be virtual. Types of Constructor It can be always debated, but I always like to segregate constructors by following types: Default Constructor A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.
class Exforsys {private:

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


int a,b; public: Exforsys(); ... };

www.technovative.org

Exforsys :: Exforsys() { a=0; b=0; }

Parameterized Constructor At times, we will require initializing class members during instantiation and this is the time where parameterized constructor will come into picture. It follows the same rules as default constructor and will have parameters. Go through following snippet:
public class MsDotNetHeaven { public MsDotNetHeaven() { //A default Constructor } public MsDotNetHeaven(String strName) { //A parameterized Constructor having one parameter } public MsDotNetHeaven(String strFirstName, String strLastName) { //A parameterized Constructor having two parameters } //Class members }

Note: A default constructor should be explicitly declared while declaring parameterized constructor. Copy constructor: This constructor takes one argument, also called one argument constructor. The main use of copy constructor is to initialize the objects while in creation, also used to copy an object. The copy constructor allows the programmer to create a new object from an existing one by initialization.

www.technovative.org

For Example:
#include <iostream.h> class Exforsys { private: int a; public: Exforsys() { } Exforsys(int w) { a=w; } Exforsys(Exforsys& e) { a=e.a; cout << " Example of Copy Constructor"; } void result() { cout<< a; } }; void main() { Exforsys e1(50); Exforsys e3(e1); cout<< "ne3=";e3.result(); }

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd. Constructors in Derived Classes

www.technovative.org

A constructor is a member function with the same name as its class. For example: class X { public: X(); // constructor for class X }; # Constructors are used to create, and can initialize, objects of their class type. # You cannot declare a constructor as virtual or static, nor can you declare a constructor as const, volatile, or const volatile. # You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value. # A member function with the same name as its class is a constructor function. Constructors cannot return values. Specifying a constructor with a return type is an error, as is taking the address of a constructor. # If a class has a constructor, each object of that type is initialized with the constructor prior to use in a program. # Constructors are called at the point an object is created. Example

// constructors.cpp // compile with: /c class MyClass { public: MyClass(){} MyClass(int i) : m_i(i) {}

private: int m_i; }; Construction order of derived class objects When a derived class object is created using constructors, it is created in the following order: 1. Virtual base classes are initialized, in the order they appear in the base list. 2. Nonvirtual base classes are initialized, in declaration order. 3. Class members are initialized in declaration order (regardless of their order in the initialization list). 4. The body of the constructor is executed. The following example demonstrates this: www.technovative.org

#include <iostream> using namespace std; struct V { V() { cout << "V()" << endl; } }; struct V2 { V2() { cout << "V2()" << endl; } }; struct A { A() { cout << "A()" << endl; } }; struct B : virtual V { B() { cout << "B()" << endl; } }; struct C : B, virtual V2 { C() { cout << "C()" << endl; } }; struct D : C, virtual V { A obj_A; D() { cout << "D()" << endl; } }; int main() { D c; }

The following is the output of the above example:


V() V2() B() C() A() D()

The above output lists the order in which the C++ run time calls the constructors to create an object of type D.
Derived-class constructor must call a base-class constructor before it does anything else. If the base class constructor is not called explicitly in a derived-class constructor, the system will try to invoke the base-class's no-arg constructor. But, remember, a base class will have a no-arg constructor only if you provide one, or, by default, if you have defined no constructors at all for the base class. In what follows, we will first use the User class example to illustrate the more common case, which is that of a derived-class constructor making an explicit call to a base-class constructor.
//DerivedConstructor.cc #include <iostream> #include <string> using namespace std; class User { string name; int age; public: // BASE

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

User( string nm, int a ) { name = nm; age = a;} void print(){cout << "Name: " << name << " Age: " << age;} }; class StudentUser : public User { // DERIVED string schoolEnrolled; public: StudentUser( string nam, int y, string school ) : User( nam, y ) { //(A) schoolEnrolled = school; } void print() { User::print(); cout << " School Enrolled: " << schoolEnrolled << endl; } }; int main() { StudentUser student( "Maura", 20, "ece" ); student.print(); // Name: Maura Age: 20 School Enrolled: ece return 0; }

Through the initialization syntax in line (A), the constructor of the derived-class object explicitly calls the base-class constructor to construct the base-class portion of the derived class object. After that, the derived class constructor proceeds to bring into existence what is defined explicitly for the derived class. A derived class object thus built is best shown pictorially as in Figure 1.

Figure 1
As was mentioned at the beginning of this section, if a base-class constructor is not invoked explicitly in a derived-class constructor, the system tries to invoke the no-arg constructor of the base class for initializing the base-class subobject. In the following program, the derived-class constructor in line (D) makes no mention of a base-class constructor. The base-class has been provided with an explicitly defined no-arg constructor in line (A) and a 1-arg constructor in line (C).

WAP to overload a function to calculate area of rectangle, triangle, and circle.


#include <iostream.h> #include <conio.h> double area(double);

www.technovative.org

float area(float,float); long int area(int,int); void main() { cout<<"Volume of the rectangle"<<area(4.4,10); cout<<"Volume of the circle"<<area(10); cout<<"Volume of the triangle"<<area(8,6); getch(); } int area(int a) { return (3.1416*a*a); } int area(float b, int h) { return (0.5*b*h); } int area(long int l, int b, int h) { return (l*b); }

Generic programming What is generic programming? Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety for suitable data types and data structure. Generic class and generic functions support this programming. A template can be used to create a family or functions. For example, a class template for an array class would enable to create arrays of carious data types like float, integer, double, etc.
Generic programming

Generic functions (Template with function)


Fig: Generic programming

Generic classes (Template with class)

Features of templates A template is a kind of macro. When an object of specific type is defined for actual use, the template definition for that class is substituted with the required data types. Templates are also called as parameterized classes or functions.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

a. Template function: The general format of a function template is:


template <class x> return_type function_name(arguments of type x) { //. // body of function //. }

Let us see a template function to swap any number. Here, the number can be either, integer, float.
#include <iostream.h> #include <conio.h> #include <stdio.h> template <class x> void swap (x &a, x &b) { x temp; temp =a; a=b; b= temp; } void main() { int a,b; cout<<enter any number?; cin>>a; cout<< second number?; cin>>b; float c = 2.5; float d = 5.6; swap(a,b); swap(c,d); cout<<a<<endl<<b; cout<<c<<endl<<d; getch(); }

b. Class Template: Class templates are often used to build safe container classes such as stack, queues, and linked list, in which maintenance of the container is generic but the item in the container is specific. In abstract data types, we could only create data types of stack or queues. This limitation is overcome by class template. The general format of class template is:
template <class T> class class_name { //. //class member specifications //. };

www.technovative.org

Let us take an example of class template


#include <iostream.h> #include <conio.h> const size =3; template <class T> class vector { T* V; public: vector() { V = new T[size]; for(int i=0;i<size;i++) V[i]=0; } vector (T* a) { for(int i =0;i<size;i++) V[i]=a[i]; } T operator * (vector &y) { T sum = 0; for (int i = 0;i<size;i++) sum+ = this->V[i]*y.V[i]; return sum; } }; int main() { int x[3]={1,3,4}; int y[3] = {3,4,5}; vector <int> v1; vector <int> v2; v1=x; v2 = y; int R = v1*v2; cout<<R1=<<R<<endl; return o; getch(); }

Advantages Same class or functions can be used for different data types. If change is required, then only few codes require changing. Templates reduce the size of source code and increases the code flexibility without reducing the safety.

C++ Program to find the roots of quadratic equations using template function.
#include <iostream.h>

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


#include <conio.h> #include <math.h>

www.technovative.org

template <class T> void roots (T a, T b, T c) { T d = b*b-4*a*c; if(d==0) { cout<<R1=R2=<< -b/(2*a)<<endl; } else if(d>0) { cout<<Roots are real<<endl; float R = sqrt(d); float R1 = (-b+R)/(2*a); float R2 = (-b-R)/(2*a); cout<<R1=<<R1<<and<<endl; cout<<R2=<<R2<<endl; } else { cout<<Roots are complex <<endl; float R1 = -b/(2*a); float R2 = sqrt(-d)/(2*a); cout<<Real part =<<R1<<endl; cout<<imaginary part=<<R2<<endl; } }

Operator overloading Operator overloading allows the programmer to define how operators (such as +, -, ==, =, and !) should interact with various data types. Because operators in C++ are implemented as functions, operator overloading works very analogously to function overloading. Consider the following example:
int nX = 2; int nY = 3; cout << nX + nY << endl;

C++ already knows how the plus operator (+) should be applied to integer operands the compiler adds nX and nY together and returns the result. Now consider this case:
Mystring cString1 = "Hello, "; Mystring cString2 = "World!"; cout << cString1 + cString2 << endl;

The intuitive expected result is that the string Hello, World! is printed on the screen. However, because Mystring is a user-defined class, C++ does not know what operator + should do. We need to tell it how the + operator should work with two objects of type Mystring. Once an operator has been www.technovative.org

overloaded, C++ will call the appropriate overloaded version of the operator based on parameter type. Features Almost any operator in C++ can be overloaded. The exceptions are: arithmetic if (?:), sizeof, scope (::), member selector (.), and member pointer selector (.*). At least one of the operands in any overloaded operator must be a user-defined type. This means you cannot overload the plus operator to work with one integer and one double. You can only overload the operators that exist. You cannot create new operators. For example, you could not create an operator ** to do exponents. All operators keep their current precedence and Associativity, regardless of what they're used for. For example, the bitwise XOR operator (^) could be overloaded to do exponents, except it has the wrong precedence and Associativity and there is no way to change this. Example: C++ program to add two complex numbers using operator overloading
#include<iostream> #include<stdio.h> #include<conio.h> using namespace std; struct complex { int real; int img; }; void getdata(complex &); complex sum(complex,complex); complex mult(complex,complex); void display(complex); int main() { complex c1,c2,c3,c4; getdata(c1); getdata(c2); c3=sum(c1,c2); cout<<"Sum= "; display(c3); c4=mult(c1,c2); cout<<"MULT= "; display(c4); getch(); return 0; } complex sum(complex c1,complex c2) { complex c; c.real=c1.real+c2.real; c.img=c1.img+c2.img; return c; }

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

void display(complex c) { cout<<c.real<<"+"<<c.img<<"i"<<endl; } complex mult(complex c1,complex c2) { complex c; c.real=c1.real*c2.real-c1.img*c2.img; c.img=c1.img*c2.real+c1.real*c2.img; return c; } void getdata(complex &c) { cout<<"Enter first complex number:"<<endl; cout<<"Enter real "; cin>>c.real; cout<<"Enter img "; cin>>c.img; }

What is destructor? What are its significance and examples. What is the use of Destructors? Destructors are also special member functions used in C++ programming language. Destructors have the opposite function of a constructor. The main use of destructors is to release dynamic allocated memory. Destructors are used to free memory, release resources and to perform other clean up. Destructors are automatically named when an object is destroyed. Like constructors, destructors also take the same name as that of the class name. General Syntax of Destructors
~ classname();

The above is the general syntax of a destructor. In the above, the symbol tilda ~ represents a destructor which precedes the name of the class. Some important points about destructors: o Destructors take the same name as the class name. o Like the constructor, the destructor must also be defined in the public. The destructor must be a public member. o The Destructor does not take any argument, which means that destructors cannot be overloaded. o No return type is specified for destructors. Type casting and its importance Converting an expression of a given type into another type is known as type casting. Sometimes it is important to guarantee that a value is stored as a real number, even if it is in fact a whole number. A common example is where an arithmetic expression involves division. When applied to two values of type int, the division operator "/" signifies integer division, so that (for example) 7/2

www.technovative.org

evaluates to 3. In this case, if we want an answer of 3.5, we can simply add a decimal point and zero to one or both numbers - "7.0/2", "7/2.0" and "7.0/2.0" all give the desired result. However, if both the numerator and the divisor are variables, this trick is not possible. Instead, we have to use a type cast. For example, we can convert "7" to a value of type double using the expression "static_cast<double>(7)". Hence in the expression
answer = static_cast<double>(numerator) / denominator

the "/" will always be interpreted as real-number division, even when both "numerator" and "denominator" have integer values. Other type names can also be used for type casting. C style typecasting
#include <iostream> using namespace std; int main() { for ( int x = 0; x < 128; x++ ) { cout<< x <<". "<< (char)x <<" "; //Note the use of the int version of x to // output a number and the use of (char) to // typecast the x into a character // which outputs the ASCII character that // corresponds to the current number } cin.get(); }

The typecast described above is a C-style cast, C++ supports two other types. First is the functionstyle cast: Function-style cast
int main() { cout<< char ( 65 ) <<"\n"; cin.get(); }

This is more like a function call than a cast as the type to be cast to is like the name of the function and the value to be cast is like the argument to the function. Next is the named cast, of which there are four:
int main() { cout<< static_cast<char> ( 65 ) <<"\n"; cin.get(); }

static_cast is similar in function to the other casts described above, but the name makes it easier to spot and less tempting to use since it tends to be ugly. Typecasting should be avoided whenever possible. The other three types of named casts are const_cast, reinterpret_cast, and dynamic_cast. They are of no use to us at this time.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Exception handling, why it is required merits and demerits Exception is a problem other than logic or syntax error that prevents the continuation of the method or the scope the user is in. in fact, exceptions are run time anomalies or unusual conditions that a program may encounter while executing.

domain_error

invalid_argument Logic_error length_error

Exception

Out_of_range

range_error runtime_error overflow_error

Causes of exceptions Stack overflow Fig: Standard Exception hierarchy Division by zero Unable to open file Violating the boundary of an array Falling short of memory Attempting to initialize an object to an impossible value

underflow_error

Types of exceptions Asynchronous: The errors that are caused by events beyond the control of the problems are called as asynchronous exception. For example, keyboards interrupt. Synchronous: The errors that are caused by the control of program are called as synchronous exception. For example, division by zero.

www.technovative.org

Steps in exception handling The purpose of exception handling mechanism is to provide means to detect and report exceptional circumstances so that appropriate action can be taken. It involves following steps: Find the problem (Hit the exception) Inform that an error is found (throw the exception) Receive an error information (catch the exception) Take the corrective actions (handle the exception)

C++ supports exceptions with three keywords: try, catch, and throw. The syntax looks like this:
try { // Something that may call "throw", e.g. throw(Exception("Uh-oh")); } catch(Exception& e) { // Do something useful with e }

General syntax
.. . try { throw exceptions(); } catch (type argument) { . } ..

Let us see and exception handling program for division by zero.


#include <iostream.h> #include <conio.h> void main() { int a,b; cout<<Enter value of a and b; cin>>a>>b; int x = a-b; try { if(x!=0) { cout<< Result (a/x)=<<a/x<<endl;

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


} else { throw (x); }

www.technovative.org

} catch(int i) { cout<< Exception caught: x=<<x<<endl; } cout<< End; getch(); }

Discussion An exception in C++ is a simpler technique, such as returning an error code or message. The semantics of using exceptions (e.g., "trying" something, "throwing" an exception, and subsequently "catching" it) are distinct from other kinds of C++ operations. When an exceptional situation arises, and you think the calling code should be made aware of it, you can stuff your message with the throw statement, as in:
throw(Exception("Something went wrong"));

When you do this, the runtime environment constructs an Exception object, then it begins unwinding the call stack until it finds a try block that has been entered but not yet exited. If the runtime environment never finds one, meaning it gets all the way to main (or the top-level scope in the current thread) and can't unwind the stack any further, a special global function named terminate is called. But if it does find a try block, it then looks at each of the catch statements for that try block for one that is catching something with the same type as what was just thrown. Something like this would suffice:
catch(Exception& e) { //...

At this point, a new Exception is created with Exception's copy constructor from the one that was thrown. (The one in scope at the throw is a temporary, so the compiler may optimize it away.) The original exception is destroyed since it has gone out of scope, and the body of the catch statement is executed. If, within the body of the catch statement, you want to propagate the exception that you just caught, you can call throw with no arguments:
throw;

This will continue the exception handling process down the call stack until another matching handler is found. This permits each scope to catch the exception and do something useful with it, then rethrow it when it is done (or not).

www.technovative.org

What are restrictions on operator overloading? The following restrictions apply to operator overloading: Invention of new operators is not allowed. For example:

void operator @ (int) ; //illegal, @ is not a built-in operator or a type name

Neither the precedence nor the number of arguments of an operator may be altered. An overloaded && for example, must have exactly two arguments--just like the built-in && operator. The following operators cannot be overloaded: Direct member access operator . De-reference pointer to class member operator .* Scope resolution operator :: Conditional operator ?: Sizeof operator sizeof Similarly, any of the new casting operators: static_cast <>, dynamic_cast <>, reinterpret_cast <> and const_cast <>, as well as the # and ## preprocessor tokens, may not be overloaded.

WAP to convert polar coordinate into rectangular coordinate.


#include <iostream.h> #include <math.h> class rectangle { float r, t; public: void getData(float ra, float ang) { r = ra; t = ang; } void display(){ float x,y; t = t*0.017453; x = r*cos(t); y = r*sin(t); cout<<"Rectangular coordinates are:"; cout<<endl<<"X= "<<x<<endl; cout<<endl<<"Y= "<<y<<endl; } }; int main(int argc, char * const argv[]){ rectangle re; float radius, angle; cout<<"Enter radius and angle:"<<endl; cin>>radius>>angle; re.getData(radius,angle); re.display();

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


return 0; }

www.technovative.org

What do you mean by inline function? What are its uses and abuses? The major objectives of using function in a program is to To save memory space, which is achieved if the function in called many times in the program. To avoid repetition of same codes, again and again.

However, if the function is small, every time a function is called, it tales a lot for extra time in executing a series tasks such as: Jumping to the function Saving registers Pushing arguments into stack Transferring function location to the program counter Returning to the calling function

So, if the function is small, a substantial percentage of execution time is spent in such overloads. This gives compiler an extra burden. The solution to this problem can be proposed in following two ways: Definition of macros: They are not function actually, and since usual error checking does not occur during compilation, it is not good solution. Invoking inline function: It is a function that is expanded in the line when it is invoked. Compiler binds the function calls with the corresponding code.

Definition of inline function Syntax


inline function_header { function body; } Example inline double cube(double a) { return (a*a*a); }

Some area where inline function does not work It is applicable when the size of function is small, so, it does not work for large functions. For function returning values, if a loop, a switch or a goto exits.

www.technovative.org

For function not returning values, if a return statement exists. If function contains static variable. If incline function are recursive.

Advantages It makes a program run faster as the overhead of a function call and return is eliminated. It reduces the extra burden of compiler. It is easy to make a function inline, as we just need to attach the keyword inline to the definition of the function.

Disadvantages It is only applicable for small functions. Since, it is request rather than command, the compiler may ignore it.

Program to find cube of integer using inline function.


#include <iostream.h> #include <conio.h> inline int cube(double a) { return (a*a*a); } int main() { int x; cout<<Enter the value of x:; cin>>x; cout<<Cube of integer is:; cout<<cubeRoot(x); getch(); return 0; }

Function overloading Definition C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types or arguments. Program to find the volume of cube, volume of cylinder, volume of rectangular box, using function overloading. TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

#include <iostream.h> #include <conio.h> int volume(int); float volume(float,int); long int volume(long int,int, int); void main() { cout<<"Volume of the cube"<<volume(4.4,10); cout<<"Volume of the cylinder"<<volume(10); cout<<"Volume of the rectangular box"<<volume(8,6,4); getch(); } int volume(int a) { return (a*a*a); } int volume(float r, int h) { return (3.14*r*r*h); } int volume(long int l, int b, int h) { return (l*b*h); }

Create an abstract class shape with tow members base and height, a member function for initialization and pure virtual function to compute area. Derive two specific classes triangle and rectangle and override the function area. Use these classes in a main function and display area of the triangle and rectangle.
#include <iostream.h> #include <conio.h> class shape { protected: float base, height; public: void getData(float b, float h) { base =b; height=h; } virtual void area()=0; }; class triangle:public shape{ public: void getData(float b, float h){

www.technovative.org

shape::getData(b,h); } void area(){ float area2 = (base*height)*0.5; cout<<"\n Area of triangle is="<<area2; } }; class rectangle:public shape{ public: void getData(float b, float h) { shape::getData(b,h); } void area() { float area1 = (base*height); cout<<"\n Area of rectangle is="<<area1; } }; int main (int argc, char * const argv[]) { triangle *tptr; rectangle *rptr; shape *sptr1, *sptr2; int i,l,b; tptr = new triangle; rptr = new rectangle; cout<<"Enter base and height:"; cin>>l>>b; tptr->getData(l,b); rptr->getData(l,b); sptr1 = tptr; sptr2 = rptr; sptr1->area(); sptr2->area(); getch(); return 0; } Sample output Enter base and height: 20 30 Area of triangle=300 Area of rectangle =600

What do you mean by message passing? Explain in context to C++? An object program consists of a set of objects that communicate with each other. So, message passing is an idea of sending message to an object, causing it to perform an operation by involving the appropriate function of the object. The process of programming in an OOP, involves the following basis steps: TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Create classes and define their behaviors Create objects from class definitions Establish communication among them

Objects communicate with one another by sending and receiving information much the same way as people pass message. A typical message communication between two objects is shown: Sending Objects Sending Objects For example, Fig: Typical message Passing Student roll_no (name)
Information

Object name

Message

A message for an object is a request for execution of a procedure, and therefore will invoke a function in the receiving object that generates the desired result. Message passing involves following specification: Name of the object The name of the function (message) Information to be sent e.g. employee salary(name);
Information

Object name

Message

Objects are created and destroyed. Communication is feasible for active objects only (alive objects). Write a program to convert feet into meter.
#include <iostream.h> class convert{ double feet; public:

www.technovative.org

void getData(double f){ feet = f; } void convertToMeter(){ double meter =0.3048*feet; cout<<"feet="<<feet<<endl; cout<<"meter="<<meter<<endl; } }; int main (int argc, char * const argv[]) //this is same as void main() { convert ne; double f; cout<<"Enter feet?"<<endl; cin>>f; ne.getData(f); ne.convertToMeter(); return 0; }

Write a program to convert inch into centimeter.


#include <iostream.h> class convert{ double inch; public: void getData(double f){ inch = f; } void convertToCm(){ double cm =2.54*inch; cout<<"inch="<<inch<<endl; cout<<"cm="<<cm<<endl; } }; int main (int argc, char * const argv[]) { convert ne; double f; cout<<"Enter inch?"<<endl; cin>>f; ne.getData(f); ne.convertToCm(); return 0; }

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Write a c++ program to convert Fahrenheit into Celsius scale.


#include<iostream.h> #include<conio.h> #include<math.h> class temp { float c; public: temp() { c=0; } temp(float cel) { cel = c; } void display(float cel) { float f; f = 1.8*cel+32; cout<<"WHEN C="<<cel<<"THEN"<<"F= "<<f<<endl; } void main() { temp p; float c; cout<<"Enter temperature in celcius"; cin>>c; p.display(c); getch(); } }

Write a c++ program to swap two numbers using inline function.


#include<iostream.h> #include<conio.h> void swap(int, int); void main() { int a,b; cout<<"Enter the two numbers"; cin>>a>>b; cout<<"The number which you entered are"<<endl; cout<<"a=="<<a<<endl<<"b=="<<b<<endl; swap(a,b); getch(); } inline void swap(int a, int b) { int temp; temp a; a=b; b=temp;

www.technovative.org

cout<<"The swapped numbers are as follows"<<endl; cout<<"a=="<<a<<endl<<"b=="<<b<<endl; }

Write a c++ program to implement insertion sort using template function.


#include<iostream.h> #include<conio.h> template<class x> void insertion(x *a, int n) { x hold; int i,j; for(i=1;i<n;i++) { hold=a[i]; for(j=i-1;j>=0&&a[j]>hold;j--) a[j+1]=a[j]; a[j+1]=hold; } } void main() { int a[7]={1,4,8,9,12,36,98}; float b[7]={0.1,4,8.90,9,12.36,36,9.8}; insertion(a,7); insertion(b,7); for(int i=0;i<=6;i++) { cout<<i<<endl; for(int j=0;j<=6;j++) { cout<<j<<endl; } getch(); } }

Write a c++ program to implement quick sort using template function.


#include<iostream.h> #include<cstdlib> using namespace std; template<class T> void quicksort(T a[], const int &leftarg, const int &rightarg) { if(leftarg<rightarg) { T pivotvalue=a[leftarg]; int left=leftarg-1; int right=rightarg+1; for(;;) { while(a[--right]>pivotvalue); while(a[++right]<pivotvalue); if(left>=right)break;

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


T temp = a[right]; a[right]=a[left]; a[left]=temp;

www.technovative.org

} int pivot = right; quicksort(a, leftarg, pivot); quicksort(a, pivot +1, rightarg); } } int main(void) { int sortme[10]; for(int i=0;i<10;i++) { sortme[i]=rand(); cout<<sortme[i]<<" "; }; cout<<endl; quicksort<int>(sortme, 0, 10 - 1); for(int i=0;i<10;i++) cout<<sortme[i]<<" "; cout<<endl; return 0; }

Write a c++ program to add and multiply any two matrices using operator overloading.
#include<iostream.h> #include<conio.h> #include<math.h> class Matrix { int A[10][10]; int m,n; public: Matrix(int a, int b) { m=a; n=b; } void readmatrix(); void printmatrix(); void addmatrix(Matrix b); Matrix operator *(Matrix b); }; void Matrix::readmatrix() { for(int i=0;i<m;i++) { for(int j=0;j<n;j++) cin>>A[i][j]; } } void Matrix::printmatrix() { for(int i=0;i<m;i++) {

www.technovative.org

for(int j=0;j<n;j++) { cout<<A[i][j]<<" "; } cout<<endl; } } void Matrix::addmatrix(Matrix b) { Matrix c(m,n); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { c.A[i][j]=A[i][j]+b.A[i][j]; } } cout<<"The Addition of the Two Matrices is:"<<endl; c.printmatrix(); } Matrix Matrix::operator*(Matrix b) { Matrix c(m,n); for(int i=0;i<m;i++) { for(int k=0;k<m;k++) { c.A[i][k]=0; for(int j=0;j<n;j++) { c.A[i][k]=A[i][j]*b.A[j][k]+c.A[i][k]; } } } return c; } void main() { clrscr(); cout<<"Enter Order The two square matrices:"; int a; cin>>a; Matrix x(a,a); Matrix y(a,a); cout<<endl<<"Enter elements in first matrix :"; x.readmatrix(); cout<<endl<<"Enter elements in the second matrix:"; y.readmatrix(); cout<<endl<<"The First Matrix:"<<endl; x.printmatrix(); cout<<endl<<"The Second Matrix:"<<endl; y.printmatrix(); x.addmatrix(y); Matrix c(a,a); c=x*y; cout<<"The Multiplication of the Two Matrices are:"<<endl;

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.


c.printmatrix(); getch(); }

www.technovative.org

What are defects in multiple inheritances? Explain with example. => Ambiguity occurs when two base classes contains a function of the same name, while a class derived from both base classes has function with the very same name. First class display() Second class display()

Third class display()

Fig.: Inheritance problem specification

Example
#include<iostream.h> class first{ public: void display() { cout<<"first class"; } }; class second { public: void display() { cout<<"Second class"; } }; class third: public first, public second { public: }; void main() { third t; t.display(); getch();

www.technovative.org

In this the compiler becomes double minded about the reference of display function that appears in both classes first and second.
Remedy

It can be removed by scope resolution operator.(::)


t.first::display() t.second::display()

=>Ambiguity comes when a derived class has multiple copies of the same base class. Example:
#include<iostream.h> class first { public: void display() { cout<<"\n i am in the first base class"; } }; class second: public first { }; class third: public first { }; class fourth: public second, public third {

First

Second

Third

Fourth

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

}; void main() { forth f; f.display(); }

In this the compiler becomes double minded, whether it intend to call the copy of f.display() of second or third. So, it throws message: Member is ambigious: first::display and first::display
Remedy

Like,

By scope resolution operator By declaring bare class virtual

class second: public virtual first { } Class third: public virtual first

Virtual Functions Class derivation is even more valuable when combined with virtual functions--functions that are declared in a base class, but implemented differently in each derived class. Consider the Shape class. It will need a grow function so that every Shape can increase its size.
class Shape { public: void grow(); .... };

But the grow function must be different for each class derived from Shape. Thus we make grow a virtual function
class Shape { public: virtualvoid grow (); ........ };

The Circle, Square and Triangle classes will now provide their own custom versions of grow. The circle version might look like:
class Circle: public Shape { public: void grow () { radius++; } ...... private: int radius;// radius of circle .... }

If cis a Circleobject, the call c.grow()increases the radius of c. When grow()is invoked through a pointer to a base class, the virtual function uses the correct grow function depending on the kind of object pointed to. www.technovative.org

If pis a pointer to a Shapeobject, then sinceCircleand Squareare derived from theShapeclass, pcould be pointing to either one of these classes. If ppoints to a Circleobject thenCircle::growwill be used, and converselySquare::growif ppoints to a Squarewhich has to be expanded.
Shape* p; Circle c; Square s; p = &c; p->grow(); p = &s;

Notice the use of ->to call grow. Calling a member function from a pointer to an object requires >instead of the dot operator. Many function calls--even overloaded ones--can be resolved by the compiler. Others can't and require dynamic binding by the loader (just how this is done is left to the operating systems course), but the need is clear. Consider:
if (....) p = &c; else p = &s; p->grow();// calls either Circle::grow //orSquare::grow

There is no way that the compiler can know how p will be set during execution. Overloading and overriding Overloading Overriding Overloading is a compile time Overriding is runtime polymorphism. polymorphism. It means, change existing behaviors. It means, add more behaviors. In overriding, we re-implement or In overloading, the parameters should change the functionality of the base be unique i.e. the number of class method in derived class. The parameters should differ or the type number of parameters and return type should be different. This is because should be same. compiler should know the methods in It appears in subclass. compile time. There is relationship between a super They appear in the same class or a class method and subclass method. subclass. Overriding blocks inheritance. There is relationship between methods available in the same class. Overloading does not block inheritance from the super class.

TECHNOVATIVE PVT. LTD.

Technovative Pvt. Ltd.

www.technovative.org

Bibliography
The book is compiled by a team of Technovative members. The following resources were used to compile the book. www.wikipedia.org C++ Program Design, Cohoon and Davidson, McGraw-Hill, 1999 Object oriented Programming-an Evolutionary Approach, Cox B J and Andrew J Novobilski, Addision-Wesley, 1991 C++ How to Program, Deital and Deital, Osborne McGraw-Hill, 1989 Computer Programming in C: V Rajaraman C programming Using turbo C++: Robert Lafore Programming in C++: Dehurst, Stephen C and Kathy T. Stark, Prentice-Hall, 1989 C++ Primer: Lippman, Stanley B and Josee Lajoie, Addison-Wesley, 1989 The C++ Programming Language: Stroupstroup Bjarne, Addison-Wesley, 1997 A text Book of C programming Language, Karn and Mahato, Benchmark Publication, 2010. Turbo C/C++ Users Guide, Borland International Fundamentals of Computers Algorithms: Horowitch and Sahani, Galgotia, 1995 C programming Language: Kernighan, BW and Ritchie, Prentice-Hall, 1955 C programming Language: An applied perspective, Miller L H and Quilici E A, Wiley, 1971 The C Odessey: Mukhi, Vijay C Encyclopedia, Radclifee R A, Sybex, 1990 The C programming Tutor, Wortaran L A and Sidebototon T O, Prentice-Hall, 1984 Programming with C++: Ravichandran, Tata McG: G.S. Baluja Practicals and Projects in C++: Sumita Arora, Dhanpat Rai & Co.(P) LTD. Tizzard K, C for professional Programmars, Affiliated East-West Press Pvt. Ltd, New Delhi, 1986.

www.technovative.org

You might also like