Unit I Objects & Classes in C++:Declaring & using classes,Constructors, Objects as function arguments, Copy Constructors, Static class data, Arrays of.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class Examples: “hello”, “high school”, “H2O”. Typical.
True or false A variable of type char can hold the value 301. ( F )
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Constructors & Destructors Review CS 308 – Data Structures.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 C++ Structures Starting to think about objects...
C++ Classes & Object Oriented Programming. Object Oriented Programming  Programmer thinks about and defines the attributes and behavior of objects. 
Review of C++ Programming Part II Sheng-Fang Huang.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 C++ is an object oriented programming language.  C++ is an extension of C with a major addition of the class construct feature.  C++ is superset of.
C++ Review CS 302 – Data Structures Review Topics Calling functions by value or reference Pointers and reference variables Static and dynamic arrays.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
C++ Review (3) Structs, Classes, Data Abstraction.
Chapter 10 Introduction to Classes
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Object Oriented Programming (OOP) Lecture No. 8. Review ► Class  Concept  Definition ► Data members ► Member Functions ► Access specifier.
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
CONSTRUCTOR AND DESTRUCTORS
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Constructors & Destructors, Proxy Classes, Friend Function and example of static member.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
1 Strings in C++ The string Class Definition of Strings How to declare strings in C++: the string class Operations on strings –Concatenation, comparison.
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.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Classes II Lecture 7 Course Name: High Level Programming Language Year : 2010.
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Learners Support Publications Constructors and Destructors.
Constructors And Destructors. 2 Constructor Special Member Function used for Initialization -- Same Name as the Class Name Special Member Function used.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Constructors and Destructors
Class and Objects UNIT II.
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.
Andy Wang Object Oriented Programming in C++ COP 3330
Review: Two Programming Paradigms
Concepts and Basics of C++ Programming
Constructors & Destructors
This technique is Called “Divide and Conquer”.
Concepts and Basics of C++ Programming
C++ Classes & Object Oriented Programming
Starting to think about objects...
Constructors and destructors
Constructors and Destructors
Classes and Objects.
9-10 Classes: A Deeper Look.
Introduction to Classes and Objects
Submitted By : Veenu Saini Lecturer (IT)
CS410 – Software Engineering Lecture #5: C++ Basics III
9-10 Classes: A Deeper Look.
Presentation transcript:

Unit I Objects & Classes in C++:Declaring & using classes,Constructors, Objects as function arguments, Copy Constructors, Static class data, Arrays of Objects, C++ String class

Functions  Function declaration ◦ return-type function-name (argument-list); ◦ void show(); ◦ float volume(int x,float y,float z);  Function definition return-type function-name(argument-list) { statement1; statement2; }  Function call ◦ function-name(argument-list); ◦ volume(a,b,c);

