Module 11
Partha Pratim
Das Module 11: Programming in C++
Objectives & Classes and Objects
Outline
Classes
Objects
Data Members
Partha Pratim Das
Complex
Rectangle
Stack
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Member
Functions
ppd@cse.iitkgp.ernet.in
Complex
Rectangle
Stack
this pointer Tanwi Mallick
Srijoni Majumdar
State of an
Object Himadri B G S Bhuyan
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 1
Module Objectives
Module 11
Partha Pratim Understand the concept of classes and objects in C++
Das
Objectives &
Outline
Classes
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 2
Module Outline
Module 11
Partha Pratim Classes
Das
Objects
Objectives &
Outline Data Members of a class
Classes
Member functions of a class
Objects
Data Members
this Pointer
Complex
Rectangle State of an Object
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 3
Module 11: Lecture 19
Module 11
Partha Pratim Classes
Das
Objects
Objectives &
Outline Data Members of a class
Classes
Member functions of a class
Objects
Data Members
this pointer
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Classes
Module 11 A class is an implementation of a type. It is the only way to
Partha Pratim implement User-defined Data Type (UDT)
Das
A class contains data members / attributes
Objectives &
Outline A class has operations / member functions / methods
Classes
A class defines a namespace
Objects
Data Members
Thus, classes offer data abstraction / encapsulation of
Complex Object Oriented Programming
Rectangle
Stack
Classes are similar to structures that aggregate data logically
Member
Functions A class is defined by class keyword
Complex
Rectangle
Stack Classes provide access specifiers for members to enforce data
this pointer hiding that separates implementation from interface
State of an private - accessible inside the definition of the class
Object
Complex public - accessible everywhere
Rectangle
Stack A class is a blue print for its instances (objects)
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Objects
Module 11 An object of a class is an instance created according to its
Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object comprises data members that specify its state
Classes A object supports member functions that specify its behavior
Objects
Data members of an object can be accesses by ”.” (dot)
Data Members
Complex operator on the object
Rectangle
Stack
Member functions are invoked by ”.” (dot) operator on the
Member
Functions object
Complex
Rectangle An implicit this pointer holds the address of an object. This
Stack
serves the identity of the object in C++
this pointer
State of an this pointer is implicitly passed to methods
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Program 11.01/02: Complex Numbers:
Attributes
Module 11 C Program C++ Program
Partha Pratim // File Name:Complex_object.c: // File Name:Complex_object_c++.cpp:
Das #include <stdio.h> #include <iostream>
using namespace std;
Objectives & typedef struct Complex { // struct class Complex { public: // class
Outline double re, im; // Data members double re, im; // Data members
} Complex; };
Classes
Objects int main() { int main() {
// Variable n1 declared, initialized // Object n1 declared, initialized
Data Members Complex n1 = {4.2, 5.3}; Complex n1 = {4.2, 5.3};
Complex printf("%d %d", n1.re, n1.im); // Use cout << n1.re << " " << n1.im; // Use
Rectangle return 0; return 0;
Stack } }
----- -----
Member 4.2 5.3 4.2 5.3
Functions
Complex
Rectangle • struct is a keyword in C for data aggregation • class is a new keyword in C+ for data aggre-
Stack gation
• The struct Complex is defined as composite • The class Complex is defined as composite
this pointer data type containing two double (re, im) data data type containing two double (re, im) data
members members
State of an
• struct Complex is a derived data type used to • class Complex is User-defined Data Type
Object
create Complex type variable n1 (UDT) used to create Complex type object n1
Complex
• Data members are accessed using ’.’ operator • Data members are accessed using ’.’ operator.
Rectangle
• struct only aggregates • class aggregates and helps to do more for
Stack
building a UDT
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Program 11.03/04: Points and Rectangles:
Attributes
C Program C++ Program
Module 11
// File Name:Rectangle_object.c: // File Name:Rectangle_object_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das using namespace std;
typedef struct { // struct Point class Point { public: // class Point
Objectives &
int x; int y; int x; int y; // Data members
Outline
} Point; };
Classes
typedef struct { // Rect uses Point class Rect { public: // Rect uses Point
Objects Point TL; // Top-Left Point TL; // Top-Left
Point BR; // Bottom-Right Point BR; // Bottom-Right
Data Members } Rect; };
Complex
Rectangle int main() { int main() {
Stack Rect r = {{0,2}, {5,7}}; Rect r = {{0,2}, {5,7}};
// r.TL <-- {0,2}; r.BR <-- {5,7} // r.TL <-- {0,2}; r.BR <-- {5,7}
Member
// r.TL.x <-- 0; r.TL.y <-- 2 // r.TL.x <-- 0; r.TL.y <-- 2
Functions
Complex // Members of structure r accessed // Rectangle Object r accessed
Rectangle
printf("[(%d %d) (%d %d)]", cout << "[(" << r.TL.x << " " << r.TL.y <<
Stack
r.TL.x, r.TL.y, r.BR.x, r.BR.y); ") (" << r.BR.x << " " << r.BR.y << ")]";
this pointer return 0; return 0;
} }
State of an ----- -----
Object [(0 2) (5 7)] [(0 2) (5 7)]
Complex
Rectangle
Stack • Data members of user-defined data types
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Program 11.05/06: Stacks:
Attributes
Module 11 C Program C++ Program
Partha Pratim // File Name:Stack_object.c: // File Name:Stack_object_c++.cpp:
Das #include <stdio.h> #include <iostream>
using namespace std;
Objectives & typedef struct Stack { // struct Stack class Stack { public: // class Stack
Outline char data [100]; char data [100];
int top; int top;
Classes
} Stack; };
Objects
// Codes for push, pop, top, empty // Codes for push, pop, top, empty
Data Members
Complex int main() { int main() {
Rectangle // Variable s declared // Object s declared
Stack Stack s; Stack s;
s.top = -1; s.top = -1;
Member
Functions // Using stack for solving problems // Using stack for solving problems
Complex
Rectangle return 0; return 0;
Stack } }
this pointer
State of an • Data members of mixed data types
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Classes
Module 11 A class is an implementation of a type. It is the only way to
Partha Pratim implement User-defined Data Type (UDT)
Das
A class contains data members / attributes.
Objectives &
Outline A class defines a namespace
Classes
Objects
Thus, classes offer data abstraction / encapsulation of
Object Oriented Programming
Data Members
Complex
Rectangle Classes are similar to structures that aggregate data logically
Stack
Member A class is a blue print for its instances (objects)
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Objects
Module 11 An object of a class is an instance created according to its
Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object comprises data members that specify its state
Classes Data members of an object can be accesses by ”.” (dot)
Objects operator on the object
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 11.07/08: Complex Numbers:
Methods
C Program C++ Program
Module 11
// File Name:Complex_func.c: // File Name:Complex_func_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das #include <math.h> #include <cmath>
using namespace std;
Objectives &
typedef struct Complex { class Complex { public:
Outline
double re, im; double re, im;
Classes } Complex;
// MEMBER FUNCTIONS / METHODS
Objects // Norm of Complex Number - global fn. // Norm of Complex Number - method
double norm(Complex c) { double norm() {
Data Members return sqrt(c.re*c.re + c.im*c.im); return sqrt(re*re + im*im);
Complex } }
Rectangle // Print number with Norm - global fn. // Print number with Norm - method
Stack void print(Complex c) { void print() {
printf("|%lf+j%lf| = ", c.re, c.im); cout << "|"<< re<< "+j"<< im<< "| = ";
Member
printf("%lf", norm(c)); // Call global cout << norm(); // Call method
Functions
} }
Complex }; // End of class Complex
Rectangle
int main() { Complex c = { 4.2, 5.3 }; int main() { Complex c = { 4.2, 5.3 };
Stack
this pointer // Call global fn. with ’c’ as param // Invoke method print of ’c’
print(c); c.print();
State of an
Object return 0; return 0;
Complex } }
Rectangle ----- -----
Stack |4.200000+j5.300000| = 6.762396 |4.2+j5.3| = 6.7624
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Program 11.09/10: Rectangles:
Methods
Module 11 Using struct Using class
Partha Pratim #include <iostream> #include <iostream>
Das using namespace std; using namespace std;
typedef struct { class Point { public:
Objectives & int x; int y; int x; int y;
Outline } Point; };
typedef struct { class Rect { public:
Classes
Point TL; // Top-Left Point TL; // Top-Left
Objects Point BR; // Bottom-Right Point BR; // Bottom-Right
} Rect;
Data Members
Complex // Global function // Method
Rectangle void computeArea(Rect r) { void computeArea() {
Stack cout << abs(r.TL.x - r.BR.x) * cout << abs(TL.x - BR.x) *
abs(r.BR.y - r.TL.y); abs(BR.y - TL.y);
Member } }
Functions };
Complex int main() { int main() {
Rectangle Rect r = { { 0, 2 }, { 5, 7 } }; Rect r = { { 0, 2 }, { 5, 7 } };
Stack
// Global fn. call // Method invocation
this pointer
computeArea(r); r.computeArea();
State of an
Object return 0; return 0;
Complex
} }
Rectangle
----- -----
Stack 25 25
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Program 11.11/12: Stacks:
Methods
Using struct Using class
Module 11
#include <iostream> #include <iostream>
Partha Pratim using namespace std; using namespace std;
Das
typedef struct Stack { class Stack { public:
char data_[100]; int top_; char data_[100]; int top_;
Objectives &
} Stack; // METHODS
Outline
bool empty(const Stack& s) bool empty() { return (top_ == -1); }
Classes { return (s.top_ == -1); }
char top(const Stack& s) char top() { return data_[top_]; }
Objects { return s.data_[s.top_]; }
void push(Stack& s, char x) void push(char x) { data_[++top_] = x; }
Data Members { s.data_[++(s.top_)] = x; }
Complex void pop(Stack& s) { --(s.top_); } void pop() { --top_; }
Rectangle };
Stack int main() { int main() {
Stack s; s.top_ = -1; Stack s; s.top_ = -1;
Member char str[10] = "ABCDE"; int i; char str[10] = "ABCDE"; int i;
Functions
Complex for (i = 0; i < 5; ++i) push(s, str[i]); for (i = 0; i < 5; ++i) s.push(str[i]);
Rectangle
Stack cout << "Reversed String: "; cout << "Reversed String: ";
this pointer while (!empty(s)) { while (!s.empty()) {
cout << top(s); pop(s); cout << s.top(); s.pop();
State of an } }
Object return 0; return 0;
Complex } }
Rectangle ----- -----
Stack Reversed String: EDCBA Reversed String: EDCBA
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Classes
Module 11 A class has operations / member functions / methods
Partha Pratim
Das A class defines a namespace
Objectives & Thus, classes offer data abstraction / encapsulation of
Outline Object Oriented Programming
Classes
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Objects
Module 11 An object of a class is an instance created according to its
Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object supports member functions that specify its behavior
Classes Member functions are invoked by ”.” (dot) operator on the
Objects object
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Program 11.13: this Pointer
Module 11 An implicit this pointer holds the address of an object
Partha Pratim
Das this pointer serves as the identity of the object in C++
Objectives & Type of this pointer for a class X object: X * const this;
Outline
this pointer is accessible only in methods
Classes
#include <iostream> using namespace std;
Objects
Data Members class X { public: int m1, m2;
void f(int k1, int k2) { // Sample Method
Complex
Rectangle
m1 = k1; // Implicit access w/o ’this’ pointer
Stack this->m2 = k2; // Explicit access w/ ’this’ pointer
cout << "Id = " << this << endl; // Identity (address) of the object
Member }
Functions };
Complex int main() {
Rectangle X a;
Stack a.f(2, 3);
cout << "Addr = " << &a << endl; // Address (identity) of the object
this pointer cout << "a.m1 = " << a.m1 << " a.m2 = " << a.m2 << endl;
return 0;
State of an
}
Object
-----
Complex
Id = 0024F918
Rectangle
Addr = 0024F918
Stack
a.m1 = 2 a.m2 = 3
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 17
this Pointer
Module 11 this pointer is implicitly passed to methods
In Source Code In Binary Code
Partha Pratim
Das class X { void f(int, int); ... } void X::f(X * const this, int, int);
Objectives &
Outline X a; a.f(2, 3); X::f(&a, 2, 3); // &a = this
Classes
Objects
Use of this pointer
Data Members Distinguish member from non-member
Complex class X { public: int m1, m2;
Rectangle void f(int k1, int k2) {
Stack m1 = k1; // this->m1 (member) is valid; this->k1 is invalid
this->m2 = k2; // m2 (member) is valid; this->k2 is invalid
Member
}
Functions
};
Complex
Rectangle Explicit Use
Stack // Link the object
this pointer class DoublyLinkedNode { public: DoublyLinkedNode *prev, *next; int data;
void append(DoublyLinkedNode *x) { next = x; x->prev = this; }
State of an }
Object ---
Complex // Return the object
Rectangle Complex& inc() { ++re; ++im; return *this; }
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 18
Module 11: End Lecture 19
Module 11
Partha Pratim Classes
Das
Objects
Objectives &
Outline Data Members of a class
Classes
Member functions of a class
Objects
Data Members
this pointer
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 19
Module 11: Lecture 20
Module 11
Partha Pratim State of an Object
Das
Notion
Objectives & Example: Rectangle
Outline
Example: Stack
Classes
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 20
State of an Object: Complex
Module 11
The state of an object is determined by the combined value of
all its data members. Consider class Complex:
Partha Pratim
Das class Complex { public:
double re_, im_; // ordered tuple of data members decide the state at any time
Objectives &
double get_re { return re_; }
Outline
void set_re(double re) { re_ = re; }
Classes double get_im { return im_; }
void set_im(double im) { im_ = im; }
Objects }
Data Members Complex c1 = {4.2, 5.3};
Complex // STATE 1 of c1 = {4.2, 5.3} // Denotes a tuple / sequence
Rectangle
Stack
A method may change the state:
Member
Functions Complex c = {4.2, 5.3};
Complex // STATE 1 of c = {4.2, 5.3}
Rectangle
Stack c.set_re(6.4);
this pointer // STATE 2 of c = {6.4, 5.3}
State of an c.get_re();
Object // STATE 2 of c = {6.4, 5.3} // No change of state
Complex
Rectangle c.set_im(7.8);
Stack // STATE 3 of c = {6.4, 7.8}
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 21
State of an Object: Rectangle
Module 11
Consider class Point and class Rect:
Partha Pratim Data members of Rect class: Point TL; Point BR; // Point class type object
Das Data members of Point class: int x; int y
Rectangle r = {{0, 5}, {5, 0}}; // Initialization
Objectives & // STATE 1 of r = {{0, 5}, {5, 0}}
Outline { r.TL.x = 0; r.TL.y = 5; r.BR.x = 5; r.BR.y = 0 }
Classes r.TL.y = 9;
// STATE 2 of r = {{0, 9}, {5, 0}}
Objects
Data Members r.computeArea();
// STATE 2 of r = {{0, 9}, {5, 0}} // No change in state
Complex
Rectangle
Stack Point p = {3, 4};
r.BR = p;
Member // STATE 3 of r = {{0, 9}, {3, 4}}
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 22
State of an Object: Stack
Module 11
Consider class Stack:
Partha Pratim Data members of Stack class: char data[5] and int top;
Das
Stack s;
// STATE 1 of s = {{?, ?, ?, ?, ?}, ?} // No data member is initialized
Objectives &
Outline s.top_ = -1;
// STATE 2 of s = {{?, ?, ?, ?, ?}, -1}
Classes
s.push(’b’);
Objects
// STATE 3 of s = {{’b’, ?, ?, ?, ?}, 0}
Data Members
s.push(’a’);
Complex
Rectangle
// STATE 4 of s = {{’b’, ’a’, ?, ?, ?}, 1}
Stack
s.empty();
Member // STATE 4 of s = {{’b’, ’a’, ?, ?, ?}, 1} // No change of state
Functions
Complex s.push(’t’);
Rectangle // STATE 5 of s = {{’b’, ’a’, ’t’, ?, ?}, 2}
Stack
s.top();
this pointer // STATE 5 of s = {{’b’, ’a’, ’t’, ?, ?}, 2} // No change of state
State of an
s.pop();
Object
// STATE 6 of s = {{’b’, ’a’, ’t’, ?, ?}, 1}
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 23
Module Summary
Module 11
Partha Pratim
We have covered the following:
Das
class Complex { public:
Objectives & double re_, im_;
Outline
Class double norm() { // Norm of Complex Number
Classes return sqrt(re_ * re_ + im_ * im_);
Objects }
};
Data Members
Attributes Complex::re_, Complex::re_im_
Complex
Rectangle
Stack Method double Complex::norm();
Member Object Complex c = {2.6, 3.9};
Functions
Complex c.re_ = 4.6;
Rectangle cout << c.im_;
Access
Stack
cout << c.norm;
this pointer
this Pointer double Complex::norm() { cout << this; return ... }
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 24
Instructor and TAs
Module 11
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor ppd@cse.iitkgp.ernet.in 9830030880
Outline Tanwi Mallick, TA tanwimallick@gmail.com 9674277774
Classes
Srijoni Majumdar, TA majumdarsrijoni@gmail.com 9674474267
Himadri B G S Bhuyan, TA himadribhuyan@gmail.com 9438911655
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 25