Learning Objectives
On successful completion of this module you should be able to:- explain the purpose of a class constructor and identify a default constructor for a class
- explain the purpose of a class destructor and identify a default destructor for a class
- Apply function overloading
- Apply operator overloading
- code and use simple C++ classes using the following facilities:
- public member functions and private data members
- one or more constructors, including where appropriate, a default constructor
- Overloading of functions
- Operator overloading
Introduction
The Class
The class is a data type which specifies the data and the permissible operations on the instance of this class. The set of operations define the interface of the objects of the class. The class definition consists of zero or more data members, which together define the data part and zero or more member functions, which together define the interface. In addition, there are three levels of program access, that are associated with a class.The members (data or functions) can be declared to be
- Private members of the class are hidden and can be accessed only with in the class. Access to them members is denied from out side the class
- Protected members are accessible within the class and to the derived class(to be covered in next modules)
- Public members are visible outside the class and can be accessed from anywhere within the program.
A class consists of data memebers and member functions. Each having different program access level.
The data memebers, specify the attributes/state of the objects of the class. The data members define the name of the attributes and their type.
The member function describes behavior of an object-class and act on state (variables/fields) of an object-class. The member functions collectively define the interface of an object of a class. The special trait about member functions is they can access the private/protected data members (state variables/fields) of their class and manipulate them. No external functions can access the private/protected data members of a class.
The Class Scope
Every class defines the scope for the members in it. The data members of a class may be defined, before they are used in a member functions, or can be used in the member functions, and may be defined later in the class. The data members have the class scope, immaterial of where they are defined in the class.Constructor
A constructor is also a member function, the first function called while creating an object. It could contain initializations to the variables of the object or calling other functions etc. The constructor by nature cannot return any value. The return has to be void. It can however take an argument list. The constructor has the same name as the class but having different argument list.The constructor can be defined within the class definition or outside of it, just as any other member function definition. It can also be defined outside the class and made inline, just as other member functions can be
The constructor which takes no arguments is called the default constructor.
Overloading constructor:When constructor are overloaded, the constructor must vary in the argument list. Upon object creation, that constructor for which there is match between the formal and the actual parameters, is invoked.
Copy constructor
A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. First argument of such constructor is a reference to an object of the same type as being constructed (const or non-const), which might be followed by parameters of any type (all having default values).Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't create one.
Refer: http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html
Destructor
The destructor destroys a previously created object. The destructor takes no arguments and cannot return a value. The destructor has the same name as of the class, except that the name is preceded by a ~ (tilda).Composite Class
A Composite object can be defined as one which consists of other objects.As an example, consider the class Circle as composite object containing an instance of Point, representing the centre and radius which is of type, float. The definition of Point and Circle in this case would be.
class Point{ float x; float y; }; class Circle{ float radius; Point centre; };
Function Overloading
In order to overload a function, a different signature should be used for each overloaded version. A function signature consists of the list of types of its arguments as well as their order. Here's a set of valid overloaded versions of a function named f:void f(char c, int i); void f(int i, char c); void f(string & s); void f(); void f(int i); void f(char c);
int f(); //error; differs from void f(); above only by return type int f(float f); //fine. unique signature
- Refer: http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr312.htm Function Overloading
- Refer for example: http://smart2help.com/e-books/ticpp-2nd-ed-vol-one/Chapter07.html
Operator Overloading
When a class is defined, a set of operations are associated with it which together define the behavior of the instance of the class. So far, mnemonics have been used to name the operation. In some situations, it may be desirable to use operators which have conventional meaning rather than use a name for it. For example, consider the class IntSet, a set of integers class. To check if two instances are equal, one way is to define a member functionint IntSet::equal(IntSet &s2);
if s1.equal(s2)
if (s1==s2)
- Refer: http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc11cplr318.htm Operator Overloading
- Refer for example: http://www.cplusplus.com/doc/tutorial/classes2/
The keyword this
The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself.One of its uses can be to check if a parameter passed to a member function is the object itself.
Resources
Problem Sets
Complete following tasks In 2 hoursProblem Set A
1. Define a class Random to provide random numbers within a range that is specified through the constructor. The class should provide a draw function to get a random number.Use the code given below for the Random Class. You need to write the code in the given program wherever it is commented as write the code here o
#include//For I/O #include// For time() #include// For srand() and rand() using namespace std; class Random{ private: int max; int min; public: Random(){ cout << "Default Random Constructor is called and default values set with Min 10 and Max 20\n"; //Write the code here to set the default values for min 10 and max 20 } Random(int minA, int maxA){ cout << "Random Constructor called with argument of Min"<< minA << " and Max"<<maxA<<"\n"; //Write the code here to set the max and min } int draw(){ int r; srand(time(0)); // Initialize random number generator. r = (rand() % (max - min)) + min; return r; } }; int main(void){ //Write the code here to declare two Instances of Random class and by calling different constructors. //Use cout to call the draw function for each of the Random instance }
Name the program as: PA1_random.cpp
Problem Set B
1. Write a class called Point that is capable of representing the coordinates of a point on a two-dimensional graph. You must permit creation of variables as follows:Point p, q(2.1, -4.3);
The declaration of p above will be for the point (0,0).
Provide the following operations:
- Return the x coordinate or the y coordinate
- Set the x coordinate or the y coordinate
- Return the distance from the origin, formula is sqrt(x2 + y2)
- Input a point as two floating point numbers
- Output a point in the format (2.1,-4.3)
Refer: http://www.cppreference.com/wiki/c/math/start
Name the program as PB1_Point.cpp
Problem Set C
1. Write a class to hold the time of day. You must permit the creation of variables as follows:Time t1, t2(3600), t3(12,00), t4(23, 59, 59);
In this case t1 is set to 00:00:00, t2 to 01:00:00 (3600 seconds), t3 to 12:00:00 and t4 to 23:59:59.
Provide the following operations:
- Return the hours, minutes or seconds
- Return the total seconds using a cast operator overload to type long
- Set the hours, minutes or seconds
- Automatically convert an integer to a time, interpreting the integer value as the number of seconds
- Input a time as three integers in the format hh:mm:ss
- Output the time in the format hh:mm:ss
- Add a specified number of seconds to a time
- Overload the operator = for assignment and == for equality.
Name the program as: Time.cpp
Comments
Post a Comment