Classes and Objects. Class scope: - private members are only accessible by the class methods.

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

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Short Notes of CS201

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Object Oriented Design

CS201 - Introduction to Programming Glossary By

An Introduction to C++

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

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

Introduction Of Classes ( OOPS )

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Lecture 18 Tao Wang 1

Assignment of Objects

Assignment of Structs

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


Intermediate Programming & Design (C++) Classes in C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

04-19 Discussion Notes

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

COMP 2355 Introduction to Systems Programming

CS201- Introduction to Programming Current Quizzes

Chapter 10 Introduction to Classes

CS201 Some Important Definitions

Object-Oriented Programming

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

CSC1322 Object-Oriented Programming Concepts

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

G52CPP C++ Programming Lecture 13

CPSC 427: Object-Oriented Programming

Inheritance, and Polymorphism.

Introduction to Classes

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

CS3157: Advanced Programming. Outline

Interview Questions of C++

Recharge (int, int, int); //constructor declared void disply();

Midterm Review. PIC 10B Spring 2018

Simplest version of DayOfYear

Cpt S 122 Data Structures. Introduction to C++ Part II

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

Object-Oriented Programming for Scientific Computing

Chapter 11. Abstract Data Types and Encapsulation Concepts

Object-Oriented Programming

Constructors for classes

C++ 8. Constructors and Destructors

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Pointers, Dynamic Data, and Reference Types

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Abstraction in Software Development

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

CS304 Object Oriented Programming Final Term

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

AN OVERVIEW OF C++ 1

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

ADTs & Classes. An introduction

Fast Introduction to Object Oriented Programming and C++

ADTs in C++ In C++, member functions can be defined as part of a struct

explicit class and default definitions revision of SC22/WG21/N1582 =

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

CIS 190: C/C++ Programming. Classes in C++

Constructor - example

Object-Oriented Principles and Practice / C++

Scope. Scope is such an important thing that we ll review what we know about scope now:

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Abstract Data Types and Encapsulation Concepts

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Binding and Variables

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

More C++ : Vectors, Classes, Inheritance, Templates

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

2 ADT Programming User-defined abstract data types

Lecture 5. Function Pointers

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Classes and Pointers: Some Peculiarities

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

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

Written by John Bell for CS 342, Spring 2018

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Introduction to C++ Systems Programming

04-17 Discussion Notes

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members

Make Classes Useful Again

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Come and join us at WebLyceum

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

Transcription:

Class Declaration Classes and Objects class class-tag //data members & function members ; Information hiding in C++: Private Used to hide class member data and methods (implementation details). Public Used to expose class member data and methods to the client (interface) Class scope: - private members are only accessible by the class methods. Public scope: - public members can be accessed outside the class Member selection operator: - To gain access to data or methods in a class the client must select the field using an appropriate operator. - member selector operator -. (dot) - class indirection operator - -> (dash, greater-than symbol) 08/25/18 1

The declaration for a class to represent date. (DateClass.h) class DateClass public: // Member function declarations void Set(int newmo, int newday, int newyr); void Print() const; bool Equal(DateClass otherdate) const; ; private: // Member data declarations int mo; int day; int yr; const at the end of a function declaration indicates that the function doesn t change the data in the object. By default members are private, must use public: to open up members to a client program. (structs default members to public) Example - piece of a client Program (prog.cpp) #include DateClass.h // variable declarations DateClass Date1; DateClass Date2; Visual Image of the DateClass Class objects: Date1 and Date2 Each has its own copies of all members Technically the functions are not duplicated. 08/25/18 2

Defining Class Methods: A method may be declared inside the class declaration and defined outside the class declaration. Must use the scope resolution operator (::) in function member header in method definition. A method may be defined inside the class declaration inline The definition for methods in the class to represent date. (DateClass.cpp) #include DateClass.h #include <iostream.h> void DateClass :: Set (int newmo, int newday, int newyr) mo = newmo; day = newday; yr = newyear; void DateClass :: Print() const cout << mo << "/" << day << "/" << yr; bool DateClass :: Equal(DateClass otherdate) const return (( mo == otherdate.mo ) && (day == otherdate.day) && (yr == otherdate.yr)) Using classes in programs: Separate: class.h file contains the class declaration (interface or specification file) class.cpp file contains the class method definitions (implementation file). Is typically compiled into class.o file for use by a client program. client.cpp file contains the client code that #includes the class.h file and is linked with the class.o to create the executable program that solves the problem. 08/25/18 3

Efficiency and Robustness Issue for Classes and Objects Passing and Returning Objects by Reference: - objects should be pass by reference & returned by reference (for efficiency) Object References as const parameter: - parameters that are not changing but marked as reference parameters should be marked with const const Methods: - methods that do not change the data members should be marked const - methods marked const should only call other methods marked const - prevents unintended write operations - encourages compiler optimization Constructors and the Destructor invoked automatically by the compiler (not the programmer) Constructors: Member function uses the class name. No return value - return data type is omitted. Can be overloaded but each must have its own signature If a class has multiple constructors then the appropriate constructor is chosen by the actual parameters (or no parameters) passed when the declaration of the class object is made. Default Constructor - parameter-less, must exist to have any constructors (This is the one used in declaration of arrays of a class). Parameterized Constructors - have parameters - matched by the data type and number of parameters passed in the declaration. Copy Constructors Convert Constructors 08/25/18 4

