Skip to main content

Creation and Behavior of software Objects

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 looks just like a struct, and indeed they are almost equivalent. By convention we always use class for abstract data types and only use struct for ‘ordinary data structures’ that don’t have member functions. The only difference between class and struct is that the default access control for members is private in the former and public in the latter.
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);
Note, however, that a function differing only by return type is illegal (it is legal to use different a return type with a different argument list, though) :
int f();  //error; differs from void f(); above only by return type 
int f(float f);  //fine. unique signature
You can overload the member functions in a class.

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 function
int IntSet::equal(IntSet &s2);
in the class IntSet, which could be used as follows:
if s1.equal(s2)
Another way of doing this is to overload the C++ "==" operator in the class IntSet. The same functionalily can be coded as:
if (s1==s2)
The C++ Operators which can be overloaded are arithmetic, logical, relational operators, as well as call(), subscripting[], dereferencing ->, assignment =, the extraction <<>> operators.

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 hours

Problem 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
}
Refer: http://www.fredosaurus.com/notes-cpp/misc/random.html
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:
  1. Return the x coordinate or the y coordinate
  2. Set the x coordinate or the y coordinate
  3. Return the distance from the origin, formula is sqrt(x2 + y2)
  4. Input a point as two floating point numbers
  5. Output a point in the format (2.1,-4.3)
Write a short test main function for your class.
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:
  1. Return the hours, minutes or seconds
  2. Return the total seconds using a cast operator overload to type long
  3. Set the hours, minutes or seconds
  4. Automatically convert an integer to a time, interpreting the integer value as the number of seconds
  5. Input a time as three integers in the format hh:mm:ss
  6. Output the time in the format hh:mm:ss
  7. Add a specified number of seconds to a time
  8. Overload the operator = for assignment and == for equality.
Write a short test main function for your class.
Name the program as: Time.cpp

Comments

Popular posts from this blog

Mini Project - Railway Reservation System

Module 1 Overview Railway Reservation System-(RRS) Project is developed to help students learn and realize capability of C programming language, and appreciate procedural approach of developing a system. RRS helps users reserve/cancel berths, search for trains, check reservation/cancellation history, etc... On the other hand it helps the railway reservation officers to prepare reservation charts, organize train schedules, etc... RRS provides two types of log-ins one is the User log-in for railway customers and the other one is Admin log-in for railway reservation officers. Project is divided into 10 modules of four hours duration each. All the modules will give exactly what to develop in the 4 hour time frame. Since most of the modules are inter-related it is important to keep track of the previous code. After submission it is allowed to make changes in the previous code to suit / integrate well to the system. Before we start the project, we need to make the followin...

Inheritance

Week 1 - M5 : Inheritance Learning Objectives At the end of this module, you will be able to Understand the implementation of inheritance in C++ Override the base class members Access overridden base class members using the scope resolution operator Understand the concept of base class initialization Introduction Inheritance The philosophy behind inheritance is to portray things as they exist in the real world. As inheritance is found in real world, it is important feature of OO programming. Inheritance has many advantages, the most important of them being the resuability of code. Once a class is defined and debugged, it can be used to create new subclasses. The reuse of existing class saves time and effort. The Class from which another class is derived is called the base class . The class which inherits the properties of the base class is called the derived class . Each instance of the derived class includes all the members of the base class. Since...