Escolar Documentos
Profissional Documentos
Cultura Documentos
hcphap@gmail.com, hcphap@dut.udn.vn
More on Classes
Chapter 2
Session Objectives
Use the scope resolution operator Use dynamic memory allocation with
New Delete
Use pointers to objects Define and use Constructors Define and use Destructors Define the "Const" keyword
The type of member function arguments must exactly match with the type declared in the class specifier.
Important for defining the member functions outside the class declaration.
New
The new operator is used to create a memory space for an object of a class The general syntax of the new operator is:
data_type pointer_variable = new data_type;
For example,
int *p; //pointer to integer type float *f; //pointer to a float type p = new int; //allocates memory for an integer f = new float; //allocates memory for a float
If call to new is successful, it returns a pointer to the space that is allocated. Returns zero if the space is not available or if some error is detected.
New (Contd.)
Same syntax for an object. For example,
Student *stu_ptr; //pointer to an object of type Student stu_ptr = new Student; //points to new Student object
Delete
Object created by new exists until it is explicitly destroyed by delete.
delete pointer_variable;
Allocating Arrays
Allocate blocks consisting of arrays of varying length using a similar technique.
int *ptr;
ptr = new int[100]; delete [] ptr;
Pointers to objects
Pointers can point to objects as well as to simple data types. Declaring a pointer to an object of a particular class is the same as declaring a pointer to a variable of any data type.
Any time you allocate an array of objects using new, you must use [] in the delete statement. Error to delete a variable that has been malloc'ed and it is an error to free a variable that was allocated with new.
Constructors
A constructor is a special member function for automatic initialisation of an object. Has the same name as the class it belongs to. Can declare and define constructors within the class, or declare them within the class and define them outside just as any other member functions.
Constructors (Contd.)
class username { public: username(); //constructor }; username::username() { }
Constructors (Contd.)
class date{ int month, day, year; public: date() //default constructor {day=1; month=1; year=1999;} date(int x) //only day is specified {day=x; month=1; year=1999;} date(int x, int y, int z) //day month year {day=x; month=y; year=z;} };
No return type is used for constructors. Also invoked when local or temporary objects of a class are created. Several constructors provide several ways of initialising a class object.
A default constructor is a constructor that does not have any arguments.
Constructors (Contd.)
As long as the constructors differ sufficiently in their argument types the compiler can select the correct one for each use, as shown in the examples given below. Each example calls a different constructor depending on the value of the argument.
date now; date today(4); date all(23,3,1998);
Destructors
A destructor is a member function that is called automatically when an object is destroyed.
Cannot be directly called from the class. The compiler itself generates a call to a destructor when an object expires.
Same name as the class but with a tilde (~) before the class name.
class username { public: ~username(); //destructor };
//constructor
//destructor
this pointer
Keyword this gives the address of the object, which was used to invoke the member function. Whenever a member function is called, the compiler assigns the address of the object which invoked the function, to the this pointer. Can be used like any other pointer to an object. Can be used to access the members of the object it points to with the use of the arrow operator.
this->age = 5; this->getdata();
Example
void func1(const int index) { index = 5;} //error
Use of this
class Person{ private: int age; public: void display(); }; void Person :: display() { this->age = 25; cout<<this->age; } void main() { Person Jack; Jack.display(); } // same as age=25 // same as cout<<age
Example
class race_cars{ private: static int count: int car_number; char name[30]; public: race_cars(){count++;} //constructor to increment count ~race_cars(){count--;} //destructor to decrement count }; int race_cars::count;
The static data member should be created and initialised before the main() program begins.
Example (Contd.)
void main() { alpha::display_count(); alpha obj1, obj2, obj3; alpha::display_count(); } //before any object //is created //after three //objects created
Even when no object has been created we can directly call the static member using the name of the class and the scope-resolution operator as shown:
alpha::display_count();
Type Conversions
Type conversion is done to convert a variable of a declared type to some other required type.
int count = 7; float average = 15.5; double totalsum = count * average;
Converting by assignment
Typical way of converting a value from one data to another using the assignment operator (=). Data types are considered " higher" or "lower" in the order shown:
Highest lowest Long double >double>float>long>int>char
Implicit or automatic conversion: when two operands of different types appear in the same expression the lower-type variable is converted to the type of the higher-type variable.
Type Casting
Need to convert a value from one type to another where the compiler will not do it automatically.
A typical use of a cast is in forcing a division to return a float when both operands are of the type int.
result = float(21)/5; Other examples: char chs; int x, y, z; float aft; x = int(chs); aft = float(y*z);
Converting by assignment is not recommended since it will truncate the fractional or real parts of a value. Better to explicitly convert one data type to another using the type casting.