Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.

Similar documents
C++ Classes 2008/04/03. Programming Research Laboratory Seoul National University

CSI33 Data Structures

COMP6771 Advanced C++ Programming

Chapter 13: Copy Control. Overview. Overview. Overview

COMP6771 Advanced C++ Programming

CS304 Object Oriented Programming Final Term

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

Object Oriented Programming

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

Short Notes of CS201

Operator overloading. Conversions. friend. inline

CS201 - Introduction to Programming Glossary By

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

eingebetteter Systeme

Fast Introduction to Object Oriented Programming and C++

Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today)

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

2 ADT Programming User-defined abstract data types

Chapter 18 - C++ Operator Overloading

COMP6771 Advanced C++ Programming

CS304 Object Oriented Programming

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

EL2310 Scientific Programming

III. Classes (Chap. 3)

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming COP3330 / CGS5409

Programming 2. Object Oriented Programming. Daniel POP

Operator Overloading in C++ Systems Programming

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

Friends and Overloaded Operators

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Friends and Overloaded Operators

PHY4321 Summary Notes

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Chapter 15 - C++ As A "Better C"

Lecture 7. Log into Linux New documents posted to course webpage

CS 7B - Spring Final Exam

C++ 8. Constructors and Destructors

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

Instantiation of Template class

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

19. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

Introduction to C++ Systems Programming

CS

Type Erasure. Nevin :-) Liber Friday, October 29, Chicago C/C++ Users Group Nevin J. Liber All Rights Reserved.

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

Object-Oriented Principles and Practice / C++

C++ Modern and Lucid C++ for Professional Programmers

C++ Tutorial AM 225. Dan Fortunato

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Programming 2. Object Oriented Programming. Daniel POP

EL2310 Scientific Programming

Object-Oriented Programming for Scientific Computing

PIC10B/1 Winter 2014 Exam I Study Guide

Introduction Of Classes ( OOPS )

And Even More and More C++ Fundamentals of Computer Science

PIC 10A Objects/Classes

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

COMP6771 Advanced C++ Programming


Basic Types, Variables, Literals, Constants

Abstract Data Types (ADT) and C++ Classes

Intermediate Programming, Spring 2017*

Interview Questions of C++

17. Classes. Overloading Functions. Operator Overloading. Function Overloading. operatorop

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

A <Basic> C++ Course

EECE.3220: Data Structures Spring 2017

Advanced Systems Programming

Classes and Operators. Ali Malik

A <Basic> C++ Course

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Financial computing with C++

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

C++ (Non for C Programmer) (BT307) 40 Hours

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

C++ Important Questions with Answers

CS250 Final Review Questions

Object Oriented Programming(OOP).

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Program construction in C++ for Scientific Computing

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

COMP6771 Advanced C++ Programming

Object-Oriented Programming

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Object-Oriented Principles and Practice / C++

COSC 2P95 Lab 5 Object Orientation

CS 376b Computer Vision

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Transcription:

Classes II: Type Conversion,, For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Abstraction and Encapsulation Abstraction: Separation of interface from implementation Encapsulation: Combining lower level elements to form higher-level entity. Access Labels (public/private/protected) enforce abstraction and encapsulation. Piyush Kumar #include<utility> Concrete Types. A concrete class exposes, rather than hides, its implementation Example : pair<> (defined in <utility>) Exists to bundle two data members. Benefits of Abstraction & Encapsulation Class internals are protected from user-lever errors. Class implementation may evolve over time without requiring change in user-level code. std::pair<std::string, int> pr1; //-- Declare a pair variable std::pair<std::string, int> pr2("heaven", 7); // Declare - initialize with constructor. std::cout << pr2.first << "=" << pr2.second << std::endl; // Prints: heaven=7 return 0; More on Class definitions Using Typedefs to streamline classes. std::string contents; std::string::size_type cursor; std::string::size_type height,width; using index = std::string::size_type; std::string contents; index cursor; index height,width; ; inline Screen::index Screen::get_cursor() const{ return cursor; 1

Class declaration class Screen; // declaration of the class Forward declaration: Introduces the name Screen into the program and indicates that Screen refers to a class name. Incomplete Type: After declaration, before definition, Screen is an incomplete type. It s known screen is a type but not known what members that type contains. Class declaration for class members. Because a class is not defined until its class body is complete, a class cannot have data members of its own type. A class can have data members that are pointers or references to its own type. class Human { Screen window; Human *bestfriend; Human *father, *mother; Implement Screen class so that: myscreen.move(4,0).set( # ); Can replace the following two lines: myscreen.set(4,0); myscreen.set( # ); Return reference to Screen in the member functions. Screen& move(index r, index c); Screen& set(char); Implementation: Screen& Screen::move(index r,index c){ index row = r* width; cursor = row +c; return *this; Mutable data members Beware of const: const Screen& Screen::display(ostream &os) const { os << contents; return *this; myscreen.move(4,0).set( # ).display(cout) Sometimes, you might want to modify a variable inside a const member function. A mutable data member is a member that is never const (even when it is a member of a const object). mutable => removes const qualification 2

