0% found this document useful (0 votes)
41 views

Module 12

This document discusses access specifiers and information hiding in C++ classes. It provides examples of classes with public and private data members and member functions. Specifically, it shows a Complex number class with public data and methods, and private data and public methods. It also shows implementations of a stack class using public data with a dynamic array and vector to illustrate how information hiding is important for efficient design and flexibility to change implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Module 12

This document discusses access specifiers and information hiding in C++ classes. It provides examples of classes with public and private data members and member functions. Specifically, it shows a Complex number class with public data and methods, and private data and public methods. It also shows implementations of a stack class using public data with a dynamic array and vector to illustrate how information hiding is important for efficient design and flexibility to change implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Module 12

Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 12: Programming in C++
Objectives & Access Specifiers
Outline

Access Specifiers
Examples

Information
Hiding
Intructors: Abir Das and Sourangshu Bhattacharya
Stack Example
Stack (public) Department of Computer Science and Engineering
Risky
Indian Institute of Technology, Kharagpur
Stack (private)
Safe {abir, sourangshu}@cse.iitkgp.ac.in
Interface and
Implementation

Get-Set Idiom
Slides taken from NPTEL course on Programming in Modern C++
Encapsulation

Class as a
by Prof. Partha Pratim Das
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 1
Module Objectives

Module 12

Intructors: Abir • Understand access specifiers in C++ classes to control the visibility of members
Das and
Sourangshu
Bhattacharya
• Learn to design with Information Hiding
Objectives &
Outline

Access Specifiers
Examples

Information
Hiding

Stack Example
Stack (public)
Risky
Stack (private)
Safe
Interface and
Implementation

Get-Set Idiom

Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 2
Module Outline

Module 12

Intructors: Abir
1 Access Specifiers
Das and
Sourangshu
Access Specifiers: Examples
Bhattacharya
2 Information Hiding
Objectives &
Outline
3 Information Hiding: Stack Example
Access Specifiers
Examples
Stack (public)
Information
Risky
Hiding
Stack (private)
Stack Example Safe
Stack (public)
Risky Interface and Implementation
Stack (private)
Safe 4 Get-Set Idiom
Interface and
Implementation

Get-Set Idiom
5 Encapsulation
Encapsulation 6 Class as a Data-type
Class as a
Data-type
7 Module Summary
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 3
Access Specifiers

Module 12

Intructors: Abir • Classes provide access specifiers for members (data as well as function) to enforce data
Das and
Sourangshu hiding that separates implementation from interface
Bhattacharya
◦ private — accessible inside the definition of the class
Objectives &
Outline ▷ member functions of the same class
Access Specifiers ◦ public — accessible everywhere
Examples

Information
▷ member functions of the same class
Hiding ▷ member function of a different class
Stack Example ▷ global functions
Stack (public)
Risky • The keywords public and private are the Access Specifiers
Stack (private)
Safe • Unless specified, the access of the members of a class is considered private
Interface and
Implementation
• A class may have multiple access specifier. The effect of one continues till the next is
Get-Set Idiom
encountered
Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 4
Program 12.01/02: Complex Number: Access Specification
Public data, Public method Private data, Public method
Module 12

Intructors: Abir
#include <iostream> #include <iostream>
Das and #include <cmath> #include <cmath>
Sourangshu using namespace std; using namespace std;
Bhattacharya
class Complex { public: double re, im; class Complex { private: double re, im;
public: public:
Objectives &
Outline
double norm() { return sqrt(re*re + im*im); } double norm() { return sqrt(re*re + im*im); }
}; };
Access Specifiers
void print(const Complex& t) { // Global fn. void print(const Complex& t) { // Global fn.
Examples
cout << t.re << "+j" << t.im << endl; cout << t.re << "+j" << t.im << endl;
Information // Complex::re / Complex::im: cannot access
Hiding // private member declared in class ’Complex’
Stack Example } }
Stack (public) int main() { Complex c = { 4.2, 5.3 }; // Okay int main() { Complex c = { 4.2, 5.3 }; // Error
Risky // ’initializing’: cannot convert from
Stack (private) // ’initializer-list’ to ’Complex’
Safe print(c); print(c);
Interface and
Implementation
cout << c.norm(); cout << c.norm();
} }
Get-Set Idiom

Encapsulation • public data can be accessed by any function • private data can be accessed only by methods
Class as a
• norm (method) can access (re, im) • norm (method) can access (re, im)
Data-type • print (global) can access (re, im) • print (global) cannot access (re, im)
• main (global) can access (re, im) & initialize • main (global) cannot access (re, im) to initialize
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 5
Information Hiding

