Chapter 17-18. Defining Classes and Creating objects class Person {public : void setAge (int n) {age=n;} int getAge() {return age;} private:int age;};

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
 2003 Prentice Hall, Inc. All rights reserved. ECE 2552 Dr. S. Kozaitis Summer Summary of Topics Related to Classes Class definition Defining member.
By Senem Kumova Metin 1 POINTERS + ARRAYS + STRINGS REVIEW.
OBJECT ORIENTED PROGRAMMING Instructor: Rashi Garg Coordinator: Gaurav Saxena.
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 11 More.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
Outline 1 Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü.
A Deeper Look at Classes CS-2303, C-Term A Deeper Look at Classes CS-2303 System Programming Concepts (Slides include materials from The C Programming.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 4 - Classes Jan 27,
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
PART I CHAPTER 16 CS116 SENEM KUMOVA METİN 1. Structures Structures : Aggregate data types built using elements of other types struct Time { int hour;
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
11 Introduction to Object Oriented Programming (Continued) Cats.
WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg.
Chapter 9 Classes: A Deeper Look, Part I Part II.
LECTURE 4. Composition Definition: A data member of a class is an object of some other class Example: an AlarmClock object needs to know when it is supposed.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Review of Last Lecture. What we have learned last lecture? What does a constructor do? What is the way to define a constructor? Can it be defined under.
1 const and this Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
 2000 Prentice Hall, Inc. All rights reserved const (Constant) Objects and const Member Functions Principle of least privilege –Only give objects.
OPERATOR OVERLOADING WEEK 4-5 CHAPTER 19. class Money {private:int lira; int kurus; public: Money() {}; Money(int l, int k) { lira=l+ k/100; kurus=k%100;
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
1 2/21/05CS250 Introduction to Computer Science II Destructors, Get and Set, and Default Memberwise Assignment.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 CMSC 202 ADTs and C++ Classes. 2 Announcements Project 1 due Sunday February 25 th at midnight – don’t be late! Notes and clarifications for Project.
EEL 3801 Part VI Fundamentals of C and C++ Programming Classes and Objects.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
Classes.  A collection of variables combined with a set of related functions MemberFunctions (methods) (methods) MemberVariables (data members) (data.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Function Overloading Can enables several function Of same name
Lecture 5: Classes (continued) Feb 1, 2005
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Object-Oriented Programming
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
group work #hifiTeam
Chapter 7: Classes Part II
Chapter 7: Classes Part II
Lecture 4: Classes (continued) June 14, 2004
Constructor & Destructor
Chapter 7: Classes Part II
7.4 friend Functions and friend Classes
Chapter 7: Classes Part II
Recitation Course 0520 Speaker: Liu Yu-Jiun.
A Deeper Look at Classes
Chapter 7: Classes Part II
Presentation transcript:

Chapter 17-18

Defining Classes and Creating objects class Person {public : void setAge (int n) {age=n;} int getAge() {return age;} private:int age;}; main() { Person p; p.setAge(8); Person & q=p; q.setAge(8); Person * pointer=new Person; pointer->setAge(8); Person arr[3]; arr[0].setAge(8);arr[1].setAge(9);arr[2].setAge(10);} CS116 SENEM KUMOVA METİN2

Access Functions class Person { public : void setAge (unsigned n) { age = n; }; unsigned getAge() const {return age;}; private: unsigned age;}; /* Member functions(methods) which access private members are access functions */ main() {Person x; cout<<x.getAge()<<endl; x.setAge(7); cout<<x.getAge()<<endl; } CS116 SENEM KUMOVA METİN3

Access Functions class Time { public : void setTime (int h, int m) { this->h= h; minute=m; } int getHour(); int getMinute() {return minute;}; void print(){cout<<hour<<“:”<minute;} private: int hour; int minute;}; int Time:: getHour(){return hour;} main() {Time x; cout<<x.getHour()<<endl; x.setTime(10,20); cout<<x.getHour()<<endl; cout<<x.getMinute()<<endl; x.print(); } CS116 SENEM KUMOVA METİN4

Constructors class Person { public : Person() {age=10;} void setAge (unsigned n) { age = n; }; unsigned getAge() const {return age;}; private: unsigned age;}; main() {Person x; cout<<x.getAge()<<endl; //  10 x.setAge(7); cout<<x.getAge()<<endl; //  7 } CS116 SENEM KUMOVA METİN5

Constructors class Person {public : Person() ; Person(string n, int a) ; void print(){cout<<name<<“:”<<age; } private: string name; int age; }; Person :: Person() { name =“Unknown”; age =0; } Person :: Person (string n, int a) { name=n; age=a;} void main() { Person p1; p1.print(); string x=“not name”; Person p2(x, 10); p2.print(); } CS116 SENEM KUMOVA METİN6

Constructor with default values class Person {public : Person(string =“Unknown”, int =0) ; void print(){ cout<<name<<“:”<<age; } private: string name; int age; }; Person :: Person (string n, int a) { name=n; age=a;} void main() { Person p1; p1.print(); string x=“not name”; Person p2(x, 10); p2.print(); Person p3(x); p3.print(); Person p4; p4=p3; // default memberwise assignment p4.print(); } CS116 SENEM KUMOVA METİN7

Constructors: Restricting Object Creation class Emp {public : Emp(unsigned ID ) { id=ID;} unsigned id; private:Emp() ;}; void main() { Emp cher( ); //IS IT POSSIBLE?? Emp elvis; //IS IT POSSIBLE?? } /* IF A CLASS EXPLICITLY DECLARES ANY CONSTRUCTOR, THE COMPILER DOES NOT PROVIDE A public DEFAULT CONSTRUCTOR */ /* IF A CLASS DECLARES a NON public DEFAULT CONSTRUCTOR, COMPILER DOES NOT PROVIDE A public DEFAULT CONSTRUCTOR */ CS116 SENEM KUMOVA METİN8

Copy Constructor A copy constructor creates a new object as a copy to another object Copy constructor for Person class -  Person(Person &); class Person {public : Person(string n, int a) { name=n; age=a;} private : string name; int age;}; main(){ string s1(“Bob”); Person p1(s1,15); Person p2(p1); /* which constructor works????? */ } You may define your copy constructor class Person {public : Person(string, int) ; Person(Person & x) {name=x.name; age=x.age+1;} ; private : string name; int age;}; CS116 SENEM KUMOVA METİN9

CONSTRUCTORS : new and new [] operators class Emp { public : Emp() {…..} Emp(const char * name) {…} private : char *n; }; int main() { int * x= new int; Emp * elvis= new Emp(); // default constructor initializes Emp * cher= new Emp(“Cher”); // second constructor initializes return 0; } CS116 SENEM KUMOVA METİN10

DESTRUCTORS A constructor is automatically invoked whenever an object is created A destructor is automatically invoked whenever an object is destroyed A destructor takes no arguments and no return type, there can be only one destructor per class class C { public : C() { … }; // constructor ~C() { … }; // destructor … } CS116 SENEM KUMOVA METİN11

DESTRUCTOR: EXAMPLE class C {public : C() {name=“anonymous”;} C(string n) { name=n;} ~C() { cout <<“destroying” <<name<<“\n”;} private: string name;}; int main() { string n = “hello”; C c1(n); C * ptr =new C(); delete ptr; // destructor for ptr object is called return 0; // destructor for c1 is called } CS116 SENEM KUMOVA METİN12

const keyword Where to use ?? – Input/ output parameters – Objects – Methods – Data members CS116 SENEM KUMOVA METİN13

const input or output parameters class Time {public: void setTime( const int & m, const int& h ) { minute=m; hour=h; /* it is not possible for setTime to change the value of m or h since m and h are constants*/ } const int & getHour() { return hour;}; private:int hour; int minute;}; main() {int a=16, b=15; Time obj; obj.setTime(a, b) ; /* setTime() cannot change the value of a or b of main()*/ const int &x = obj.getHour(); /* main() cannot change the return value of getHour()  hour is private */ } CS116 SENEM KUMOVA METİN14

const objects class Time { public: void setTime( int h, int m) {hour=h; minute=m}; void printStandard() const{ cout<<hour<<“:”<<minute;}; private: int hour; int minute; }; main() { Time wakeup; wakeup.setTime(8,30); wakeup.printStandard(); const Time noon; noon.setTime(8,30); // noon is a constant object you can not call a // non_const method noon.printStandard();} // const object may call only const methods CS116 SENEM KUMOVA METİN15

const methods class Time { public: void setTime( int, int ); void printUniversal() const {hour=12; }; //?????? void printStandard() const { cout<<hour;}; private: int hour; int minute; }; /* The keyword const in methods printUniversal and printStandard shows that unlike method SetTime, these methods do not change the value of any Time data member… */ CS116 SENEM KUMOVA METİN16

const data members class Increment { public: Increment(int c=0, int i=1); void addIncrement {count+=incr;} void print const { cout<<count;}; private: int count; const int incr; }; /* It is not possible to change the values of const data members after initialization, initialization can be done only in constructors*/ Increment:: Increment(int c, int i) :count(c),incr(i){}; // Increment:: Increment(int c, int i) :increment(i){count=c;}; CS116 SENEM KUMOVA METİN17

Class Data Members and Methods To create a class member static keyword is used A static (class) member is created once and it is unique for all objects created from a class class C {int x; static int s;}; C c1, c2, c3; CS116 SENEM KUMOVA METİN18 xxx c1 c2 c3 C::s

Static members : Data members A static member does not effect the size of a class or an object of this class type A static data member may be declared inside a class declaration but must be defined outside class Task {public: … private: static unsigned n; // declaration … }; unsigned Task::n=0; // definition CS116 SENEM KUMOVA METİN19

Static members : Methods A static method can access only other static members class Task {public: static unsigned getN() const {return n;} static int getK() const {return k;} //NOT POSSIBLE!!! private: static unsigned n; int k; }; CS116 SENEM KUMOVA METİN20

Static members : Accessing class Task {public: static unsigned getN() const {return n;} static unsigned n; }; unsigned Task::n=5; int main() {Task c1, c2; c1.getN(); // access through an object Task::getN(); // access through class (direct access) unsigned x= c1.n; // access through an object unsigned y= c2.n; // access through an object unsigned z= Task::n; // access through class (direct access) } CS116 SENEM KUMOVA METİN21

Static variables defined inside methods class C {public : void m(); private : int x; }; void C::m() { static int s=0; // one copy for all objects!! cout<<++s<<‘\n’;} int main() { C c1,c2,c3; c1.m(); // 1 c2.m(); // 2 c3.m(); // 3 return 0;} CS116 SENEM KUMOVA METİN22

static const data members class Date { public: static const int monthsPerYear =12; Date(int =1, int =1, int =1900); void print const { cout<<month<<“.”<<day<<<<“.”year; } private: int day; int month; int year; }; Date:Date(int d, int m, int y) {day=d; year=y; if(m>0&&m<=monthsPerYear) month=m; else { cout<<“invalid month”; month=1;}} void main() { Date obj1(12,4,1999); obj1.print(); Date obj2(3,12,2000); obj2.print();} CS116 SENEM KUMOVA METİN23

How to define functions wtih objects ?? Call by value  Send/return objects to/from functions Call by reference  Send/return references (or pointers) of objects to/from functions Friend Functions CS116 SENEM KUMOVA METİN24

Passing and Returning Objects by Value class Person { public : void setAge (unsigned n) { age = n; }; unsigned getAge() const {return age;}; private: unsigned age;}; Person func1() { Person p; p.setAge(4); return p;} unsigned func2( Person y) { y.setAge(3); return y.getAge(); } main() {Person x; cout<<x.getAge()<<endl; x=func1(); cout<<x.getAge()<<endl;; cout << func2(x)<<endl; cout<<x.getAge()<<endl;} CS116 SENEM KUMOVA METİN25 OUTPUT ???

Passing and Returning Objects by Reference class Person { public : void setAge (unsigned n) { age = n; }; unsigned getAge() const {return age;}; private: unsigned age;}; Person & func1() { static Person p; p.setAge(4); return p;} unsigned func2( Person & y) { y.setAge(3); return y.getAge(); } main() {Person x; cout<<x.getAge()<<endl; x=func1(); cout<<x.getAge()<<endl;; cout << func2(x)<<endl; cout<<x.getAge()<<endl;} CS116 SENEM KUMOVA METİN26 OUTPUT ???

Pointer to Objects class Person { public : void setAge (unsigned n) { age = n; }; unsigned getAge() const {return age;}; private: unsigned age;}; void func(Person * ptr) { ptr->setAge(5); cout getAge()<<endl; } void main() { Person x; x.setAge(4); cout<<x.getAge()<<endl; func(&x); cout<<x.getAge()<<endl;} CS116 SENEM KUMOVA METİN27  Accessing to an object’s members through a pointer requires class indirection operator “->” OUTPUT ???

Friend Functions  A class’s private members are accessible only to 1. its methods (member functions) 2. its friend functions!!!  A friend function must be declared inside class definition with keyword “friend”  A friend function can be declared within private, protected or public part of the declaration of class  A friend function is not a method!!!!

Friend Function class Count {friend void setX(Count &, int); // friend function public: Count ():x(0){} ~Count() {cout<<“object is destructed”<<endl;} void print() { cout<<x<<endl;} private: int x;}; void setX(Count &c, int val) {c.x=val;} int main() { Count counter; cout<<“counter.x after instantiation : ”; counter.print(); setX(counter,8); cout<<“counter.x after call to setX friend function : ”; counter.print();}

The Pointer Constant this class C {public :C() {x=0;} private:int x;}; IS SAME WITH class C {public :C() {this->x=0;} private:int x;}; CS116 SENEM KUMOVA METİN30

The Pointer Constant this class Person {public : Person( string & name) { this->name=name; } string getName(){return name; // return this->name } private: string name;}; void main() { string n(“Joe”); Person p(n); cout<<n<<“ “<<p.getName();} CS116 SENEM KUMOVA METİN31

Using this pointer to enable cascaded function calls // Person.h class Person {public : Person( string & n, int a) { setPerson(n,a); } Person & setPerson(string & n, int a) {setAge(a); setName(n); return * this; /*enables cascading*/ } Person & setName(string & n) { name=n; return * this; /*enables cascading */} Person & setAge(int a) { if(age>0) age=a; else age=0; return * this; /*enables cascading*/ } void print() {cout<< name<<“ –”<< age<<endl;} private:string name; int age;}; CS116 SENEM KUMOVA METİN32

Using this pointer to enable cascaded function calls #include #include “Person.h” using namespace std; int main() { Person p; string s=“Mary”; string q=“Joe”; p.setName(s).setAge(10); p.print(); p.setPerson(q,12).print(); } CS116 SENEM KUMOVA METİN33