Chapter 03 Constructors and Destructors
Operator Overloading
return-type classname :: operator(op-arglist) { //function body }
We can’t overload these operators: 1.
Class member selection (. and .*)
2.
Scope resolution operator (::)
3.
Size of operator (sizeof)
4.
Conditional operator( : ? )
Object Oriented Programming (SYIF) 2008-2009 by Kute T. B.
-1-
Chapter 03 Constructors and Destructors
Process of defining overloaded operators: 1.
Create a class that defines the data type that is to be used in the overloading operation.
2.
Declare the operator function in the public part of the class. It may be either a member function or a friend function.
3.
Define the operator function to implement the required operations.
Object Oriented Programming (SYIF) 2008-2009 by Kute T. B.
-2-
Chapter 03 Constructors and Destructors
#include
class Space { int x,y; public: void get(int a, int b) { x = a; y = b; } void show() { cout<<"\n X = "<<x; cout<<"\n Y = "<
-3-
Chapter 03 Constructors and Destructors
#include class Index { int val; public: Index(){} Index(int z) { val = z; } void show() { cout<<"\n val = "<
-4-
Chapter 03 Constructors and Destructors
class Overload { int n1,n2,n3; public: Overload(){} Overload(int a,int b,int c) { n1 = a; n2 = b; n3 = c; } void show() { cout<<"\n n1 = "<
-5-
Chapter 03 Constructors and Destructors
class Complex { float x,y,z; public: Complex( ) { } Complex(float a, float b, float c) { x=a; y=b; z=c; } void display(char *s) { cout<<"\n"<<s; cout<<"\n X:"<<x; cout<<"\n Y:"<
-6-
Chapter 03 Constructors and Destructors
class Vector { int a[10]; public: Vector(){ } void inPut() { cout<<"Enter 10 values : "; for(int i=0;i<10;i++) cin>>a[i]; } void outPut() { cout<<"\nResultant array : "; for(int i=0;i<10;i++) cout<<"\n"<
-7-