Mutable data members Guideline. mutable size_t access_ctr; ; void Screen::do_display(std::ostream& os) const { ++access_ctr; // keep count of calls to any member func. os << contents; Never repeat code. If you have member functions that need to have repeated code, abstract it out in another function and make them call it (maybe inline it). Type conversion: Revisited Type conversions: revisited int i; float f; f = i; // implicit conversion f = (float)i; // explicit conversion f = float(i); // explicit conversion Can convert from one type into this type with constructor Bitset( const unsigned long x ); How do we convert from this type to something else? Create an operator to output the other type Later. Implicit Type conversion Beware: A constructor that can be called with a single argument defines an implicit conversion from the parameter type to the class type. Class SalesItem { Public: SalesItem(const std::string &book = ) : isbn (book), units_sold(0), revenue(0.0) { class String { String( int ); // Allocation constructor //... ; // Function that receives an object of type String as an argument void foo( const String& ); // Here we call this function with an int as argument int x = 100; foo( x ); // Implicit conversion => foo( String( x ) ); String null_book = 9-999-9999-9 ; Item.sale_isbn(null_book); // implicit type conversion.. 3

User defined implicit type conversion Suppressing implicit conversions. class String{ std::string str; String(char * cp){str = cp;; operator const char * () const; ; String::operator const char * () const{ std::cout << "type conversion" << std::endl; const char * out = str.c_str(); return out; Use explicit before conversion constructors. explicit String( char* cp ); // Constructor void foo(const String& astring){; void bar(const char * fewchars){; foo("hello"); // Implicit type conversion char* -> String String peter = "pan"; // Calls parametrized constructor. Treats "pan" as char * static_cast<const char *>(peter); // Implicit type conversion String -> const char* bar(peter); return 0;. friend function/classes Can access private and protected (more later) members of another class friend functions are not member functions of class Defined outside of class scope A Friend declaration begins with the keyword friend Properties hip is granted, not taken NOT symmetric if B a friend of A, A not necessarily a friend of B NOT transitive if A a friend of B, B a friend of C, A not necessarily a friend of C. friend declarations friend function Keyword friend before function prototype in class that is giving friendship. friend int myfunc( int x ); Appears in the class granting friendship friend class Type friend class Classname in class granting friendship If ClassOne granting friendship to ClassTwo, friend class ClassTwo; appears in ClassOne's definition Why use friends? to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Be careful: can have access to everything, which defeats data hiding. have permission to change the internal state from outside the class. Always use member functions instead of friends to change state 4

An example #include <iostream> #include <string> class SalesItem { friend bool operator==(const Sales_item&, const SalesItem&); friend std::istream& operator>>(std::istream&, SalesItem&); friend std::ostream& operator<<(std::ostream&, const SalesItem&); // other members as before // added constructors to initialize from a string or an istream SalesItem(const std::string &book): isbn(book), units_sold(0), revenue(0.0) { SalesItem(std::istream &is) { is >> *this; // operations on SalesItem objects // member binary operator: left-hand operand bound to implicit this pointer SalesItem& operator+=(const SalesItem&); // other members as before Class to handle an integer sequence /* File: numbers.hpp */ #include<ostream> class Sequence{ int * numbers; int length; Sequence(); Sequence(const int, std::string &); // Parameterized constructor Sequence(const Sequence&); // Copy constructor ~Sequence(); // Destructor void operator=(const Sequence &); // Overloaded assignmnt int operator()(int); friend std::ostream& operator<<(std::ostream&, const Sequence&); ; /* File: main.cpp */ #include "numbers.hpp" #include<sstream> #include<ostream> Sequence::Sequence(){ numbers = nullptr; length = 0; Sequence::Sequence(const int n, std::string & instring){ std::stringstream ss; ss << instring; length = n; numbers = new int[length]; for(int i = 0; i < length; i++){ ss >> numbers[i]; Sequence::Sequence(const Sequence & inseq){ std::cout << "Copy constructor" << std::endl; length = inseq.length; numbers = new int[length]; for(int i = 0; i < length; i++){ numbers[i] = inseq.numbers[i]; Sequence::~Sequence(){ if(numbers!= nullptr){ delete [] numbers; numbers = nullptr; int Sequence::operator()(int index){ return numbers[index]; std::ostream& operator<<(std::ostream& out, const Sequence& seq){ out << "Overloaded <<" << std::endl; for(int i = 0; i < seq.length; i++){ out << seq.numbers[i] << " "; out << std::endl; return out; #include "numbers.hpp" std::string instr = "12 34 56 78 88 77"; Sequence w(4, instr); std::cout << w(2) << std::endl; // overloaded () std::cout << w; // overloaded << operator Output: 56 Overloaded << 12 34 56 78 5