Module 12

Intructors: Abir • The private part of a class (attributes and member functions) forms its
Das and
Sourangshu implementation because the class alone should be concerned with it and have the right
Bhattacharya
to change it
Objectives &
Outline • The public part of a class (attributes and member functions) constitutes its interface
Access Specifiers which is available to all others for using the class
Examples

Information
• Customarily, we put all attributes in private part and the member functions in public
Hiding part. This ensures:
Stack Example
Stack (public)
◦ The state of an object can be changed only through one of its member functions
Risky
(with the knowledge of the class)
Stack (private)
Safe ◦ The behavior of an object is accessible to others through the member functions
Interface and
Implementation
• This is known as Information Hiding
Get-Set Idiom

Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 6
Information Hiding

Module 12

Intructors: Abir • For the sake of efficiency in design, we at times, put attributes in public and / or
Das and
Sourangshu member functions in private. In such cases:
Bhattacharya
◦ The public attributes should not decide the state of an object, and
Objectives &
Outline
◦ The private member functions cannot be part of the behavior of an object
Access Specifiers We illustrate information hiding through two implementations of a stack
Examples

Information
Hiding

Stack Example
Stack (public)
Risky
Stack (private)
Safe
Interface and
Implementation

Get-Set Idiom

Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 7
Program 12.03/04: Stack: Implementations using public data

Module 12 Using dynamic array Using vector

Intructors: Abir #include <iostream> #include <iostream>


Das and #include <cstdlib> #include <vector>
Sourangshu
Bhattacharya using namespace std; using namespace std;
class Stack { public: char *data_; int top_; class Stack { public: vector<char> data_; int top_;
Objectives & public: int empty() { return (top_ == -1); } public: int empty() { return (top_ == -1); }
Outline void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
Access Specifiers
void pop() { --top_; } void pop() { --top_; }
Examples
char top() { return data_[top_]; } char top() { return data_[top_]; }
}; };
Information
Hiding
int main() { Stack s; char str[10] = "ABCDE"; int main() { Stack s; char str[10] = "ABCDE";
s.data_ = new char[100]; // Exposed Allocation s.data_.resize(100); // Exposed Sizing
Stack Example s.top_ = - 1; // Exposed Init s.top_ = -1; // Exposed Init
Stack (public)
Risky
for(int i = 0; i < 5; ++i) s.push(str[i]); for(int i = 0; i < 5; ++i) s.push(str[i]);
Stack (private)
Safe
// Outputs: EDCBA -- Reversed string // Outputs: EDCBA -- Reversed string
Interface and
while(!s.empty()) { cout << s.top(); s.pop(); } while(!s.empty()) { cout << s.top(); s.pop(); }
Implementation delete [] s.data_; // Exposed De-Allocation
Get-Set Idiom } }
Encapsulation

Class as a • public data reveals the internals of the stack (no information hiding)
Data-type • Spills data structure codes (Exposed Init / De-Init) into the application (main)
Module Summary
• To switch from array to vector or vice-versa the application needs to change
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 8
Program 12.03/04: Stack: Implementations using public data
Risky
Using dynamic array Using vector
Module 12

Intructors: Abir
#include <iostream> #include <iostream>
Das and #include <cstdlib> #include <vector>
Sourangshu using namespace std; using namespace std;
Bhattacharya
class Stack { public: char *data_; int top_; class Stack { public: vector<char> data_; int top_;
public: int empty() { return (top_ == -1); } public: int empty() { return (top_ == -1); }
Objectives &
Outline
void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
void pop() { --top_; } void pop() { --top_; }
Access Specifiers
char top() { return data_[top_]; } char top() { return data_[top_]; }
Examples
}; };
Information int main() { Stack s; char str[10] = "ABCDE"; int main() { Stack s; char str[10] = "ABCDE";
Hiding s.data_ = new char[100]; // Exposed Allocation s.data_.resize(100); // Exposed Sizing
Stack Example s.top_ = - 1; // Exposed Init s.top_ = -1; // Exposed Init
Stack (public)
Risky for(int i=0; i<5; ++i) s.push(str[i]); for(int i=0; i<5; ++i) s.push(str[i]);
Stack (private) s.top_ = 2; // STACK GETS INCONSISTENT s.top_ = 2; // STACK GETS INCONSISTENT
Safe // Outputs: CBA -- WRONG!!! // Outputs: CBA -- WRONG!!!
Interface and
Implementation
while (!s.empty()) { cout << s.top(); s.pop(); } while (!s.empty()) { cout << s.top(); s.pop(); }
delete [] s.data_; // Exposed De-Init
Get-Set Idiom
} }
Encapsulation

