Download presentation
Presentation is loading. Please wait.
1
Object Oriented Programming With C++
CHAPTER : 2 Classes and Objects
2
Object Oriented Programming With C++
Contents Object Oriented Programming With C++ CHAPTER : 2 Class Specification Class Objects Scope Resolution operator Access members Defining Member functions Data hiding Constructors and Destructors Types of Constructors Static data members Friend Functions Passing and returning objects Array of objects Dynamic objects Pointers to objects Generic functions and classes Operator overloading using friend functions such as +,-,pre-increment, post-increment, [],etc. overloading <<,>>
3
Object Oriented Programming With C++
CHAPTER : 2 Why Classes??? C Structures revisited.. C language structures provide a method for packing together data of different types. A structure is a convenient tool for handling a group of logically related data items. Struct student { char name[20]; int rollnumber; float total_marks; };
4
Object Oriented Programming With C++
CHAPTER : 2 Why Classes??? The keyword struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. The identifier student, which is referred to as structure name or structure tag, can be used to create variables of type student. Ex: structure student A; // C declaration. Member variables can be accessed through dot or period operator as follows:
5
Object Oriented Programming With C++
CHAPTER : 2 Why Classes??? Limitations of C structures The standard c does not allow struct data type to be treated like built-in types. Structure members can be easily assigned values using the dot operator, but cannot add two structure members or subtract two structure members. Another important limitation of c structures is that they do not permit data hiding, i.e. they can be accessed directly by structure variables by any function anywhere in the program.
6
Object Oriented Programming With C++
CHAPTER : 2 Why Classes??? C++ supports all the features of structure defined in C, but C++ has expanded its capability further to suit its OOP philosophy. In C++ structure can have both variables and functions as members. It can also declare some of its members as private so that they can be accessed directly by external functions. C++ incorporates all these functionalities and extensions of structures in a new user-defined data type called “class”
7
Object Oriented Programming With C++
CHAPTER : 2 Introduction- Class Defines the nature of an object. Keyword class. Defines a new type that links code and data. A class is a logical abstraction, but an object has physical existence. An object is an instance of a class.
8
Object Oriented Programming With C++
CHAPTER : 2 Introduction- Class A class is a way to bind the data and its associated functions together. It allows data and functions to be hidden, if necessary from external use. Class is a abstract data type that can be treated like a built-in type
9
Object Oriented Programming With C++
CHAPTER : 2 Introduction- Class A class consists of two parts Class declaration and class function definitions The class declaration describes the type and scope of its members. The class function definitions describes how the class functions are implement. The class declaration is similar to structure declaration.
10
Object Oriented Programming With C++
CHAPTER :2 Syntax class class-name { private data and functions access-specifier: data and functions // ... } object-list; The access specifiers are private, public and protected.
11
Object Oriented Programming With C++
CHAPTER : 2 Access Specifiers Public : allows functions or data to be accessible to other parts of your program. Private (default): allows functions or data to be accessible only within the class. Protected: is needed only when inheritance is involved. Functions that are declared within a class are called member functions. Member functions may access any element of the class of which they are a part. This includes all private elements. Variables that are elements of a class are called member variables or data members.
12
Object Oriented Programming With C++
CHAPTER : 2 Example class Student { int usn; public: void setUsn(int usn); int getUsn(); private: char *name; void setName(char* name); char* getName(); };
13
Object Oriented Programming With C++
CHAPTER : 2 The class body contains declarations of variables and functions and these are called members. The variables declared inside the class are called data members and functions declared inside the function are called member functions. By default members of class are private.
14
Restrictions for a member
Object Oriented Programming With C++ CHAPTER : 2 Restrictions for a member A non-static member variable cannot have an initializer. No member can be an object of the class that is being declared. No member can be declared as auto, extern, or register. You should make all data members of a class private to that class.
15
Scope resolution operator
Object Oriented Programming With C++ CHAPTER : 2 Scope resolution operator The :: operator links a class name with a member name in order to tell the compiler what class the member belongs to. Example: class Demo { int i; public: void setI(); }; void Demo::setI() { i = 10;}
16
Scope Resolution operator
Object Oriented Programming With C++ CHAPTER : 2 Scope Resolution operator it can allow access to a name in an enclosing scope that is "hidden" by a local declaration of the same name. Example: int i; // global i void f() { int i; // local i ::i = 10; // now refers to global i . . . }
17
A simple program on class
Object Oriented Programming With C++ CHAPTER : 2 A simple program on class #include <iostream.h> void item::getdata(int a, float b) Class item { { int number; // private by default number=a; float cost; // private by default cost=b; public: } void getdata(int a,float b); void main() void putdata(void) { { item x; cout <<“number: “<<number <<“\n”; cout<<“\n object x”<<“\n”; cout <<“cost:”<<cost<<“\n”; x.getdata(100,299.95); } x.putdata(); }; item y; cout<<“\n object y”<<“\n”; y.getdata(200,99.95); y.putdata(); }
18
Object Oriented Programming With C++
CHAPTER : 2 Nested Classes Possible to define a class within a class. Nested class is valid only within the scope of the enclosing class. Nested class are rarely used.
19
Object Oriented Programming With C++
CHAPTER : 2 Local Classes void f() { class myclass { int i; public: void put_i(int n) { i=n; } int get_i() { return i; } } ob; ob.put_i(10); cout << ob.get_i(); } #include <iostream> using namespace std; void f(); int main() { f(); // myclass not known here return 0; } Restrictions of local class: all member functions must be defined within the class declaration. The local class may not use or access local variables of the function in which it is declared. No static variables may be declared inside a local class.
20
Object Oriented Programming With C++
CHAPTER : 2 Friend Functions You can grant a nonmember function access to the private members of a class by using a friend. A friend function has access to all private and protected members of the class for which it is a friend. Keyword friend.
21
Object Oriented Programming With C++
CHAPTER : 2 Friend Functions #include <iostream> using namespace std; class myclass { int a, b; public: friend int sum(myclass x); void set_ab(int i, int j); }; void myclass::set_ab(int i, int j) { a = i; b = j; } int sum(myclass x) { return x.a + x.b; } int main() myclass n; n.set_ab(3, 4); cout << sum(n); return 0; 1. Friends can be useful when you are overloading certain types of operators. 2. friend functions make the creation of some types of I/O functions easier. 3. two or more classes may contain members that are interrelated relative to other parts of your program.
22
Object Oriented Programming With C++
CHAPTER : 2 Friend Classes It is possible for one class to be a friend of another class. The friend class and all of its member functions have access to the private members defined within the other class.
23
Object Oriented Programming With C++
CHAPTER : 2 Friend Classes #include <iostream> using namespace std; class TwoValues { int a; int b; public: void init(int i, int j) { a = i; b = j; } friend class Min; }; class Min { int min(TwoValues x); int Min::min(TwoValues x) { return x.a < x.b ? x.a : x.b; } int main() TwoValues ob; ob.init(10,20); Min m; cout << m.min(ob); return 0; It is critical to understand that when one class is a friend of another, it only has access to names defined within the other class. It does not inherit the other class.
24
Object Oriented Programming With C++
CHAPTER : 2 Write a class STACK which does push and pop operations. stack int tos; int stck[SIZE]; public: init(); push(ele); pop(); Stack
25
Constructors and Destructors
Object Oriented Programming With C++ CHAPTER : 2 Constructors and Destructors A constructor is a special function that is a member of a class and has the same name as that class. class stack { int stck[SIZE]; int tos; public: stack(); // constructor void push(int i); int pop(); }; // stack's constructor stack::stack() { tos = 0; } . Constructors are specially used to initialize the values of the data members without using a member function. . In C++, constructors cannot return values and, thus, have no return type.
26
Constructors and Destructors
Object Oriented Programming With C++ CHAPTER : 2 Constructors and Destructors An object’s constructor is automatically called when an object is created. An object's constructor is called once for global or static local objects.
27
Constructors and Destructors
Object Oriented Programming With C++ CHAPTER : 2 Constructors and Destructors The complement of the constructor is the destructor. When an object is destroyed, its destructor (if it has one) is automatically called. In C++, it is the destructor that handles deactivation events. The destructor has the same name as the constructor, but it is preceded by a ~ (tilde). Local objects are created when their block is entered, and destroyed when the block is left. Global objects are destroyed when the program terminates. reasons why a destructor may be needed: an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened. In C++, it is the destructor that handles deactivation events.
28
Constructors and Destructors
Object Oriented Programming With C++ CHAPTER : 2 Constructors and Destructors // This creates the class stack. class stack { int stck[SIZE]; int tos; public: stack(); // constructor ~stack(); // destructor void push(int i); int pop(); }; // stack's constructor stack::stack() { tos = 0; cout << "Stack Initialized\n"; } // stack's destructor stack::~stack() cout << "Stack Destroyed\n"; like constructors, destructors do not have return values.
29
Object Oriented Programming With C++
CHAPTER : 2 Types of Constructors Default Constructors Parameterized Constructors Copy Constructors
30
Object Oriented Programming With C++
CHAPTER : 2 Default Constructors A constructor that accepts no arguments is called as default constructor. When you create an object : A a; a default constructor is invoked
31
Object Oriented Programming With C++
CHAPTER : 2 Default Constructors Special Characteristics: They should be declared in public section. Invoked automatically when an object is created. No return type, not even void. They can have default arguments. Constructors can not be virtual. We can not refer to their address. When a constructor is declared for a class, initialization becomes mandatory.
32
Parameterized Constructors
Object Oriented Programming With C++ CHAPTER : 2 Parameterized Constructors #include <iostream> using namespace std; class myclass { int a, b; public: myclass(int i, int j) {a=i; b=j;} void show() {cout << a << " " << b;} }; int main() { myclass ob(3, 5); ob.show(); return 0; } It is possible to pass arguments to constructors. These arguments help initialize an object when it is created. When you define the constructor's body, use the parameters to initialize the object. myclass ob = myclass(3, 4);
33
Parameterized Constructors
Object Oriented Programming With C++ CHAPTER : 2 Parameterized Constructors Implicit : Integer ob(4,5); Explicit: Integer ob = ob(4,5); The parameters of the constructor can be of any type except that of the class to which it belongs. But can accept reference to its own class.
34
Multiple Constructors in a class
Object Oriented Programming With C++ CHAPTER : 2 Multiple Constructors in a class class Integer { int a,b; public: Integer() { a=0;b=0;} Integer(int x,int y) {a=x;b=y;} Integer(Integer &i) { a = i.a; b=i.b; } //Copy Constructor }
35
Constructor can have default arguments
Object Oriented Programming With C++ CHAPTER : 2 Constructor can have default arguments 1. Integer (int a, int b=10); 2. main() { Integer ob(20); }
36
Object Oriented Programming With C++
CHAPTER : 2 Copy Constructor Copy constructor is used to declare and initialize an object from another object. Integer i2(i1); Integer i2 = i1;
37
Constructors with One Parameter: A Special Case
Object Oriented Programming With C++ CHAPTER : 2 Constructors with One Parameter: A Special Case #include <iostream> using namespace std; class X { int a; public: X(int j) { a = j; } int geta() { return a; } }; int main() { X ob = 99; // passes 99 to j cout << ob.geta(); // outputs 99 return 0; }
38
Object Oriented Programming With C++
CHAPTER : 2 Static Class Members Static Data Members Static Member Functions Class Static member ob1 ob2 ob3 ob4 Obn . . .
39
Object Oriented Programming With C++
CHAPTER : 2 Static Data Member Only one copy is created for all objects of that class. All static variables are initialized to zero before the first object is created. Visible only within the class. When you declare a static data member within a class, you are not defining it. You must provide a global definition for it elsewhere, outside the class. Also known as Class Variables. Example: execute That is, you are not allocating storage for a static member when declared in a class.
40
Object Oriented Programming With C++
CHAPTER : 2 Static Data Member A static member variable exists before any object of its class is created. Uses: a static member variable is to provide access control to some shared resource used by all objects of a class. a static member variable is to keep track of the number of objects of a particular class type that are in existence As a convenience, older versions of C++ did not require the second declaration of a static member variable. However, this convenience gave rise to serious inconsistencies and it was eliminated several years ago. However, you may still find older C++ code that does not re declare static member variables. In these cases, you will need to add the required definitions.
41
Sharing a static Data Member
Object Oriented Programming With C++ CHAPTER : 2 Sharing a static Data Member number number number 200 100 300 As a convenience, older versions of C++ did not require the second declaration of a static member variable. However, this convenience gave rise to serious inconsistencies and it was eliminated several years ago. However, you may still find older C++ code that does not redeclare static member variables. In these cases, you will need to add the required definitions. 3 Count (common to all three objects
42
Static Member Functions
Object Oriented Programming With C++ CHAPTER : 2 Static Member Functions Restrictions: Static member functions can have access only to other static members. A static member function does not have a this pointer. There cannot be a static and a non-static version of the same function. A static member function may not be virtual. They cannot be declared as const or volatile.
43
Static Member Functions
Object Oriented Programming With C++ CHAPTER : 2 Static Member Functions #include<iostream> using namespace std; class StaticFunction { static int i; public: static void init(int x) { i = x; } void show() { cout<<i; } }; int StaticFunction :: i; int main() { StaticFunction :: init(10); StaticFunction obj; obj.show(); } *Calling static function before creating object
44
Object Oriented Programming With C++
CHAPTER : 2 #include <iostream> using namespace std; class demo { static int resource; public: static int get_resource(); void free_resource() { resource = 0; } }; int demo ::resource; // define resource int demo ::get_resource() { if(resource) return 0; // resource already in use else { resource = 1; return 1; // resource allocated to this object }
45
Object Oriented Programming With C++
CHAPTER : 2 int main() { demo ob1, ob2; /* get_resource() is static so may be called independent of any object. */ if(demo::get_resource()) cout << "ob1 has resource\n"; if(! demo::get_resource()) cout << "ob2 denied resource\n"; ob1.free_resource(); if(ob2.get_resource()) // can still call using object syntax cout << "ob2 can now use resource\n"; return 0; }
46
When Constructors and Destructors Are Executed
Object Oriented Programming With C++ CHAPTER : 2 When Constructors and Destructors Are Executed A local object's constructor is executed when the object's declaration statement is encountered. The destructors for local objects are executed in the reverse order of the constructor functions. Global objects have their constructors execute before main( ) begins execution. Global destructors execute in reverse order after main( ) has terminated. Program
47
Passing Objects to Functions
Object Oriented Programming With C++ CHAPTER : 2 Passing Objects to Functions standard call-by value mechanism. When a copy of an argument is made during a function call, a normal constructor is not called. Instead, the object’s copy constructor is called. If a class does not define a copy constructor, then C++ provides a default one. The copy constructor creates a bitwise copy of the object. Program Two questions arise: Is the object's constructor called when the copy is made? Is the object's destructor called when the copy is destroyed?
48
Returning Objects A function may return an object to the caller
Object Oriented Programming With C++ CHAPTER : 2 Returning Objects A function may return an object to the caller Program Object Assignment Assuming that both objects are of same type, you can assign One object to another Program
49
Object Oriented Programming With C++
CHAPTER : 2 Arrays of Objects In C++ it is possible to have array of objects. The syntax for declaring and using an object array is exactly the same as it is for any other array type PROGRAM1 PROGRAM2 PROGRAM3 If a class defines parameterized constructor, you may initialize each object in an array by specifying an initialization list, just like you do for other type of arrays. cl ob[3] = { cl(1), cl(2), cl(3) };
50
Object Oriented Programming With C++
CHAPTER : 2 Arrays of Objects Constructor c1 is invoked explicitly, the short form is used in common in most of the programs. Short form can only be used to initialize object arrays whose constructors require only one argument.
51
Creating Initialized vs. Uninitialized Arrays
Object Oriented Programming With C++ CHAPTER : 2 Creating Initialized vs. Uninitialized Arrays A special case situation occurs if you intend to create both initialized and uninitialized arrays of objects PROGRAM Constructor defined by c1 requires one parameter. This implies that any array declared this type must be initialized. For example c1 a[9] // error, since constructor require initializers. To solve this error, one need to overload constructor i.e. add one more constructor that takes no parameter. In this way arrays that are initialized and those uninitialized both are allowed
52
Object Oriented Programming With C++
CHAPTER : 2 Pointers to Objects Just as you can have pointers to other variables, you can have pointers to objects. When accessing members of a class given a pointer to an object use the arrow -> operator instead of dot operator. PROGRAM1 PROGRAM2 PROGRAM3
53
Object Oriented Programming With C++
CHAPTER : 2 The this pointer When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object.(i.e. object on which the function is called) Usually used when overloading operators. PROGRAM
54
Object Oriented Programming With C++
CHAPTER : 2 The this pointer Within a member function, the members of class can be accessed directly without any object or class qualification. Thus inside pwr() statement b=base means this->b=base, this pointer points to the object that is invoked by pwr() Thus this->b refers to that object’s copy of b. This pointer is automatically passed to all member functions.
55
Pointers to Class Members
Object Oriented Programming With C++ CHAPTER : 2 Pointers to Class Members "points" generically to a member of a class. Since member pointers are not true pointers, the . and –> cannot be applied to them. Special pointer-to-member operators .* and –>*. Pointers to class members are pointers to offset of member. PROGRAM1 PROGRAM2
56
Pointers to Class Members
Object Oriented Programming With C++ CHAPTER : 2 Pointers to Class Members int cl::*d; int *p; cl o; p = &o.val // this is address of a specific val d = &cl::val // this is offset of generic val
57
Object Oriented Programming With C++
CHAPTER : 2 Dynamic Objects Dynamic allocation operators: new and delete. Used to allocate and free memory at run time. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new. Heap memory is finite. If there is insufficient available memory to fill an allocation request, then new will fail and a bad_alloc exception will be generated. p_var = new type; delete p_var;
58
Object Oriented Programming With C++
CHAPTER : 2 Dynamic Objects C++ also supports dynamic memory location functions called malloc() and free() Allocated in heap. bad_alloc exception???? <new> header file defines above said exception PROGRAM
59
Object Oriented Programming With C++
CHAPTER : 2 Dynamic Objects Advantages of new and delete over malloc() and free new automatically allocates enough memory to hold an object of the specified type. new automatically returns a pointer of the specified type. new and delete can be overloaded. The delete operator must be used only with a valid pointer previously allocated by using new. You need not use a sizeOf() operator.
60
Object Oriented Programming With C++
CHAPTER : 2 Initializing Allocated Memory you can initialize allocated memory to some known value by putting initializer after type p_var = new var_type (initializer); the type of the initializer must be compatible with the type of data for which memory is being allocated. PROGRAM
61
Allocating Arrays You can allocate arrays using new operator
Object Oriented Programming With C++ CHAPTER : 2 Allocating Arrays You can allocate arrays using new operator p_var = new array_type [size]; To free an array use this form of delete delete [ ] p_var; PROGRAM you may not specify an initializer when allocating arrays
62
Object Oriented Programming With C++
CHAPTER : 2 Allocating Objects can allocate objects dynamically by using new. an object is created and a pointer is returned to it. The dynamically created object acts just like any other object. PROGRAM
63
Object Oriented Programming With C++
CHAPTER : 2 Allocating Objects dynamically allocated objects may have constructors and destructors. PROGRAM
64
Object Oriented Programming With C++
CHAPTER : 2 Placement form of new There is a special form of new called placement form, that can be used to specify an alternative method of allocating memory It is primarily useful when overloading new operator for special circumstances p_var=new(arg-list) type;
65
Generic Functions and Classes
Object Oriented Programming With C++ CHAPTER : 2 Generic Functions and Classes high-powered feature of OOPS. The type of data upon which the function or class operates is specified as a parameter. You can use one function or class with several different types of data.
66
Object Oriented Programming With C++
CHAPTER : 2 Generic Functions Defines a general set of operations that will be applied to various types of data. The type of data that the function will operate upon is passed to it as a parameter. A single general procedure can be applied to a wide range of data. Many algorithms are logically the same no matter what type of data is being operated upon. By creating a generic function, you can define the nature of the algorithm, independent of any data.
67
Object Oriented Programming With C++
CHAPTER : 2 Generic Functions keyword template. Template or framework. template <class Ttype> ret-type func-name(parameter list) { // body of function } Ttype is a placeholder name for a data type used by the function. compiler will automatically replace with an actual data type when it creates a specific version of the function.
68
Object Oriented Programming With C++
CHAPTER : 2 Generic Functions Program template <class X> void swapargs(X &a, X &b)
69
Object Oriented Programming With C++
CHAPTER : 2 Generic Functions Imp. Terms: template function Specialization or generated function instantiating
70
A Function with Two Generic Types
Object Oriented Programming With C++ CHAPTER : 2 A Function with Two Generic Types PROGRAM Explicitly Overloading a Generic Function When you create a template function, you are, in essence, allowing the compiler to generate as many different versions of that function as are necessary for handling the various ways that your program calls the function. PROGRAM
71
Overloading a Function Template
Object Oriented Programming With C++ CHAPTER : 2 Overloading a Function Template PROGRAM Using Standard Parameters with Template Functions PROGRAM
72
Generic Function Restrictions
Object Oriented Programming With C++ CHAPTER : 2 Generic Function Restrictions When functions are overloaded, you may have different actions performed within the body of each function. But a generic function must perform the same general action for all versions—only the type of data can differ.
73
Object Oriented Programming With C++
CHAPTER : 2 Generic Classes You create a class that defines all the algorithms used by that class. the actual type of the data being manipulated will be specified as a parameter when objects of that class are created. Generic classes are useful when a class uses logic that can be generalized.
74
Object Oriented Programming With C++
CHAPTER : 2 Generic Classes template <class Ttype> class class-name { ... } class-name <type> ob; PROGRAM
75
Object Oriented Programming With C++
CHAPTER : 2 Two Generic Data Types PROGRAM The typename and export Keywords
76
Object Oriented Programming With C++
CHAPTER : 2 The Power of Templates The creation of reusable code. You have a solid software component You are saved from the tedium of creating separate implementations for each data type.
77
Object Oriented Programming With C++
CHAPTER : 2 Operator Overloading You overload operators by creating operator functions. An operator function defines the operations that the overloaded operator will perform relative to the class upon which it will work. Keyword operator. Either members or nonmembers of a class. Nonmember operator functions are almost always friend functions.
78
Creating a Member Operator Function
Object Oriented Programming With C++ CHAPTER : 2 Creating a Member Operator Function ret-type class-name::operator#(arg-list) { // operations } # is a placeholder operator functions return an object of the class they operate on. They can even have any other valid type. unary operator, arg-list will be empty. binary operators, arg-list will contain one parameter
79
Object Oriented Programming With C++
CHAPTER : 2 Operator Overloading Program 1 – simple program Program 2 – multiple operators ob1 = ob1 + ob2; ob1 = ob1.+(ob2); (ob1+ob2).show();
80
Object Oriented Programming With C++
CHAPTER : 2 Operator Overloading Creating Prefix and Postfix Forms of the Increment and Decrement Operators- // Prefix increment type operator++( ) { // body of prefix operator } // Postfix increment type operator++(int x) { // body of postfix operator // Prefix decrement type operator– –( ) { // body of prefix operator } // Postfix decrement type operator– –(int x) { // body of postfix operator
81
Overloading the Shorthand Operators
Object Oriented Programming With C++ CHAPTER : 2 Overloading the Shorthand Operators loc loc::operator+=(loc op2) { longitude = op2.longitude + longitude; latitude = op2.latitude + latitude; return *this; }
82
Restrictions of Operator overloading
Object Oriented Programming With C++ CHAPTER : 2 Restrictions of Operator overloading . :: .* ? Can not be overloaded You cannot alter the precedence of an operator. You cannot change the number of operands that an operator takes. operator functions cannot have default arguments.
83
Operator Overloading Using a Friend Function
Object Oriented Programming With C++ CHAPTER : 2 Operator Overloading Using a Friend Function Operators can be overloaded using non member function, i.e. friend function. It does not have a this pointer. Therefore, an overloaded friend operator function is passed the operands explicitly. binary operator - has two parameters unary operator - has one parameter. PROGRAM
84
Using a Friend to Overload ++ or – –
Object Oriented Programming With C++ CHAPTER : 2 Using a Friend to Overload ++ or – – PROGRAM
85
Friend Operator Functions Add Flexibility
Object Oriented Programming With C++ CHAPTER : 2 Friend Operator Functions Add Flexibility ob + 100; //valid ob; //invalid PROGRAM
86
Overloading new and delete
Object Oriented Programming With C++ CHAPTER : 2 Overloading new and delete // Allocate an object. void *operator new(size_t size) { /* Perform allocation. Throw bad_alloc on failure. Constructor called automatically. */ return pointer_to_memory; } // Delete an object. void operator delete(void *p) { /* Free memory pointed to by p. Destructor called automatically. */ } size_t is a defined type capable of containing the largest single piece of memory that can be allocated. parameter size will contain the number of bytes needed to hold the object being allocated. new function must return a pointer to the memory that it allocates. The delete function receives a pointer to the region of memory to be freed.
87
Overloading new and delete
Object Oriented Programming With C++ CHAPTER : 2 Overloading new and delete PROGRAM 1 PROGRAM 2
88
Overloading new and delete for Arrays
Object Oriented Programming With C++ CHAPTER : 2 Overloading new and delete for Arrays // Allocate an array of objects. void *operator new[](size_t size) { /* Perform allocation. Throw bad_alloc on failure. Constructor for each element called automatically. */ return pointer_to_memory; } // Delete an array of objects. void operator delete[](void *p) { /* Free memory pointed to by p. Destructor for each element called automatically. */ } PROGRAM
89
Overloading Some Special Operators
Object Oriented Programming With C++ CHAPTER : 2 Overloading Some Special Operators Overloading [ ] cout << ob[1]; ob.operator[](1); We can even use the [] operator to the left and right side of the object. PROGRAM 1 This operator is overloaded specifically to check array boundary. PROGRAM 2
90
Overloading Some Special Operators
Object Oriented Programming With C++ CHAPTER : 2 Overloading Some Special Operators Overloading ( ) You can also specify default arguments. Overloading –> class member access operator object->element; must return a pointer to an object of the class
91
Overloading the Comma Operator
Object Oriented Programming With C++ CHAPTER : 2 Overloading the Comma Operator Overloading ,
92
Overloading stream operator
Object Oriented Programming With C++ CHAPTER : 2 Overloading stream operator << is an output stream operator. Ostream is a class and cout is object of that class. cout<<a; displays the value of variable a. By overloading << operator we can display the object directly with the following statement: MyClass ob; cout<<ob; PROGRAM Stream operators are binary operators.
93
Overloading stream operator
Object Oriented Programming With C++ CHAPTER : 2 Overloading stream operator Syntax is the same as any other binary operator: friend ostream & operator<< (ostream & out, MyClass &object) { out<<object.i<<object.j<<endl; return out; } In this case, There should be two parameters to be passed as the operator <<() function is a non member function. We pass ostream object as first parameter because cout is the first argument to be passed. We pass object of the class as second argument so that the information of the object is displayed. We are passing a reference of the objects because the intention is only to display the value(s) of the variable without modification. The variable will be modified, in order to keep the modification performed on the variable, you should pass it as reference. Since the function has two parameters it can not be part of the class. Therefore it should be declared outside the class. As this operator is a binary operator it works on two values and forms a third value, so this function should return a type ostream because it comes to the right side of the operator. Thus the function should return type ostream .
94
Overloading stream operator
Object Oriented Programming With C++ CHAPTER : 2 Overloading stream operator >> is an input stream operator. Istream is a class and cin is object of that class. PROGRAM friend istream & operator>> (istream & in, const MyClass &object) { in>>object.i<<object.j<<endl; return in; }
95
Object Oriented Programming With C++
CHAPTER : 2 Contd. Ob<<ob; PROGRAM Ob<<i; passing an integer value:- PROGRAM
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.