Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1
Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g int and double. However, real programs have to deal with more complicated objects e.g complex numbers, dates and times, matrices, 4-vectors Typically these are composites of the basic types for which we want to define some set of rules e.g addition of complex numbers. We would like to be able to write something like: Complex a,b,c;...... c = a + b; where a,b,c represent complex numbers. Fortunately C++ allows one to do this :) Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 2
Introduction to Classes In C++ new user-defined data types can be declared by using classes. A class can be thought of as a collection of one or more variables together with their associated functions (methods). In order to define such a new data type one uses the class construct. (Usually in a header file) one would write a definition of the form: class Example { [private:] member_1 member_2;... [public:] member_3; member_4;... }; Here member_1...member_n is a declaration of a member variable (which may be of another class type) or a member function. The keywords private and public denote access (more about this later). Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 3
Introduction to Classes Let us consider as a concrete example a class to represent dates. Its declaration could look like class Date{ public: unsigned day; unsigned month; unsigned year; void Set(unsigned d, unsigned m, unsigned y); void Print(); }; This class has 3 (public) data members, each being an unsigned int and 2 (public) member functions. Such a class declaration is usually found in a.h file. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 4
Introduction to Classes Member Function Implementations The functions which are prototyped in a class declaration must be defined. As usual these are normally placed in a.cpp file. In order to distinguish a class member function from a normal function one uses the :: (scope resolution) syntax. e.g. for the Date class one would define: void Date::Set(unsigned d, unsigned m, unsigned y) { day =d; month=m; year =y; } void Date::Print() { cout<<"date is "<<day<< "-" <<month<< "-" << year << endl; } N.B. The class member variables ( day, month, year ) are used as normal variables within member functions. They are NOT declared within the member functions! Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 5
Introduction to Classes Using Class Objects A class declaration provides a new user-defined type. This is demonstrated in the example program date1.cpp Once we have this we can create objects of the particular class type. e.g. Date d; Declares d to be an object of type class Date. Notice the distinction between a class and an object. We say that an object is an instance of a class. The relationship is the same as that between a variable and a data type. Accessing the public members (functions and data) from outside the class scope requires the dot. operator. e.g. d.set( 24, 2, 1998); cout << "year is " << d.year << endl; d.print(); A second example of using a very simple class is the example rect1.cpp, which shows how one can use a class to represent rectangles. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 6
Public and Private members Public and Private Members The key words public and private denote access to the members. private variables my only be assigned to or read by member (or friend) functions. private member functions may only be called by other member functions. public members have no such restrictions. N.B. The default access is private The Data Hiding Paradigm One important principle of Object Oriented programming is the idea of Data Hiding. This can be achieved by always doing the following: Make all data members private Interact with an object only via a well defined set of (member) interface functions. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 7
Public and Private members By applying the data hiding paradigm one can re-write the Date class (see date2.cpp ) class Date{ unsigned day; unsigned month; unsigned year; public: void Set(unsigned d, unsigned m, unsigned y); void Print() const; unsigned Day() const { return day; } unsigned Month() const { return month; } unsigned Year() const { return year; } }; Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 8
Public and Private members Now that the data members are private we have to provide a set of accessor functions: (Day(), Month(), Year() ) which provide an interface to Date objects. Here we have used two new features: the keyword const after a function prototype declares that a member function does not modify any of the member data. The second new feature we have used is to in-line the accessor functions. This is where the function definition is placed in the class declaration. This is commonly used for trivial (one or two statements say) functions which can then be optimized by the compiler. A second example is rect2.cpp Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 9
Constructors and destructors Constructors and Destructors For the Date class we have used the member function Set to initialize the member data. More generally when one creates an object one always needs to ensure that it is in some well defined initial state. This task is so common that a special function, called a constructor is provided for every class to facilitate this. The constructor takes the same name as the class and is called whenever an object of a class is created. If one does not explicitly provide a constructor a default constructor is provided by the compiler which takes no arguments and does not initialize any member data. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 10
Constructors and destructors Replacing the Set function by a constructor the Date declaration becomes: class Date{ unsigned day; unsigned month; unsigned year; public: Date(unsigned d, unsigned m,unsigned y); void Print() const; unsigned Day() const { return day; } unsigned Month() const { return month; } unsigned Year() const { return year; } }; Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 11
Constructors and destructors and the definition of the constructor could be: Date::Date(unsigned d, unsigned m,unsigned y) { day =d; month=m; year =y; } Notice that the constructor has NO return type. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 12
Constructors and destructors Once a constructor has been declared object creation can only take place by providing the correct number of arguments. For example, to create Date objects we have to provide the 3 arguments e.g. Date d( 9, 3, 1999); This ensures Date objects can only be created with their 3 data members initialized. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 13
Constructors and destructors The initiation of member data is so common that the is also a special syntax. An in-line declaration of the Date constructor could be:... Date(unsigned d, unsigned m,unsigned y):day(d),month(m),year(y) {}... The initialisation of the member data takes place before the constructor body. It is possible, and is fairly common, to overload constructors. For example, one might provide a second version of the Date constructor which takes no arguments and initializes the member data to correspond to todays date. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 14
Constructors and destructors Destructors There is also a special function called a Destructor, which is called whenever an object is destroyed (e.g. goes out of scope). This member function takes the special name ~classname where classname is the name of the class. e.g. for the Date class one could have the in-line destructor:... ~Date(){}... Destructors take no arguments and have no return value. Again, a default version (which does nothing) is supplied by the compiler if one isn't explicitly declared. It is not possible to overload destructors. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 15
Constructors and destructors Copy constructor There is a third special function provided by the compiler called the Copy Constructor (see p462). This is an overloaded form of the constructor which is called whenever a copy of an object is needed. For example: Date a = b; It is also implicitly used whenever an object is passed by value as a function argument or as a return value (there is also a default copyassignment function). By default this makes a simple byte-wise copy of the member data. Which is usually fine unless an object contains pointers. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 16
Constructors and destructors An explicit definition of a copy constructor (which is not actually needed in this case) could be: Date::Date(const Date& rhs) { day =rhs.day; month=rhs.month; year =rhs.year; } This creates a new Date object, with its member data initialized to be the same as an existing object. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 17
Friend Functions Friend Functions Sometimes it is necessary to allow a non-member function to have access to some of the private members of a class. Rather than making the members public, or creating extra accessor functions one can declare a function to be a friend A typical friend function several class objects as arguments. For example, consider a function which takes two objects and constructs a new Rectangle with width and height equal to the larger of the two quantities for the two rectangles. Such a function might be defined: Rectangle Surround(const Rectangle& a, const Rectangle& b) { double w=a.width; double h=a.height; if( b.width > w ) w = b.width; if( b.height > h ) h = b.height; return Rectangle(w,h); } Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 18
Friend Functions Notice here, that a Rectangle is returned by value (using the copy constructor). This function clearly needs to access the private data members, so it needs to be declared to be a friend. This can be done by adding the declaration: friend Rectangle Surround(const Rectangle& a, const Rectangle& b); to the Rectangle class declaration. See rect4.cpp. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 19
Introduction to Classes Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 20