Class as a
Data-type
• Application may intentionally or inadvertently tamper the value of top – this corrupts the stack!
• s.top = 2; destroys consistency of the stack and causes wrong output
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 9
Program 12.05/06: Stack: Implementations using private data
Safe
Using dynamic array Using vector
Module 12

Intructors: Abir
#include <iostream> #include <iostream>
Das and #include <vector>
Sourangshu using namespace std; using namespace std;
Bhattacharya
class Stack { private: char *data_; int top_; class Stack { private: vector<char> data_; int top_;
public: // Initialization and De-Initialization public: // Initialization and De-Initialization
Objectives &
Outline
Stack(): data_(new char[100]), top_(-1) { } Stack(): top_(-1) { data_.resize(100); }
~Stack() { delete[] data_; } ~Stack() { };
Access Specifiers
// Stack LIFO Member Functions // Stack LIFO Member Functions
Examples
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Information void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
Hiding void pop() { --top_; } void pop() { --top_; }
Stack Example char top() { return data_[top_]; } char top() { return data_[top_]; }
Stack (public) }; };
Risky int main() { Stack s; char str[10] = "ABCDE"; int main() { Stack s; char str[10] = "ABCDE";
Stack (private) for (int i=0; i<5; ++i) s.push(str[i]); for (int i=0; i<5; ++i) s.push(str[i]);
Safe while (!s.empty()) { cout << s.top(); s.pop(); } while (!s.empty()) { cout << s.top(); s.pop(); }
Interface and
Implementation
} }
Get-Set Idiom

Encapsulation • private data hides the internals of the stack (information hiding)
• Data structure codes contained within itself with initialization and de-initialization
Class as a
Data-type
• To switch from array to vector or vice-versa the application needs no change
• Application cannot tamper stack – any direct access to top or data is compilation error!
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 10
Program 12.07: Interface and Implementation
Interface Implementation
Module 12

Intructors: Abir // File: Stack.h -- Interface // File: Stack.cpp -- Implementation


Das and class Stack { private: // Implementation #include "Stack.h"
Sourangshu char *data_; int top_;
Bhattacharya
public: // Interface Stack::Stack(): data_(new char[100]), top_(-1) { }
Stack(); Stack::~Stack() { delete[] data_; }
Objectives &
Outline ~Stack(); int Stack::empty() { return (top_ == -1); }
int empty(); void Stack::push(char x) { data_[++top_] = x; }
Access Specifiers
void push(char x); void Stack::pop() { --top_; }
Examples
void pop(); char Stack::top() { return data_[top_]; }
Information char top();
Hiding
};
Stack Example
Stack (public) Application
Risky #include <iostream>
Stack (private) using namespace std;
Safe #include "Stack.h"
Interface and int main() {
Implementation
Stack s; char str[10] = "ABCDE";
Get-Set Idiom for (int i = 0; i < 5; ++i) s.push(str[i]);
Encapsulation while (!s.empty()) {
cout << s.top(); s.pop();
Class as a
Data-type
}
}
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 11
Get–Set Methods: Idiom for fine-grained Access Control

Module 12 • We put attributes in private and the methods in public to restrict the access to data
• public methods to read (get) and / or write (set) data members provide fine-grained control
Intructors: Abir
Das and class MyClass { // private
Sourangshu int readWrite_; // Like re_, im_ in Complex -- common aggregated members
Bhattacharya

int readOnly_; // Like DateOfBirth, Emp_ID, RollNo -- should not need a change
Objectives &
Outline
int writeOnly_; // Like Password -- reset if forgotten
Access Specifiers
Examples
int invisible_; // Like top_, data_ in Stack -- keeps internal state
Information
Hiding public:
Stack Example // get and set methods both to read as well as write readWrite_ member
Stack (public) int getReadWrite() { return readWrite_; }
Risky void setReadWrite(int v) { readWrite_ = v; }
Stack (private)
Safe // Only get method to read readOnly_ member - no way to write it
Interface and
Implementation
int getReadOnly() { return readOnly_; }
Get-Set Idiom // Only set method to write writeOnly_ member - no way to read it
Encapsulation void setWriteOnly(int v) { writeOnly_ = v; }
Class as a
Data-type // No method accessing invisible_ member directly - no way to read or write it
}
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 12
Get, Set Methods

