Sie sind auf Seite 1von 82

Learning and Knowledge

Inheritance

2006 IBM Corporation

Learning & Knowledge

Inheritance
Objectives
Explaining the inheritance Explaining how to derive inherited classes Using constructors in inheritance Using protected access specifier contd on the next slide..
2 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Explaining public inheritance Explaining private inheritance Using method overriding Using multiple inheritance Explaining virtual function

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Introduction
Inheritance is a powerful feature of OOP and its most important use is in software reusability. It is the process of creating new classes from already existing classes. The new class is called derived class and the already existing class is called the base class. The derived class inherits all the capabilities of the base class and can have some additional capabilities.

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance
The derivation of a class from only one base class
is called single inheritance and it is the ability of derived class to inherit member functions and member variables of the existing base class.

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance - Example


class worker class employee { private : int empno; char empname[20]; char desig[20]; public : void getinfo(); void printinfo(); }; }; { private : int empno; char empname[20]; char desig[20]; int bp, da, hra, netpay; public : void getinfo(); void printinfo(); void getpaydetails(); void printpaydetails();

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance
Notice that in both employee and worker classes
the fields empno, empname, desig and methods getinfo, printinfo() are the same.

We can declare worker class we can inherit the


features of employee class

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance
A Derived class is defined by specifying its relationship with the
base class in addition to its own details.

General form of defining a derived class is


Class derived_class : visibility_mode base_class Derived_class name of the derived class Visibility_mode access permission for the members of the derived class, it may either be private, public or protected Default access specifier is private Base_class is the name of the base_class from where we want to draw the features

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance - Example


class worker class employee { private : int empno; char empname[20]; char desig[20]; public : void getinfo(); void printinfo(); }; }; { private : int empno; char empname[20]; char desig[20]; int bp, da, hra, netpay; public : void getinfo(); void printinfo(); void getpaydetails(); void printpaydetails(); }; class worker : public employee { private : int bp, da, hra, netpay; public : void getpaydetails(); void printpaydetails();

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Derived class
The colon (:) indicates that we are inheriting
something.

It indicates the derivation of derived class (worker)


from the base class (employee)

The visibility mode is public.


i.e when a base class is publicly inherited, all public members of the base class becomes public members of the derived class.

10

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Single Inheritance - Example


Refer worker.cpp

11

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

The Access Specifier


An access specifier defines the accessibility of variables and functions at different parts in the body of a program. Access specifiers are of three types: 1. Private 2. Protected 3. public

12

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

For a class: private members (both data and methods) are accessible within that class only. protected members are accessible within that class and its derived sub_classes as well. public members are accessible everywhere and anywhere in the program using that class.

13

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Table summarizing different accessibility relationships: access specifier accessible within accessible from the class outside the class private protected public yes yes yes No No yes

Table: Accessibility relationship in a class

14

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Public Inheritance
In public inheritance base class properties are inherited in the derived class using the public keyword. all the derived class member functions can be access protected and public members of the base class. the derived class functions cannot access the private class members of the base class.

15

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

In public inheritance the protected and public class members of the base class are derived as protected and public members respectively in the derived class. the derived class definition begins as shown below: class derived_class : public base_class { ----------------------------} This accessibility relationship is shown diagrammatically in the next figure.
16 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Figure: Accessibility relationship in public inheritance


17 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Summary of accessibility relationships in public inheritance. base class accessible accessible accessible access from ow n from from outside specifier class derived the class class private yes no no protected yes yes no public yes yes yes Table:Accessibility relationships in public inheritance

18

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

The following table shows an accessibility relation in public base class member visibility private protected
06/09/11 2006 IBM Corporation

19

Programming in C++

Learning & Knowledge

Private Inheritance
In private inheritance base class properties are inherited in the derived class using the private keyword. the derived class member functions can access only the protected and public class members but not the private members of the base class. the protected and public members of the base class are derived as private members in the derived class.

20

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

In private inheritance objects of the derived class cannot access private, protected and even public members of the base class. the derived class definition begins using the private keyword as shown below: class derived_class_name : private base_class_name { --------------------} This accessibility relationship is shown diagrammatically in the following figure.
21 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Figure: Accessibility relationship in private inheritance


22 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

The table below summarises the accessibility relationship in private inheritance a tabular form. in access accessible fromaccessible from accessible from specifier own class derived class outside Private yes no no protected yes yes no public yes yes no Table: Accessibility relationship in private inheritance

23

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

The following table shows a relationship in private inheri

24

Programming in C++

base class member visibility Private Protected


06/09/11 2006 IBM Corporation

Learning & Knowledge

Constructors In Inheritance
In inheritance the base-class default constructor is called every time when we invoke a derived class constructor in order to create an object of the derived class. As a result, the derived class constructors may be redoing some of the things done by the base-class default constructor. In order to avoid this repetition of the same job,the derived class constructors should invoke corresponding base class constructors.

25

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

What is inherited from the base class ?

In principle, a derived class inherits every member of a base class except: its constructor and its destructor its operator=() members its friends

Although the constructors and destructors of the base class are not inherited themselves, its default constructor (i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.

26

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Derived-class default constructor should invoke base-class default constructor. For derived-class default constructor, the function definition heading should become derived_class :: derived_class(): base_class() { --------------------}

27

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Derived constructor with a constructor with the same relevant parameters into i

The derived constructor sho

28

Programming in C++

derived_class :: derived_cla : base_class (x1,..,xi)


06/09/11 2006 IBM Corporation

Learning & Knowledge

Example of Constructors and Destructors invocation


// constructors and derived classes #include <iostream> using namespace std; class son : public mother { public: son (int a) : mother (a) { cout << "son: int parameter\n\n"; } };

class mother { public: mother () { cout << "mother: no parameters\n"; } mother (int a) { cout << "mother: int parameter\n"; } };

int main () { daughter cynthia (0); son daniel(0); return 0; } Output : mother: no parameters daughter: int parameter

class daughter : public mother { public: daughter (int a) { cout << "daughter: int parameter\n\n"; } };
29 Programming in C++

mother: int parameter son: int parameter


06/09/11 2006 IBM Corporation

Learning & Knowledge

Destructors In Inheritance
It is not necessary to define a destructor in the derived class unless there is some special task to be performed. When a derived-class object goes out of scope, the derived class destructor is called first and then the base class destructor.

30

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Me
31 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Overriding the Baseclass method

32

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Multiple Inheritance
In multiple inheritance a new class is derived from more than one base classes. the derived class definition begins like class employ : public person, public array { --------} The base classes are listed after the colon (:) separated by comas.
33 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Example of Multiple Inheritance


class CRectangle: public CPolygon, public COutput { public: #include <iostream> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; }
34 Programming in C++

int area () { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area () { return (width * height / 2); } }; void main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5);

cout<<"The area of the rectangle is : "<<endl; rect.output (rect.area()); cout<<"The area of the triangle is : "<<endl; trgl.output (trgl.area());
06/09/11 2006 IBM Corporation

Learning & Knowledge

Virtual Base Class


How can we avoid duplication elements passed to
derived class when multiple inheritance is involved. stdinfo studmarks

Langmarks

totmarks

35

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Virtual Base Class


Class stdinfo is inherited by two classes namely langmarks
and submarks. The class totmark then inherits from classes langmarks and submarks.

In this process both multiple and multilevel inheritance are


introduced.

Now the totmarks has two base classes and these two base
classes have a common base class stdinfo

Totmarks has duplication of inherited members. How


should these duplication be eliminated ?

36

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Virtual Base Class


The confusion created by multiple inheritance
from the same class can be avoided by using virtual base class.

A virtual base class causes a program to have


only one copy of that class into a derived class.

We can make a virtual base class just by adding


the keyword virtual when declaring the base class in a class definition.

37

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Example of Virtual Base Class


class stdinfo { /* ... */ }; // indirect base class class langmarks : virtual public stdinfo { /* ... */ }; class studmarks : virtual public stdinfo { /* ... */ }; class totmarks : public langmarks, public studmarks { /* ... */ }; // valid

38

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Ambiguous base classes


When you derive classes, ambiguities can result if base and
derived classes have members with the same names.

Access to a base class member is ambiguous if you use a name or


qualified name that does not refer to a unique function or object. class is not an error. The ambiguity is only flagged as an error if you use the ambiguous member name.

The declaration of a member with an ambiguous name in a derived For example, suppose that two classes named A and B both have a
member named x, and a class named C inherits from both A and B. An attempt to access x from class C would be ambiguous. name using the scope resolution (::) operator.

You can resolve ambiguity by qualifying a member with its class

39

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Ambigious base class


class B1 { public: int i; int j; void g(int) { } }; int main() { D dobj; D *dptr = &dobj; dptr->i = 5; // dptr->j = 10; //ambigious error dptr->B1::j = 10; class B2 { public: int j; void g() { } }; } // dobj.g(); dobj.B2::g();

class D : public B1, public B2 { public: int i; };


40 Programming in C++ 06/09/11 2006 IBM Corporation

Learning and Knowledge

Polymorphism

2006 IBM Corporation

Learning & Knowledge

Polymorphism
Polymorphism triggers different reactions in
objects in response to the same message.

42

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Binding
Binding : It is the process of resolving a function call during
the execution time or compile time.

OR

Binding is the process of associating a function to a class


through the class's object or pointer (i.e resolving the function identity ) is called Binding Person p1; P1.acceptdetails()

43

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Types of Binding
Static or Early Binding Dynamic or late Binding

44

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Static Binding
Binding that happens during compile time is called Static
Binding.

Eg :
main() { Person p1; P1.acceptdetails(); //binding happens during compile time }

45

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Dynamic or Late Binding


Binding that happens during runtime is called Dynamic
Binding.

Eg :
main() { Person *p1; P1=new person; P1->acceptdetails(); //binding happens during run time }

46

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Normal member functions accessed with pointers


class Base { public: void Base_Message() { cout<<"This is Base Class \n"; } };//end of Base class class Derived : public Base { public: void Derived_Message() { cout<<"This is Derived Class \n"; } }; //end of derived class

void main() { Base *baseptr=new Base; Derived *derivedptr=new Derived; baseptr->Base_Message(); derivedptr->Derived_Message(); }

Output : This is Base Class This is Derived Class

47

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Special Case
When the Base and derived class use the same
name to one of their member functions, and a pointer to the Base class is used to invoke the member functions of both the base and derived classes

48

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Example :
class Base { public: void show_Message() { cout<<"This is Base Class \n"; } };//end of Base class class Derived : public Base { public: void show_Message() { cout<<"This is Derived Class \n"; } };
49

void main() { Base *baseptr=new Base; baseptr->show_Message(); //make the baseptr point to derived class object baseptr=new Derived; baseptr->show_Message(); }

Output : This is Base Class This is Base Class

//end of derived class


Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

In situations where one or more derived classes


have a function with the same name and one of these functions is invoked, the identity of the function needs to be resolved.

The compiler associates the member function with


a class by identifying the type of the object or type of the pointer that is used to invoke the member function

50

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

How to implement Dynamic Binding


Dynamic Binding is implemented by the use of
Virtual Functions.

51

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Virtual Functions
When the Base class and the Derived class use
the same name to their member functions to resolve the identity of these functions (To ensure Late Binding) these functions are to be declared (with in the classes) preceded by the keyword 'Virtual' and they are called 'Virtual Functions'

52

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Example :
class Base { public: virtual void show_Message() { cout<<"This is Base Class \n"; } };//end of Base class class Derived : public Base { public: virtual void show_Message() { cout<<"This is Derived Class \n"; } };
53

void main() { Base *baseptr=new Base; baseptr->show_Message(); //make the baseptr point to derived class object baseptr=new Derived; baseptr->show_Message(); }

Output : This is Base Class This is Derived Class

//end of derived class


Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

Rules for virtual functions

1. Virtual functions must have identical declarations in the Base and Derived
classes

2. Virtual functions cannot be used as Friend Functions 3. Virtual functions cannot be static 4. A Virtual function in a Base class must be defined, even though it is not
used.

5. Constructors cannot be declared as virtual. 6. Destructors can be declared as virtual.

54

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Polymorphism

Static
( Compile Time )

Dynamic
( Run-time )

Operator Overloading

Function Overloading
55

Method Overriding

Virtual Functions

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Pure Virtual Functions

A Virtual Function with no body is called as Pure


Virtual Function

This is done by adding the notation "=0" to the


virtual function declaration eg Virtual void show_Message() = 0;

56

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Polymorphic class
The class which contains atleast one of more
virtual functions / pure virtual functions is called 'polymorphic class'.

57

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Abstract Base Class


The class containing one or more pure virtual functions
is called an 'Abstract Base Class'

An Abstract class can only be used as a Base class for


deriving sub classes.

instances(objects) of Abstract classes CANNOT be


created

58

Programming in C++

06/09/11

2006 IBM Corporation

Vehicle

Flyer

Learning and Knowledge

Streams

2006 IBM Corporation

Learning & Knowledge

Stream Classes
Ios is the base class Istream and ostream class derived from ios class and are
dedicated for input and output

Istream class contains functions like


Get(), getline(), read, and overloaded insertion (<<)

Ostream class contains function like


Put(),write, and overloaded extraction(>>)

Iostream is derived from both istream and ostream classes,


by multipleinheritance

62

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Character reading and Writing


#include <stdafx.h> #include <iostream.h> #include <fstream.h> int main() { ofstream outfile("c:\\test2.txt"); outfile<<"String Handling \n"; outfile<<"working on files \n"; outfile<<"testing the streams \n"; outfile.close (); return 0; } #include <stdafx.h> #include <iostream.h> #include <fstream.h> int main() { //reading from the file const int MAX=80; char buffer[MAX]; ifstream infile("c:\\test2.txt"); while(infile) { infile.getline(buffer,MAX); cout<<buffer<<endl; } }

63

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Writing characters to a file


Writing the characters to a file

#include <stdafx.h> #include <iostream.h> #include <fstream.h> //Write to the file int main() { const int MAX=80; char buffer[MAX]; ifstream infile("c:\\test2.txt"); while(infile) { infile.getline(buffer,MAX); cout<<buffer<<endl; } }

64

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Reading and Writing to a file using get and put


#include <stdafx.h>
#include <stdafx.h> #include <iostream.h> #include <fstream.h> #include <string.h> int main() { ofstream outfile("c:\\test3.txt"); //char str[]="Time is a great teacher"; char s[30]; cout<<"Enter a value : "; cin.getline (s,30); for (int j=0;j<strlen(s);j++) { outfile.put(s[j]); } outfile.close (); return 0; }

#include <iostream.h> #include <fstream.h> #include <string.h> int main() { ofstream outfile("c:\\test3.txt"); //reading from a file char ch; ifstream infile("c:\\test3.txt"); cout<<"The contents of the file are :"<<endl; while(infile) { infile.get(ch); cout<<ch; } return 0; }

65

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Writing to an object
#include "stdafx.h" #include <fstream.h> class person { protected : char name[40]; int age; public: void getdata() { cout<<"Enter name : "; cin>>name; cout<<"enter age : "; cin >>age; } }; int main() { person p1; p1.getdata (); ofstream outfile("c:\\person.dat"); outfile.write ((char *)&p1,sizeof(p1)); }

66

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Reading from an Object


#include "stdafx.h" #include <fstream.h> class person { protected : char name[40]; int age; public: void showdata() { cout<<"\n Name : "<<name; cout<<"\n Age : "<<age<<endl; } }; int main() { person p1; ifstream infile("c:\\person.dat"); infile.read ((char *)&p1,sizeof(p1)); p1.showdata (); return 0; }

67

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Reading and Writing from an object


#include "stdafx.h" #include <fstream.h> class person { protected : int age; public: void getdata() { cout<<"Enter name : "; cin>>name; cout<<"enter age : "; } void showdata() { cout<<"\n Name : "<<name; cout<<"\n Age : "<<age<<endl; } }; void main() { person p1; fstream file; file.open("c:\\person.dat",ios::app|ios::out|ios::in); cin >>age; char name[40];

char ch; do { cout<<"Enter person's data : "<<endl; p1.getdata (); file.write ((char *)&p1,sizeof(p1)); cout<<"Enter another person(Y/N)"; cin>>ch; //to get the no. of records file.seekg(0,ios::end); int pos=file.tellg (); int reccount=pos/sizeof(p1); cout<<"The total no. of records are : "<<reccount; file.seekg (0); //reset to start the file file.read((char *)&p1,sizeof(p1)); while(!file.eof()) { cout<<"\n person:"; p1.showdata (); file.read((char *)&p1,sizeof(p1)); } }while(ch=='y');

68

Programming in C++

06/09/11

2006 IBM Corporation

Learning and Knowledge

Operator Overloading

2006 IBM Corporation

Learning & Knowledge

Operator Overloading
Operator Overloading refers to giving additional
meaning to the normal C++ operators when they are applied to the user-defined datatypes

The overloaded operator is defined as a function


inside a class.

The function for the overloaded operator is


declared using the keyword 'Operator'

70

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Syntax for Operator Overloading


For Eg: if the + operator is overloaded in the fps_distance class the declaration for the operator fucntion is as
follows:

int fps_distance :: operator + (fps_distance);

Return value

Class name

Keyword

Operator to be overloaded

71

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Syntax for operator overloading


General form of an operator overloading function
is
return type class-name::operator operator_to_overload(arg list) { } Example : void sample::operator ++() { }

72

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Function overloading
C++ allows you to use the same name for different
functions. As long as they have different parameter type lists, the compiler will regards them as different functions.

Eg : int max(int, int);


int max(int, int, int); double max(double, double); Refer FunctionOverloading.cpp

73

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Why Operator Overloading ?


The Operator + is used to add integer or float.
We cannot use this operator to add two objects.

For example we need to add 2 time objects and


return the sum of the same to the user.

This cannot be done the + operator, we need to


use the user defined function to perform this type of calculation

74

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Operator Overloading
Operator overloading enable us to apply standard
operators such as +, -, *, < and many more, to objects of our own data types.

We need to write a function that redefines a


particular operator so that it performs a particular action every time it is applied to objects of our class.

An operator overloading function is created using


the keyword operator.

75

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

c++ operators that can be overloaded are


+ - * / % ^ | ~ !

== < > += -= *= /= %= ^= &= != << >> >>= == <= >= && || ++ -- []

() new delete

76

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Operators which cannot be overloaded


:: scope resolution operator Sizeof operator ?: conditional operator .* de-reference pointer to class member operator . Direct member operator

77

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Classification of Operator Overloading


Unary Operator Overloading : There should be no arguments for
unary operator overloading.

Eg : i ++, j ++, -- are unary operators


Binary Operator Overloading : There should be one parameter for
binary operator overloading.

Eg : i + j mn m*n Where +, -, * are called binary operators

78

Programming in C++

06/09/11

2006 IBM Corporation

Learning & Knowledge

Overloading of Binary Operator +


class fps { private : int feet; float inch; public : fps(int=0, float=0.0); fps operator+(fps &k) { feet+= k.feet; inch+=k.inch; while(inch>12.0) { inch=inch - 12; feet++; return *this; } void print() { } };
79 Programming in C++ 06/09/11 2006 IBM Corporation

fps::fps(int f=0,float i=0.0) { feet=f; inch=i; } void fps::print() { cout<<"Feet="<<feet; cout<<"Inch="<<inch; } void main() { fps obj1(11,11); fps obj2(10,10); fps obj3; obj3=obj1 + obj2; obj3.print(); }

Learning & Knowledge

Overloading of Unary Operator ++


class fps { private : int feet; float inch; public : fps(int=0, float=0.0); void operator++() { feet+= 1; inch+= 1; if(inch>=12.0) { inch-=12; feet++; } void print() { } };
80 Programming in C++ 06/09/11 2006 IBM Corporation

fps::fps(int f=0,float i=0.0) { feet=f; inch=i; } void fps::print() { cout<<"Feet="<<feet; cout<<"Inch="<<inch; } void main() { fps obj1(11,11); ++Obj1; obj3.print(); }

Learning & Knowledge

Example of Post incrementing


fps operator++(int) { fps temp; temp.feet = feet++; temp.inch=inch++; if(inch >= 12.0) { inch-=12; feet+=1; } return temp; }

void main() { fps obj1(10,10); fps obj2; obj2=obj1++; }

while overloading the unary operators ++ and -- to distinguish between prefixing and postfixing a dummy parameter is used in case of ostfixing
81 Programming in C++ 06/09/11 2006 IBM Corporation

Learning & Knowledge

References
Programming With C++ - Schaum Series John
Hubbar

Programming in C++ - Radha Ganesh www.Codeguru.com www.cplusplus.com

82

Programming in C++

06/09/11

2006 IBM Corporation

Das könnte Ihnen auch gefallen