Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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

2 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);

3 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; }

4 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

5 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

6 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.

7 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)

8 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;

9 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.

10 An example: Classes and Objects

11 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.

12 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.

13 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).

14 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.

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

16 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

17 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);

18 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(); }

19 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;}

20 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; }

21 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() { }

22 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

23 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; }

24 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.

25 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.

26 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.

27 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 }

28 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;

29 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; }

30 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, 12071 }; Accesing an array, name[index]. Eg. billy[2] = 75; a = billy[2];

31 // 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; }

32 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.

33 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; }

34 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.

35 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(); }

36 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; }

37 The string Class in C++ CS 103 37 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

38 Definition of Strings CS 103 38 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

39 Declaration of strings CS 103 39 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”;

40 Operations on strings (Concatenation) CS 103 40 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

41 Comparison Operators for string Objects CS 103 41 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.

42 Example of String Comparisons CS 103 42 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

43 Getting a string Object Length & Checking for Emptiness CS 103 43 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();

44 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.

45 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()


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

Similar presentations


Ads by Google