Module 12

Intructors: Abir • Get, Set methods of a class are the interface defined for accessing and using the private
Das and
Sourangshu data members. The implementation details of the data members are hidden.
Bhattacharya
• Not all data members are allowed to be updated or read, hence based on the
Objectives &
Outline requirement of the interface, data members can be read only, write only, read and write
Access Specifiers both or not visible at all.
Examples

Information
• Let get and set be two variables of bool type which signifies presence of get and set
Hiding methods respectively. In the below table, T denotes true (that is, method is present)
Stack Example
Stack (public)
and F denotes False (that is, method is absent)
Risky
Stack (private)
Safe Variables get set
Interface and
Implementation Non Visible F F
Get-Set Idiom
Read Only T F
Encapsulation
Write Only F T
Class as a
Data-type Read - Write T T
Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 13
Program 12.08: Get - Set Methods: Employee Class
Get-Set Methods
Module 12

Intructors: Abir // File Name:Employee_c++.cpp:


Das and #include <iostream>
Sourangshu #include <string>
Bhattacharya
using namespace std;
Objectives &
Outline class Employee { private:
string name; // read and write: get_name() and set_name() defined
Access Specifiers
string address; // write only: set_addr() defined. No get method
Examples
double sal_fixed; // read only: get_sal_fixed()defined. No set method
Information double sal_variable; // not visible: No get-set method
Hiding

Stack Example public: Employee() { sal_fixed = 1200; sal_variable = 10; } // Initialize


Stack (public) string get_name() { return name; }
Risky void set_name(string name) { this->name = name; }
Stack (private) void set_addr(string address) { this->address = address; }
Safe
double get_sal_fixed() { return sal_fixed; }
Interface and
Implementation
// sal_variable (not visible) used in computation method salary()
double salary() { return sal_fixed + sal_variable; }
Get-Set Idiom
};
Encapsulation int main() {
Class as a Employee e1; e1.set_name("Ram"); e1.set_addr("Kolkata");
Data-type cout << e1.get_name() << endl; cout << e1.get_sal_fixed() << endl << e1.salary() << endl;
Module Summary
}
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 14
Encapsulation

Module 12

Intructors: Abir • classes wrap data and functions acting on the data together as a single data structure. This is
Das and
Sourangshu Aggregation
Bhattacharya
• The important feature introduced here is that members of a class has a access specifier,
Objectives &
Outline
which defines their visibility outside the class
Access Specifiers • This helps in hiding information about the implementation details of data members and
Examples
methods
Information
Hiding ◦ If properly designed, any change in the implementation, should not affect the interface
Stack Example provided to the users
Stack (public)
Risky ◦ Also hiding the implementation details, prevents unwanted modifications to the data
Stack (private) members.
Safe
Interface and
Implementation
• This concept is known as Encapsulation which is provided by classes in C++.
Get-Set Idiom

Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 15
Class as a Data-type

Module 12
• We can conclude now that class is a composite data type in C++ which has similar behaviour
Intructors: Abir
Das and to built in data types. We explain below with the Complex class (representing complex
Sourangshu
Bhattacharya
number) as an example

Objectives &
Outline // declare i to be of int type // declare c to be of Complex type
int i; Complex c;
Access Specifiers
Examples
// initialise i // initialise the real and imaginary components of c
Information int i = 5; Complex c = { 4, 5 };
Hiding

Stack Example // print i // print the real and imaginary components of c


Stack (public) cout << i; cout << c.re << c.im;
Risky
OR c.print(); // Method Complex::print() defined for printing
Stack (private)
OR cout << c; // operator<<() overloaded for printing
Safe
Interface and
Implementation // add two ints // add two Complex objects
Get-Set Idiom
int i = 5, j = 6; Complex c1 = { 4, 5 }, c2 = { 4, 6 };
i+j; c1.add(c2); // Method Complex::add() defined to add
Encapsulation OR c1+c2; // operator+() overloaded to add
Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 16
Module Summary

Module 12

Intructors: Abir • Access Specifiers help to control visibility of data members and methods of a class
Das and
Sourangshu
Bhattacharya
• The private access specifier can be used to hide information about the implementation
details of the data members and methods
Objectives &
Outline • Get, Set methods are defined to provide an interface to use and access the data
Access Specifiers members
Examples

Information
Hiding

Stack Example
Stack (public)
Risky
Stack (private)
Safe
Interface and
Implementation

Get-Set Idiom

Encapsulation

Class as a
Data-type

Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 17

You might also like