add to the DateClass.h the specification of the public member functions for construction: DateClass(); // declaration of the default constructor DateClass(int, int, int); // declaration of a parameterized constructor add to the DateClass.cpp the implementation of the constructors: DateClass::DateClass() mo = 1; day = 1; yr = 2000; DateClass::DateClass(int initmo, int initday, int inityr) mo = initmo; day = initday; yr = inityr; Copy Constructor: Shallow copy - An operation that copies one class object to another without copying any pointed-to data. assignment - Queue1 = Queue2. Pointer values are copied, but both queues point to same data. As items are added and removed from Queue1, this automatically effects Queue2, causes system errors. int *p; int arr[5] = 2, 4, 6, 8, 10 p = new int[5]; p = arr; // What is actually copied???? 08/25/18 5

C++ automatically does shallow copying: passing a parameter by value initializing a variable in a declaration using the assignment operator returning a value from a function performing an assignment using the assignment operator Deep copy - An operation that not only copies a class object data to another but also makes copies of any pointed-to data. Copy Constructor - invoked whenever one class object is initialized by another. Initialization Means: (these default to shallow copying without c.c.) 1. Initialization in a variable declaration QueType Q1 (Q2) ; 2. Passing a copy of an actual to formal parameter using pass-by-value. fun1(q1). void fun1(quetype Q) 3. Returning object using return-by-value from a function return (Q);. Q1 = fun1(..); Prototype of the copy constructor: class SomeClass public: SomeClass(const SomeClass& someobject); // copy constructor ; Body of constructor should dynamically allocate memory and copy items from parameter into dynamic memory of this class object. To disable using the object in pass-by-value or return-by-value include the copy constructor in the private section. 08/25/18 6

Convert Constructor converts a different data type into this class data type. must be a single parameter constructor can be used implicitly as an alternative to function overloading and explicit casting can be used explicitly to cast and convert (using keyword explicit) add to the DateClass.h the specification for copy & convert constructors: DateClass(const DateClass& d ); // copy constructor DateClass(const string& s ); // convert constructor or explicit DateClass(const string& s); //explicit version add to the DateClass.cpp the implementation of these constructors: DateClass::DateClass(const DateClass & d) mo = d.mo; day = d.day; yr = d.yr; DateClass::DateClass(const string& s) mo = (s[0]- 0 * 10) + (s[1] 0 ); day = (s[2]- 0 * 10) + (s[3] 0 ); yr = (s[4]- 0 * 10) + (s[5] 0 ); 08/25/18 7

Constructor Initializers (ctor initializer): Used to initialize any data members Only way to initialize constant data in a constructor Can leave function body empty class SomeClass public: SomeClass( ); private: int dm1; const int dm2; ; SomeClass::SomeClass( ) : dm1(3), dm2(15) cout << dm1 << dm2 <<endl ; // prints 3 and 15 08/25/18 8

Destructor - uses same syntax as constructor but member function name has a tilde (~) in front of it. Implicitly invoked when control reaches the end of the block in which the variable is declared ( lifetime is over ). DateClass d1; constructor is invoked destructor is invoked Only necessary if deallocation is not automatic. Deallocation occurs automatically when the private data is enclosed entirely within the abstraction barrier of the class (static memory allocation). ( DateClass). Non-automatic deallocation occurs when there is a pointer within the class that points to dynamic data outside of abstraction barrier ( Dynamic implementation of a list). When the variable is destroyed the only automatic deallocation is the pointer variable, leaving the dynamic data no longer accessible. add to the DateClass.h the specification for destructor: ~DateClass(); // declaration of the destructor add to the DateClass.cpp the implementation of the destructor: DateClass:: ~DateClass() // Body of member function - deallocates any dynamic memory 08/25/18 9

Class Data Members and Methods Static data members - belongs to the class itself, not the instance - a data member declared static is created just once for the entire class - declared inside the class declaration using the keyword static - Must be defined outside all blocks and initialized class SomeClass public: private: static int count; // declaration ; int SomeClass::count = 0; // definition Static methods - can only access static members of the class class SomeClass public: static int ReportCount( ) const; private: static int count; // declaration ; int SomeClass::count = 0; // definition int SomeClass::ReportCount( ) const return count; 08/25/18 10

Static local variables inside class methods - method has one underlying variable shared by all objects in the class when the method is invoked class SomeClass public: int F1( ) ; private: int d1; ; int SomeClass::F1( ) static int v = 0; v++; return v; // only init once, shared by all objects int main( ) SomeClass a, b, c; cout << a. F1( ) << b. F1( ) << c.f1( ) << endl; // prints 1, 2, 3 08/25/18 11

Pointers to Objects Class indirection operator : -> used for pointers to objects int main( ) DateClass* dptr; dptr->set(1,24,2000); dptr->print( ); The Pointer constant this - this pointer can be used inside a method to access the object that invoked the method. - this is equal to the address of the object instance - this pointer is constant and can be accessed in nonstatic methods void DateClass :: Set (int newmo, int newday, int newyr) //mo = newmo; this -> mo = newmo; //day = newday; this -> day = newday; //yr = newyear; this -> yr = newyear; 08/25/18 12