1 / 45

Object Oriented Programming

Object Oriented Programming. Lecture 3. Constructors Initializer List. One of the most common tasks a constructor carries out is initializing data members Constructor must initialize the count member to 0 e.g ; count() { x = 0; }. Constructors Initializer List.

elmer
Download Presentation

Object Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Programming Lecture 3

  2. Constructors Initializer List • One of the most common tasks a constructor carries out is initializing data members • Constructor must initialize the count member to 0 • e.g; • count() • { x= 0; }

  3. Constructors Initializer List • This is not the preferred approach (although it does work). Here’s how you should • Initialize a data member • e.g; count() : x(0) { } • The initialization takes place following the member function declarator but before the function body. • It’s preceded by a colon. The value is placed in parentheses following the member data.

  4. Constructors Initializer List • If multiple members must be initialized, they’re separated by commas. • The result is the initializer list (sometimes called by other names, such as the member-initialization list). • e.g; TestClass() : m1(7), m2(33), m2(4) ←initializer list • { }

  5. Reasons for Constructors Initializer List The reasons are complex, but have to do with the fact that members initialized in the initializer list are given a value before the constructor even starts to execute But this kind of initializing is important in some situations Actions more complicated than simple initialization must be carried out in the constructor body, as with ordinary functions

  6. Example: #include <iostream> using namespace std; class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(intft, float in) : feet(ft), inches(in) { }

  7. void getdist() { cout << “\nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist() { cout << feet << “\’-” << inches << ‘\”’; } };

  8. int main(intargc, char *argv[]){ Distance dist1(11, 6.25); Distance dist2(dist1); Distance dist3 = dist1; cout<< “\ndist1 = “; dist1.showdist(); cout << “\ndist2 = “; dist2.showdist(); cout << “\ndist3 = “; dist3.showdist(); cout << endl; return 0; }

  9. What is a copy constructor? • It is a member function which initializes an object using another object of the same class. • A copy constructor has the following general function prototype:  class_name (constclass_name); • It is an another way to initialize an object: you can initialize it with another object of the same type. • We don’t need to create a special constructor for this; one is already built into all classes. • It’s called the default copy constructor. • It’s a one argument constructor whose argument is a variable of the same class as the constructor.

  10. Copy Constructor Example #include<iostream.h> #include<conio.h> //--------------------------------------------------------------------------- //copy constructor class test class copyconst { private: int a; public: copyconst(){ } copyconst(int x) { a=x; } void disp_sq() { cout<<"\nSquare of "<<a<<"="<<a*a<<endl; } ~copyconst() { cout<<"destructor"<<endl;} };

  11. int main(intargc, char *argv[]) { copyconstobj(5); copyconst obj2(obj); copyconst obj3=obj2; obj.disp_sq(); obj2.disp_sq(); obj3.disp_sq(); system("PAUSE"); return 0; }

  12. Constructor Overloading Constructor overloading refers to the use of more than one constructor with same name but different number of arguments. Each constructor is called according to its signature matching Example program: #include<iostream.h> #include<conio.h> class constructor { private:

  13. int x; public: constructor() { x=0; } constructor(int a) { x=a; } constructor(float a) { x=a; }

  14. void input(int y) { x=y; } void display() { cout<<x<<“\n”; } };

  15. int main(intargc, char *argv[]) { constructor obj1; constructor obj2(10); Constructor obj3(4.5); cout<<“After invoking constructors value of x for obj1 and obj2”; obj1.display(); obj2.display(); Obj3.display(); cout<<“After invoking input() value of x is for obj1 and obj2”; obj1.input(50); obj2.input(80); Obj3.input(50.5); obj1.display(); obj2.display(); Obj3.display(); getche(); Return 0; }

  16. Lab Task Write a program which input records of ten employees and then to print it out on the screen. The task should only be done by using constructors. Write a class using constructors to find the factorial of any given integer value.

  17. Functions Overloading C++ enables several functions of the same name to be defined, as long as they have different signatures. This is called function overloading. The C++ compiler selects the proper function to call by examining the number, types and order of the arguments in the call. Function overloading is used to create several functions of the same name that perform similar tasks, but on different data types.

  18. Overloaded functions are distinguished by their signatures. A signature is a combination of a function’s name and its parameter types (in order). The compiler encodes each function identifier with the number and types of its parameters.

  19. Example of overloaded Function without classes #include <iostream.h> using namespace std; int square(int x ) { cout << "square of integer " << x << " is "; return x * x; } float square( float y ) { cout << “Square of float " << y << " is "; return y * y; } intmain(void) { cout << ; cout << square(7)<<endl; cout << square(7.5)<<endl; }

  20. Function overloading example in a class. #include<iostream.h> #include<conio.h> #include<string.h> //--------------------------------------------------------------------------- class ovrlod { private: int a; float b,d; string c; public: void get_data(int x) { a=x; }

  21. void get_data(float y,float z) { b=y; d=z; } void get_data(string z) { c=z; } void display_sq() { cout<<"square of "<<a<<"="<<a*a<<endl; } void display_float() { cout<<"add float values "<<b<<"+"<<d<<"="<<b+d<<endl; }

  22. void display_char() { cout<<"entered char "<<c<<endl; } };

  23. int main() { ovrlod obj; obj.get_data(5); obj.get_data(5.5,5.5); obj.get_data("Tahir"); obj.display_sq(); obj.display_float(); obj.display_char(); getch(); return 0; }

  24. static Class Data • static data member • Only one copy of a variable shared by all objects of a class • “Class-wide” information • A property of the class shared by all instances, not a property of a specific object of the class • Declaration begins with keyword static

  25. static Class Members • static member function • Is a service of the class, not of a specific object of the class • static applied to an item at file scope • That item becomes public only in that program • The static members of the class need to be available from any client code

  26. static Class Members • Use static data members to save storage when a single copy of the data for all objects of a class will suffice. • A class’s static data members and static member functions exist and can be used even if no objects of that class have been instantiated.

  27. An Example of Static Class Data Here’s an example, STATDATA, that demonstrates a simple static data member: // statdata.cpp // static class data #include <iostream> using namespace std; class sta { private: static int count;

  28. public: sta() { count++; } intgetcount() { return count; } }; //-------------------------------------------------------------- intsta::count = 0; //////////////////////////////////////////////////////////////// intmain(void) { Sta f1, f2, f3; //create three objects cout << “count is “ << f1.getcount() << endl; cout<< “count is “ << f2.getcount() << endl; cout<< “count is “ << f3.getcount() << endl; return 0; }

  29. Static Versus automatic member variables

  30. Assignment 1 Write a program in C++ by using a class to copy one string into another string and also to find out the length of the string without using any built-in function. Write a class which can convert temperatures. Such as if we provide Centigrade to Fahrenheit converter or Fahrenheit to Centigrade without using built in functions. Submission Date: Time 1:00pm to 1:30pm Note: No late submission will be accepted

  31. The Scope Resolution Operator • The concept of classes adds new scope rules to those of the C++ language. • You remember that one point of classes is to provide an encapsulation technique • It makes sense that all names declared within a class be treated within their own scope as distinct from external names, function names, and other class names. • This creates the need for the scope resolution operator

  32. Syntax of Scope resolution operator • Return data type [class name]:: function name(argument list) • e.g • void test::hello(); • int test::hello(int x, int y);

  33. Scope resolution operator #include <iostream> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ class test{ private: public: void hello(void); }; void test::hello(void) { std::cout<<"Hello"<<endl; } int main(intargc, char *argv[]) { test obj; obj.hello(); system("PAUSE"); return EXIT_SUCCESS; }

  34. Scope Resolution Operator #include <cstdlib> #include <iostream> using namespace std; class temp { private: int t; public: temp(){}; temp(int x): t(x) { } void sqr(temp); void show() { cout<<"Value in T variable"<<t<<endl; } };

  35. Scope Resolution Operator void temp::sqr(temp num1) { t=num1.t*num1.t; } int main(intargc, char *argv[]) { temp obj; obj.add(5); obj.show(); system("PAUSE"); return EXIT_SUCCESS; }

  36. Passing object As Arguments • Objects can also be passed as arguments to member functions. When an object is passed as an argument to a member function. • Only the name of the object is written in the argument list • The number of parameters and their types must be defined in the member function to which the object is to be passed. • The objects that are passed are treated local for the number function and are destroyed when the control returns to the calling function.

  37. Passing object As Arguments #include <iostream.h> #include<string.h> using namespace std; class test{ private: string name; public: Void get (void) { cout<<“Enter your name”<<endl; Cin>>name; } Void display(test obj) { Cout<<“Your entered name is”<<obj.name<<endl; } };

  38. Passing object As Arguments int main(intargc, char *argv[]) { test temp, obj; temp.get(); obj.display(temp); system("PAUSE"); return EXIT_SUCCESS; }

  39. Passing and Returning object to Functions as Arguments #include <iostream> using namespace std; class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0){ } Distance(intft, float in) : feet(ft), inches(in) { } void getdist() { cout << “\nEnter feet: “; cin>> feet; cout << “Enter inches: “; cin>> inches; }

  40. Passing and Returning object to Functions as Arguments void showdist() { cout << feet << “\’-” << inches << ‘\”’; } Distance add_dist(Distance); }; Distance Distance::add_dist(Distance d2) { Distance temp; temp.inches = inches + d2.inches; if(temp.inches >= 12.0) { temp.inches -= 12.0; temp.feet = 1; } temp.feet += feet + d2.feet; return temp; }

  41. Passing and Returning object to Functions as Arguments int main(intargc, char *argv[]) { Distance dist1, dist3; Distance dist2(11, 6.25); dist1.getdist(); dist3 = dist1.add_dist(dist2); cout<< “\ndist1 = “; dist1.showdist(); cout << “\ndist2 = “; dist2.showdist(); cout << “\ndist3 = “; dist3.showdist(); cout << endl; system("PAUSE"); return EXIT_SUCCESS; }

  42. Four main member Functions in Classes • There are four member functions that the C++ compiler “expects” to be in every class. • Default Constructor • Destructor • Copy Constructor • Assignment Operator If programmer does not write these member functions now-a-days C++ compiler will automatically generates them.

  43. Example #include<iostream.h> Class memberfunc{ private: Int x; public: Void input(int a) {x=a;} void output() { cout<<x<<endl; }};

  44. int main(intargc, char *argv[]) { memberfunc obj1; obj1.input(5); memberfunc obj2=obj1; obj1.output(); obj2.output(); Obj2.input(90); Obj1=obj2; Obj1.output(); Obj2.ouput(); system("PAUSE"); return EXIT_SUCCESS }

  45. Thanks

More Related