CONSTRUCTORS the Class Designer Can Guarantee

CONSTRUCTORS the Class Designer Can Guarantee

Object Oriented Programming License: http://creativecommons.org/licenses/by-nc-nd/3.0/ Object Oriented Programming Default Constructor: Initializing Class Objects: CONSTRUCTORS A constructor that defaults all its arguments or requires no arguments, i.e. a constructor that can be invoked with no arguments. The class designer can guarantee initialization of every object by providing a special member function called the constructor . class Point{ // Declaration Point Class int x,y; // Attributes: x and y coordinates The constructor is invoked automatically each time an object of that class is public: created (instantiated). Point(); // Declaration of the default constructor These functions are used to (for example) assign initial values to the data bool move(int, int); // A function to move points void print(); // to print coordinates on the screen members, open files, establish connection to a remote computer etc. }; The constructor can take parameters as needed, but it cannot have a return // Default Constructor value (even not void ). Point::Point() The constructor has the same name as the class itself. { x = 0; // Assigns zero to coordinates There are different types of constructors. y = 0; For example, a constructor that defaults all its arguments or requires no } arguments, i.e. a constructor that can be invoked with no arguments is called // -------- Main Program ------------- default constructor. int main() See Example e41.cpp { In this section we will discuss different kinds of constructors. Point p1, p2; // Default construct is called 2 times Point *ptr; // ptr is not an object, constructor is NOT called ptr = new Point; // Object is created, default constructor is called http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.1 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.2 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming // A constructor with Parameters Constructors with Parameters: // Points may not have negative coordinates Like other member functions, constructors may also have parameters. Point::Point(int x_first, int y_first) Users of the class (client programmer) must supply constructors with { necessary arguments. if ( x_first < 0 ) // If the given value is negative x = 0; // Assigns zero to x class Point{ // Declaration Point Class else int x,y; // Properties: x and y coordinates x = x_first; public: if ( y_first < 0 ) // If the given value is negative Point(int, int); // Declaration of the constructor y = 0; // Assigns zero to y bool move(int, int); // A function to move points else void print(); // to print coordinates on the screen y = y_first; }; } // -------- Main Program ------------- This declaration shows that the users of the Point class have to give two integer int main() arguments while defining objects of that class. { Point p1(20, 100), p2(-10, 45); // Construct is called 2 times Example: Point *ptr = new Point(10, 50); // Construct is called once In the following example, it is assumed that the points are not allowed to have Point p3; // ERROR! There is not a default constructor negative coordinates. : } See Example e42.cpp http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.3 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.4 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming Multiple Constructors Default Values of Constructor Parameters The rules of function overloading are also valid for constructors. So, a class Like other functions, parameters of constructors may also have default values. may have more than one constructor with different type of input parameters. class Point{ public: Point::Point() // Default constructor Point (int = 0 , int = 0 ); // Default values must be in the declaration { : ............... // Body is not important }; } Point::Point (int x_first, int y_first) { Point::Point(int x_first, int y_first) // A constructor with parameters if ( x_first < 0 ) // If the given value is negative { x = 0; // Assigns zero to x ................. // Body is not important else x = x_first; } if ( y_first < 0 ) // If the given value is negative y = 0; // Assigns zero to y Now, the client programmer can define objects in different ways: else y = y_first; Point p1; // Default constructor is called } Pointp2(30,10); // Constructor with parameters is called Now, client of the class can create objects as follows: The following statement causes an compiler error, because the class does not Point p1(15, 75); // x=15, y=75 include a constructor with only one parameter. Point p2(100); // x=100, y=0 This function can be also used as a default constructor Point p3(10); // ERROR! There isn't a constructor with one parameter Pointp3; //x=0,y=0 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.5 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.6 http://www.buzluca.info http://www.buzluca.info 1 Object Oriented Programming License: http://creativecommons.org/licenses/by-nc-nd/3.0/ Object Oriented Programming Initializing Arrays of Objects If the class has a default constructor the programmer may define an array of When an array of objects is created, the default constructor of the class is objects as follows: invoked for each element (object) of the array one time. Point array[5]= { 10 , 20 , {30,40} }; // An array with 5 elements Point array[10]; // Default constructor is called 10 times Here, an array with 5 elements has been defined, but the list of initial values To invoke a constructor with arguments, a list of initial values should be used. contains only 3 values, which are sent as arguments to the constructors of the // Constructor ( can be called with zero, one ore two arguments) first three elements. Point (int = 0, int = 0) For the last two elements, the default constructor is called. List of initial values // Array of Points Point array[]= { 10 , 20 , {30,40} }; // An array with 3 elements (objects) To call the default constructor for an object, which is not at the end of the or to make the program more readable array: Point array[]= { Point(10) , Point(20) , Point(30,40) }; // An array with 3 objects Point array[5]= { 10 ,20 , Point() , {30,40} }; // An array with 5 elements array[2] array[4] Three objects of type Point have been created and the constructor has been invoked Here, for objects and the default constructor is invoked. three times with different arguments. Objects: Arguments: Following statements cause compiler errors: array[0] x_first = 10 , y_first = 0 Point array[5]= { 10 , 20 , , {30,40} }; // ERROR! Not readable array[1] x_first = 20 , y_first = 0 array[2] x_first = 30 , y_first = 40 Point array[5]= { 10 , 20 , () , {30,40} }; // ERROR! Not readable http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.7 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.8 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming Constructor Initializers The solution is to use a constructor initializer. Instead of assignment statements constructor initializers can be used to class C{ initialize data members of an object. const int CI; // constant data member int x; // nonconstant data member Specially, to assign initial value to a constant member using the constructor public: initializer is the only way. C() : CI(0) // initial value of CI is zero Consider the class: { x = -2; } class C{ }; const int CI; // constant data member int x; // nonconstant data member All data members of a class can be initialized by using constructor initializers. public: class C{ C( ) { // Constructor const int CI; // constant data member x = 0; // OK x not const int x; // nonconstant data member // CI = 0; // ERROR! CI is const public: } C(int, int); }; }; The example below is not correct, either: C::C( int a, int b ) : CI(a), x(b) // Definition of the Constructor class C{ { } // The body may be empty // const int CI = 10 ; // ERROR! int main() { int x; // nonconstant data member C obj1(-5, 1); // Objects may have different const values }; C obj2(0, 18); http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.9 http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr. Feza BUZLUCA 4.10 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming DESTRUCTORS // Constructor : copies the input character array that terminates with a null character • The destructor is called automatically // to the contents of the string 1. when each of the objects goes out of scope or 2. a dynamic object is deleted from memory by using the delete operator. String::String(const char *in_data) { • A destructor is characterized as having the same name as the class but with a size = strlen(in_data); // strlen is a function of the cstring library tilde ‘ ~’ preceded to the class name. contents = new char[size +1]; // +1 for null ( '\0' ) character • A destructor has no return type and receives no parameters. strcpy(contents, in_data); // input_data is copied to the contents • A class may have only one destructor. } size String int main() // Test program Example: A user defined class *contents t e x t \0 void String::print() { { class String{ cout << contents << " " << size << endl; String string1("string 1"); int size; // Length (number of chars) of the string } String string2("string 2"); char *contents; // Contents of the string string1.print(); public: // Destructor string2.print(); String(const char *); // Constructor // Memory pointed by contents is given back return 0; // destructor is called twice void print(); // An ordinary member function String:: ~String() } ~String() ; // Destructor { }; delete[] contents; } Actually, the standard library of C++ contains a string class. Programmers don't See Example e43.cpp need to write their own String class. We write this class only to show some concepts. http://www.faculty.itu.edu.tr/buzluca ©1999-2015 Dr.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    5 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us