Functions Parameter Passing  Pass by value  Pass by reference Pass By ValuePass By Reference void foo(int y) { cout << "y = " << y << endl; } int main() { foo(5); // first call int x = 6; foo(x); // second call foo(x+1); // third call return 0; } void foo(int &y) // y is now a reference { cout << "y = " << y << endl; y = 6; cout << "y = " << y << endl; } int main() { int x = 5; cout << "x = " << x << endl; foo(x); cout << "x = " << x << endl; return 0; }

Function Overloading C++ allows to use the same function name to create functions that perform a variety of different tasks. This is know as function polymorphism in OOP. int add (int a, int b); //prototype 1 int add (int a, int b, int c); //prototype 2 double add (double x, double y);//prototype 3 double add (int p, double q);//prototype 4 double add (double p, int q); //prototype 5 add(5,10);//uses prototype 1 add(15,10.0);//uses prototype 4 add(12.5,7.5); //uses prototype 3 add(5,10,15); //uses prototype 2 add(0.75,5); //uses prototype5

Classes and Objects  Class is a way to bind the data and procedures that operates on data.  Class declaration: class class_name { private: variable declarations;//class function declarations;//members public: variable declarations;//class function declarations;//members };//Terminates with a semicolon

Classes and Objects Within the body, the keywords private: and public: specify the access level of the members of the class.  the default is private. Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section. Class members that have been declared as private can be accessed only from within the class. Public class members can be accessed from outside the class also.

Class Example This class example shows how we can encapsulate (gather) a circle information into one package (unit or class) class Circle { private: double radius; public: void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; No need for others classes to access and retrieve its value directly. The class methods are responsible for that only. They are accessible from outside the class, and they can access the member (radius)

Classes and Objects Objects are run time instance of a class. Class is a representation of the object, and Object is the actual run time entity which holds data and function that has been defined in the class. Object declaration: class_name obj1; class_name obj2,obj3; class class_name {……}obj1,obj2,obj3;

Classes and Objects  Accessing class members ◦ Object-name.function-name(actual-arguments); ◦ obj1.setdata(100,34.4);  Defining Member Functions ◦ Outside the class definition. return-type class-name::function-name (argument declaration) { Function body; } ◦ Inside the class definition. Same as normal function declaration.

An example: Classes and Objects

Classes and Objects  Object as arrays class employee { char name [30]; float age; public: void getdata(void); void putdata(void); }; employee manager[3];//array of manager employee worker[75];//array of worker Manager[i].putdata(); This program will create an array, takes the values for each of the element and displays it.

Constructors and Destructors In order to behave like built-in data types, the derived-data types such as ‘objects’ should automatically initialize when created and destroyed when goes out of scope. For this reason C++ introduces a special member functions called constructor and destructor to automatically initialize and destroy the objects.

Constructor Constructors are used to initialize the objects. Constructor is a special kind of function which is the member of the class. The name of the constructor is same as the name of the class. Constructor is automatically called whenever an object is created. Constructors DO NOT have a return value. If no constructor is defined by the user, the compiler supplies the default constructor(with no parameters).

Constructors Characteristics  Declared in the public section.  Invoked automatically when the objects are created.  Do not have return type.  Cannot be inherited. Though a derived class can call the base class constructor.  Can have default arguments.  Cannot be virtual.  We cannot refer to their addresses.  An object with a constructor (or destructor) cannot be used as a member of a union.  They make ‘implicit calls’ to the operators ‘new’ and ‘delete’ when memory allocation is required.

Types of Constructors Default Constructor. Parameterized Constructor. Copy Constructor.

Constructors Parameterized Constructors class integer { int m,n; public: integer (); integer(int x, int y); …. }; integer :: integer(int x,int y){ m=x;n=y;} integer num1 = integer(0,100);//explicit call int num1(0,100);//implicit call

Copy Constructors It is used to declare and Initialize an object from another object. It takes the reference to an object of the same class as itself as an argument. The process of initializing through a copy constructor is called as copy initialization. A copy constructor has the following general function prototype: class_name (class_name &var);

Example Copy Constructor Class Student { Int x; public: Student() { x=10; } Student(int a) { x=a; } Student(student &s) { x=s.x; } void Display() { Count<<x;} }; int main() { Student s3; Student s1(100); //object s1 is created and initialized Student s2(s1); //copy constructor called cout<<“x of s1=”<<s1.Display(); cout<<“x of s2=”<<s2.Display(); cout<<“x of s3=”<<s3.Display(); }

Constructors Multiple Constructors class integer { int m,n; public: integer(void); integer(int x, int y); …. }; integer :: integer(void){ m=0;n=0;} integer :: integer(int x,int y){ m=x;n=y;}

Constructor Overloading #include class Overclass { public: int x; int y; Overclass() { x = y = 0; } Overclass(int a) { x = y = a; } Overclass(int a, int b) { x = a; y = b; } }; int main() { Overclass A; Overclass A1(4); Overclass A2(8, 12); cout << "Overclass A's x,y value:: " << A.x << ", "<< A.y << "\n"; cout << "Overclass A1's x,y value:: "<< A1.x << ","<< A1.y << "\n"; cout << "Overclass A2's x,y value:; "<< A2.x << ", "<< A2.y << "\n"; return 0; }

Destructor A destructor is the complement of the constructor that is, it is used to destroy the objects. The objects are destroyed in order to deallocate the memory occupied. The name of the destructor is the same as the constructor and is preceded by a ‘ ~ ’ (tilt) operator. A destructor for objects is executed in the reverse order of the constructor functions. Eg. ~student() { }

What is a destructor? It is a member function which deletes an object. A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called A destructor has: (i) the same name as the class but is preceded by a tilde (~) (ii) no arguments and return no values

class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor }; string::string(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); } string::~string() { delete []s; }

Comments on destructors If you do not specify a destructor, the compiler generates a default destructor for you. When a class contains a pointer to memory you allocate, it is your responsibility to release the memory before the class instance is destroyed.

Static Class Data If a data item in a class is declared as static, then only one such item is created for the entire class, no matter how many objects there are. A static data item is useful when all objects of the same class must share a common item of information. A member variable declared static has properties similar to normal static variable.

Static data members The static data member is initialized to zero when the first object of its class is created. No other initialization takes place. Memory is allocated for static variables only once for the entire class and is shared by all objects. It is visible only within the class, but its lifetime is the entire program. The type and the scope of each static member variable must be defined outside the class definition. This is because static members are stored separately rather than as a part of an object. They are also termed as class variables.

Example Class foo { Static int count; //declaration only public: foo() { count++;} Void getcount() { return count;} }; Int foo::count=0; //definition of count Int main() { foo f1,f2; cout<<“Count is”<<f1.getcount(); //each object sees the same cout<<“Count is”<<f1.getcount(); //value }

Static member functions Provide a very generic functionality that doesn’t require us to instantiate the class, i.e. static member functions declared in the public part of a class declaration can be accessed without specifying an object of the class. Can access only static members (functions or data members). Cannot be a const member function. A static member function can be called using the class name (instead of its object) as follows: Class_name:: function_name;

Static member functions #include class Data { static int count; int i; public: void setData() { i = ++count; } void showData() { cout<<”object “<<i<<”\n”; } static void showCount() { cout<<”count :”<<count<<”\n”; } }; int Data::count; int main() { Data d1,d2; d1.setData(); d2.setData(); Data::showCount(); Data d3; D3.setData(); Data:: showCount(); d1.showData(); d2.showData(); d3.showData(); return 0; }

Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. A syntax for declaration of an array type name [elements]; Eg. int add[5]; Initializing an array Eg. int add[5] = { 16, 2, 77, 40, }; Accesing an array, name[index]. Eg. billy[2] = 75; a = billy[2];

// arrays example #include using namespace std; int billy [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; }

Array of objects Array of objects is group of object residing in continuous memory location and accessible using the same name. An array of objects behaves like any other array and can be accessed using the index i.e the dot(.) operator.

Arrays of object #include using namespace std; class Employee { char name[20]; int age; public: void getData() { cout >name; cout >age; } void putData() { cout<<”Name :”<<name<<”\n”; cout<<”Age :”<<age<<”\n”; } }; int main() { Employee manager[3]; for(int i=0;i<3;i++) { cout<<”Enter details of manager”<<i<<”\n”; manager[i].getData(); } for(i=0;i<3;i++) { cout<<”Manager”<<i<<”\n”; manager[i].putData(); } return 0; }

Passing Objects in Functions An object may be used as a function arguments. Eg.class X { public: void func(X x) {} }; int main() { X a,b; a.func(b); } Note: to avoid expensive duplication and to let other functions use the same object as the calling function.

Time Class Example (passing object as function Argument) class time { int hrs, mins, sec; public: time( ): hrs(0),mins(0),sec(0) { } time(int h, int m=0, int s=0) { hrs = h; mins = m; sec = s; } void getTime(); void showTime(); void addTime(time,time); }; void time :: getTime() { cout >hrs; cout >mins; cout >sec; } void time::showTime() { cout<<hrs<<”:”<<mins<<”:”<<sec<<”\n“; } void time::addTime(time t1,time t2) { sec=(t1.sec+t2.sec) mins=sec/60; mins=mins+t1.mins+t2.mins; hrs=mins/60; mins=mins%60; hrs=hrs+t1.hrs+t2.hrs; } int main() { Time t1, t2(5,45,54), t3; t3.getTime(); t3.addTime(t1,t2); cout<<”t1 : “; t1.showTime(); cout<<”t2 : “; t2.showTime(); cout<<”t3 : “; t3.showTime(); }

C-string In C++ two kinds of strings are commonly used, C-string and strings that are object of the string class. C-strings are arrays of type character. #include #include //for setw using namespace std; int main() { const int MAX = 20; //max characters in string char str[MAX]; //string variable str char str1[]="This is a string variable"; //const string cout <<"\nEnter a string: "; Cin.get(str,Max); //gets string with a blankspace cin >> setw(MAX) >> str; //put string in str, // no more than MAX chars cout << "You entered: "<< str << endl; cout<<“The constant string with values:”<<str1; return 0; }

The string Class in C++ CS C++ has a library Include it in your programs when you wish to use strings: #include In this library, a class string is defined and implemented It is very convenient and makes string processing easier than in C

Definition of Strings CS Generally speaking, a string is a sequence of characters Examples: “hello”, “high school”, “H2O”. Typical desirable operations on strings are:  Concatenation: “high”+“school”=“highschool”  Comparisons: “high”<“school” // alphabetical  Finding/retrieving/modifying/deleting/inserting substrings in a given string

Declaration of strings CS The following instructions are all equivalent. They declare x to be an object of type string, and assign the string “high school” to it:  string x(“high school”);  string x= “high school”;  string x; x=“high school”;

Operations on strings (Concatenation) CS Let x and y be two strings To concatenate x and y, write: x+y string x= “high”; string y= “school”; string z; z=x+y; cout<<“z=“<<z<<endl; z =z+“ was fun”; cout<<“z=“<<z<<endl; Output: z=highschool z= highschool was fun

Comparison Operators for string Objects CS We can compare two strings x and y using the following operators: ==, !=,, >= The comparison is alphabetical The outcome of each comparison is: true or false The comparison works as long as at least x or y is a string object. The other string can be a string object, a C-style string variable, or a double-quoted string.

Example of String Comparisons CS string x= “high”; char y[]= “school”; char *p = “good”; If (x<y) cout<<“x<y”<<endl; If (x<“tree”) cout<<“x<tree”<,endl; If (“low” != x) cout<<“low != x”<<endl; if( (p>x) cout x”<<endl; Else cout<<“p<=x”<<endl; Output: x<y x<tree low != x p>x

Getting a string Object Length & Checking for Emptiness CS To obtain the length of a string object x, call the method length() or size(): To check of x is empty (that is, has no characters in it): int len=x.length( ); --or-- int len=x.size( ); bool x.empty();

Finding string objects n = String_object.find (string) – searches for the string passed as parameter in the String_object and returns its position. Ex. n=s1.find(“Hello”); n = String_object.find_first_of (group_of_chars) – looks for any of a group of characters and returns the position of the first one it finds. Ex. n=s1.find_first_of(“spde”); Here it looks for any of the groups ‘s’ ‘p’ ‘d’ ‘e’ and returns its position. n = String_object.find_first_not_of (group_of_chars) – finds the first character in its string that is not one of the specified group. findr() which scans the string backwards. find_last_of() which finds the last character matching one of the group of characters find_last_not_of() which finds the last character in its string that is not one of the specified group.

String functions for finding string //finding substrings in string objects #include using namespace std; int main() { string s1 = “In Xanadu did Kubla Kahn a stately pleasure dome decree”; int n; n = s1.find(“Kubla”); cout << “Found Kubla at “ << n << endl; n = s1.find_first_of(“spde”); cout << “First of spde at “ << n << endl; n = s1.find_first_not_of(“aeiouAEIOU”); cout << “First consonant at “ << n << endl; return 0; } Output Found Kubla at 14 First of spde at 7 First consonent at 1 Other funtion are rfind() Find_last_of() Find_last_not_of()