C++
CONSTRUCTORS
&
DESTRUCTORS
Introduction
• A constructor in C++ is a special method that is
automatically called when an object of a class is created.
• To create a constructor, use the same name as the class,
followed by parentheses.
Constructors
• A constructor is a special member function which enables an
object to initialize itself when it is created. (In other word, it
is used to initialize all class data members.)
• It is special because its name is same as the class name.
• In C++, Constructor is automatically called when object
create.
• These constructors get invoked whenever an object of its
associated class is created.
• It is called constructor because it constructs the values of
data members of the class.
Constructor- example
class add
{
int m, n ;
public :
add (void) ;
------
};
add :: add (void)
{
m = 0; n = 0;
}
• When a class contains a constructor, it is guaranteed that an
object created by the class will be initialized automatically.
• add a ;
• Not only creates the object a of type add but also initializes
its data members m and n to zero.
continue …
Constructors
• There is no need to write any statement to invoke the
constructor function.
• If a ‘normal’ member function is defined for zero
initialization, we would need to invoke this function for
each of the objects separately.
• A constructor that accepts no parameters is called the
default constructor.
• The default constructor for class A is A : : A ( )
continue …
Characteristics of Constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are
created.
• They do not have return types, not even void and they
cannot return values.
continue …
Characteristics of Constructors
• They cannot be inherited, though a derived class can call
the base class constructor.
• Like other C++ functions, Constructors can have default
arguments.
• Constructors can not be virtual.
continue …
Characteristics of Constructors
• We can not refer to their addresses.
• An object with a constructor (or destructor) can not be used
as a member of a union.
• They make ‘implicit calls’ to the operators new and delete
when memory allocation is required.
continue …
Parameterized Constructors
It is possible to pass arguments to constructors. Typically,
these arguments help initialize an object when it is created. To
create a parameterized constructor, simply add parameters to it the
way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
#include <iostream>
class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Copy Constructor
• A copy constructor is used to declare and initialize an
object from another object.
integer (integer & i) ; (to get value from other constructor)
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is
known as copy initialization.
Copy Constructor
• The statement
I 2 = I 1;
will not invoke the copy constructor.
• If I 1 and I 2 are objects, this statement is legal and assigns
the values of I 1 to I 2, member-by-member.
• A reference variable has been used as an argument to the
copy constructor.
• We cannot pass the argument by value to a copy constructor.
continue …
Dynamic Constructors
• The constructors can also be used to allocate memory while
creating objects.
• This will enable the system to allocate the right amount of
memory for each object when the objects are not of the
same size.
• Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects.
• The memory is created with the help of the new operator.
Destructors
• A destructor is used to destroy the objects that have been
created by a constructor.
• Like constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a
tilde.
eg: ~ integer ( ) { }
• A destructor never takes any argument nor does it return
any value.
• It will be invoked implicitly by the compiler upon exit from
the program – or block or function as the case may be – to
clean up storage that is no longer accessible.
Destructors
• It is a good practice to declare destructors in a program
since it releases memory space for further use.
• Whenever new is used to allocate memory in the
constructor, we should use delete to free that memory.
continue …
OPERATOR
OVERLOADINGAND
TYPE
CONVERSIONS
Introduction
• It is one of the many exciting features of C++.
• C++ has ability to provide the operators with a special meaning
for a data types.
• We can overload (give additional meaning to) all the C++
operators except:
• Class member access operators ( . & .*)
• Scope resolution operators ( : : )
• Size operator (sizeof)
• Conditional operators (? : )
• When an operator is overloaded, its original meaning is not lost
Defining Operator Overloading
• To define an additional task to an operator, we must specify what it
means in relation to the class to which the operator is applied.
• This is done with the help of a special function called operator
function.
return type class-name : :operator op (arg-list)
{
Function body // task defined
}
DefiningOperatorOverloading
• return type is the type of value returned by the specified operation.
• op is the operator being overloaded.
• op is preceded by the keyword operator.
• operator op is the function name.
continue…
DefiningOperatorOverloading
• Operator Function must be either
member function (non-static) Or friend function.
The basic difference :
• A friend function will have only one argument for unary
operators and two for binary operators.
• A member function has no arguments for unary
operators and one argument for binary operators.
• Arguments may be passed either by value or by reference.
continue…
Process of OperatorOverloading
The process of overloading involves the following steps:
• Create a class that defines the data type that is to be used in
the overloading operation.
• Declare the operator function operator op( ) in the public part
of the class. It may be either a member function or a friend
function.
• Define the operator function to implement the required
operations.
continue…
Process of OperatorOverloading
• Overloaded operator functions can be invoked by expressions such
as:
For unary operators: op x or x op
For binary operators: x op y
• op x or x op would be interpreted as
for a friend function:operator op (x)
for a member function: x.operator op ( )
• x op y would be interpreted as
for a friend function:operator op (x,y)
for a member function: x.operator op (y)
continue…
Overloading Unary Operators
Consider a unary minus operator:
• It takes just one operand.
• It changes the sign of an operand when applied to a basic data
item.
• The unary minus when applied to an object should change the
sign of each of its data items.
Overloading Binary Operators
As a rule, in overloading binary operators,
• the left-hand operand is used to invoke the operator function
and
• the right-hand operand is passed as an argument.
Overloading Binary Operators
complex operator+(complex a, complex b)
{
return complex((a.x + b.x),(a.y + b.y));
}
• The compiler invokes an appropriate constructor, initializes an
object with no name and returns the contents for copying into an
object.
• Such an object is called a temporary object.
continue…
Overloading Binary Operators Using
Friends
• Friend function requires two arguments to be explicitly passes to
it.
• Member function requires only one.
friend complex operator+(complex, complex);
complex operator+(complex a, complex b)
{
return complex((a.x + b.x),(a.y + b.y));
}
• We can use a friend function with built-in type data as the left-
hand operand and an object as the right-hand operand.
Manipulation of Strings using
Operators
• There are lot of limitations in string manipulation in C as well as in
C++.
• Implementation of strings require character arrays, pointers
and string functions.
• C++ permits us to create our own definitions of operators that can
be used to manipulate the strings very much similar to other built-
in data types.
• ANSI C++ committee has added a new class called string to the
C++ class library that supports all kinds of string manipulations.
Manipulationof Strings using Operators
• Strings can be defined as class, objects which can be then
manipulated like the built-in types.
• Since the strings vary in size, we use new to allocate memory
for each string and a pointer variable to point to the string
array.
continue…
Manipulationof Strings using Operators
• We must create string objects that can hold two pieces of
information:
• Length
• Location
class string
{
char *p; // pointer to string
int len; // length of string
public :
------
------
};
continue…
Rules For Overloading Operators
• Only existing operators can be overloaded. New operators
cannot be created.
• The overloaded operator must have at least one operand that is
of user-defined type.
• We cannot change the basic meaning of an operator.
• Overloaded operators follow the syntax rules of the original
operators.
Rules ForOverloadingOperators
• The following operators that cannot be overloaded:
Size of Size of operator
. Membership operator
.* Pointer-to-member operator
: : Scope resolution operator
? ; Conditional operator
continue…
Rules ForOverloadingOperators
• The following operators can be over loaded with the use of
member functions and not by the use of friend functions:
• Assignment operator =
• Function call operator( )
• Subscripting operator [ ]
• Class member access operator ->
• Unary operators, overloaded by means of a member function,
take no explicit arguments and return no explicit values, but,
those overloaded by means of a friend function, take one
reference argument.
continue…
Rules ForOverloadingOperators
• Binary arithmetic operators such as +, -, * and / must explicitly
return a value. They must not attempt to change their own
arguments.
• Binary operators overloaded through a member function
take one explicit argument and those which are overloaded
through a friend function take two explicit arguments.
continue…
Type Conversions
• The type conversions are automatic only when the data types
involved are built-in types.
int m;
float x = 3.14159;
m = x; // convert x to integer before its value is assigned
// to m.
• For user defined data types, the compiler does not support
automatic type conversions.
• We must design the conversion routines by ourselves.
Type Conversions
• Different situations of data conversion between incompatible
types.
• Conversion from basic type to class type.
• Conversion from class type to basic type.
• Conversion from one class type to another class type.
continue…
Basic to ClassType
• A constructor to build a string type object from a char * type
variable.
string : : string(char *a)
{
length = strlen(a);
P = new char[length+1];
strcpy(P,a);
}
• The variables length and p are data members of the class string.
continue…
Basic to ClassType
class time
{ int hrs ;
int mins ;
public :
…
time (int t)
{
hrs = t / 60 ;
mins = t % 60;
}
} ;
time T1;
int duration = 85;
T1 = duration;
continue…
ClassTo BasicType
• A constructor function do not support type conversion from a
class type to a basic type.
• An overloaded casting operator is used to convert a class type
data to a basic type.
• It is also referred to as conversion function.
operator typename( )
{
…
… ( function statements )
…
}
• This function converts a calss type data to typename.
continue…
ClassTo BasicType
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
• This function converts a vector to the square root of the sum of
squares of its components.
continue…
ClassTo BasicType
• The casting operator function should satisfy the following
conditions:
• It must be a class member.
• It must not specify a return type.
• It must not have any arguments.
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
continue…
ClassTo BasicType
• Conversion functions are member functions and it is
invoked with objects.
• Therefore the values used for conversion inside the
function belong to the object that invoked the function.
• This means that the function does not need an argument.
continue…
One Class ToAnother Class Type
objX = objY ; // objects of different types
• objX is an object of class X and objY is an object of class Y.
• The class Y type data is converted to the class X type data and
the converted value is assigned to the objX.
• Conversion is takes place from class Y to class X.
• Y is known as source class.
• X is known as destination class.
One ClassToAnotherClassType
• Conversion between objects of different classes can be carried
out by either a constructor or a conversion function.
• Choosing of constructor or the conversion function depends upon
where we want the type-conversion function to be located in the
source class or in the destination class.
continue…
One ClassToAnotherClassType
operator typename( )
• Converts the class object of which it is a member to typename.
• The typename may be a built-in type or a user-defined one.
• In the case of conversions between objects, typename refers to
the destination class.
• When a class needs to be converted, a casting operator
function can be used at the source class.
• The conversion takes place in the source class and the result is
given to the destination class object.
continue…
One ClassToAnotherClassType
Consider a constructor function with a single argument
• Construction function will be a member of the destination
class.
• The argument belongs to the source class and is passed to the
destination class for conversion.
• The conversion constructor be placed in the destination class.
continue…

C++ - Constructors,Destructors, Operator overloading and Type conversion

  • 1.
  • 2.
    Introduction • A constructorin C++ is a special method that is automatically called when an object of a class is created. • To create a constructor, use the same name as the class, followed by parentheses.
  • 3.
    Constructors • A constructoris a special member function which enables an object to initialize itself when it is created. (In other word, it is used to initialize all class data members.) • It is special because its name is same as the class name. • In C++, Constructor is automatically called when object create. • These constructors get invoked whenever an object of its associated class is created. • It is called constructor because it constructs the values of data members of the class.
  • 4.
    Constructor- example class add { intm, n ; public : add (void) ; ------ }; add :: add (void) { m = 0; n = 0; } • When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. • add a ; • Not only creates the object a of type add but also initializes its data members m and n to zero. continue …
  • 5.
    Constructors • There isno need to write any statement to invoke the constructor function. • If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. • A constructor that accepts no parameters is called the default constructor. • The default constructor for class A is A : : A ( ) continue …
  • 6.
    Characteristics of Constructors •They should be declared in the public section. • They are invoked automatically when the objects are created. • They do not have return types, not even void and they cannot return values. continue …
  • 7.
    Characteristics of Constructors •They cannot be inherited, though a derived class can call the base class constructor. • Like other C++ functions, Constructors can have default arguments. • Constructors can not be virtual. continue …
  • 8.
    Characteristics of Constructors •We can not refer to their addresses. • An object with a constructor (or destructor) can not be used as a member of a union. • They make ‘implicit calls’ to the operators new and delete when memory allocation is required. continue …
  • 10.
    Parameterized Constructors It ispossible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
  • 11.
    #include <iostream> class Point { private: intx, y; public: // Parameterized Constructor Point(int x1, int y1) { x = x1; y = y1; } int getX() { return x; } int getY() { return y; } };
  • 12.
    int main() { // Constructorcalled Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; }
  • 13.
    Copy Constructor • Acopy constructor is used to declare and initialize an object from another object. integer (integer & i) ; (to get value from other constructor) integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization.
  • 14.
    Copy Constructor • Thestatement I 2 = I 1; will not invoke the copy constructor. • If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-member. • A reference variable has been used as an argument to the copy constructor. • We cannot pass the argument by value to a copy constructor. continue …
  • 15.
    Dynamic Constructors • Theconstructors can also be used to allocate memory while creating objects. • This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size. • Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. • The memory is created with the help of the new operator.
  • 16.
    Destructors • A destructoris used to destroy the objects that have been created by a constructor. • Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. eg: ~ integer ( ) { } • A destructor never takes any argument nor does it return any value. • It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible.
  • 17.
    Destructors • It isa good practice to declare destructors in a program since it releases memory space for further use. • Whenever new is used to allocate memory in the constructor, we should use delete to free that memory. continue …
  • 18.
  • 19.
    Introduction • It isone of the many exciting features of C++. • C++ has ability to provide the operators with a special meaning for a data types. • We can overload (give additional meaning to) all the C++ operators except: • Class member access operators ( . & .*) • Scope resolution operators ( : : ) • Size operator (sizeof) • Conditional operators (? : ) • When an operator is overloaded, its original meaning is not lost
  • 20.
    Defining Operator Overloading •To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. • This is done with the help of a special function called operator function. return type class-name : :operator op (arg-list) { Function body // task defined }
  • 21.
    DefiningOperatorOverloading • return typeis the type of value returned by the specified operation. • op is the operator being overloaded. • op is preceded by the keyword operator. • operator op is the function name. continue…
  • 22.
    DefiningOperatorOverloading • Operator Functionmust be either member function (non-static) Or friend function. The basic difference : • A friend function will have only one argument for unary operators and two for binary operators. • A member function has no arguments for unary operators and one argument for binary operators. • Arguments may be passed either by value or by reference. continue…
  • 23.
    Process of OperatorOverloading Theprocess of overloading involves the following steps: • Create a class that defines the data type that is to be used in the overloading operation. • Declare the operator function operator op( ) in the public part of the class. It may be either a member function or a friend function. • Define the operator function to implement the required operations. continue…
  • 24.
    Process of OperatorOverloading •Overloaded operator functions can be invoked by expressions such as: For unary operators: op x or x op For binary operators: x op y • op x or x op would be interpreted as for a friend function:operator op (x) for a member function: x.operator op ( ) • x op y would be interpreted as for a friend function:operator op (x,y) for a member function: x.operator op (y) continue…
  • 25.
    Overloading Unary Operators Considera unary minus operator: • It takes just one operand. • It changes the sign of an operand when applied to a basic data item. • The unary minus when applied to an object should change the sign of each of its data items.
  • 26.
    Overloading Binary Operators Asa rule, in overloading binary operators, • the left-hand operand is used to invoke the operator function and • the right-hand operand is passed as an argument.
  • 27.
    Overloading Binary Operators complexoperator+(complex a, complex b) { return complex((a.x + b.x),(a.y + b.y)); } • The compiler invokes an appropriate constructor, initializes an object with no name and returns the contents for copying into an object. • Such an object is called a temporary object. continue…
  • 28.
    Overloading Binary OperatorsUsing Friends • Friend function requires two arguments to be explicitly passes to it. • Member function requires only one. friend complex operator+(complex, complex); complex operator+(complex a, complex b) { return complex((a.x + b.x),(a.y + b.y)); } • We can use a friend function with built-in type data as the left- hand operand and an object as the right-hand operand.
  • 29.
    Manipulation of Stringsusing Operators • There are lot of limitations in string manipulation in C as well as in C++. • Implementation of strings require character arrays, pointers and string functions. • C++ permits us to create our own definitions of operators that can be used to manipulate the strings very much similar to other built- in data types. • ANSI C++ committee has added a new class called string to the C++ class library that supports all kinds of string manipulations.
  • 30.
    Manipulationof Strings usingOperators • Strings can be defined as class, objects which can be then manipulated like the built-in types. • Since the strings vary in size, we use new to allocate memory for each string and a pointer variable to point to the string array. continue…
  • 31.
    Manipulationof Strings usingOperators • We must create string objects that can hold two pieces of information: • Length • Location class string { char *p; // pointer to string int len; // length of string public : ------ ------ }; continue…
  • 32.
    Rules For OverloadingOperators • Only existing operators can be overloaded. New operators cannot be created. • The overloaded operator must have at least one operand that is of user-defined type. • We cannot change the basic meaning of an operator. • Overloaded operators follow the syntax rules of the original operators.
  • 33.
    Rules ForOverloadingOperators • Thefollowing operators that cannot be overloaded: Size of Size of operator . Membership operator .* Pointer-to-member operator : : Scope resolution operator ? ; Conditional operator continue…
  • 34.
    Rules ForOverloadingOperators • Thefollowing operators can be over loaded with the use of member functions and not by the use of friend functions: • Assignment operator = • Function call operator( ) • Subscripting operator [ ] • Class member access operator -> • Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument. continue…
  • 35.
    Rules ForOverloadingOperators • Binaryarithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments. • Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. continue…
  • 36.
    Type Conversions • Thetype conversions are automatic only when the data types involved are built-in types. int m; float x = 3.14159; m = x; // convert x to integer before its value is assigned // to m. • For user defined data types, the compiler does not support automatic type conversions. • We must design the conversion routines by ourselves.
  • 37.
    Type Conversions • Differentsituations of data conversion between incompatible types. • Conversion from basic type to class type. • Conversion from class type to basic type. • Conversion from one class type to another class type. continue…
  • 38.
    Basic to ClassType •A constructor to build a string type object from a char * type variable. string : : string(char *a) { length = strlen(a); P = new char[length+1]; strcpy(P,a); } • The variables length and p are data members of the class string. continue…
  • 39.
    Basic to ClassType classtime { int hrs ; int mins ; public : … time (int t) { hrs = t / 60 ; mins = t % 60; } } ; time T1; int duration = 85; T1 = duration; continue…
  • 40.
    ClassTo BasicType • Aconstructor function do not support type conversion from a class type to a basic type. • An overloaded casting operator is used to convert a class type data to a basic type. • It is also referred to as conversion function. operator typename( ) { … … ( function statements ) … } • This function converts a calss type data to typename. continue…
  • 41.
    ClassTo BasicType vector :: operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } • This function converts a vector to the square root of the sum of squares of its components. continue…
  • 42.
    ClassTo BasicType • Thecasting operator function should satisfy the following conditions: • It must be a class member. • It must not specify a return type. • It must not have any arguments. vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } continue…
  • 43.
    ClassTo BasicType • Conversionfunctions are member functions and it is invoked with objects. • Therefore the values used for conversion inside the function belong to the object that invoked the function. • This means that the function does not need an argument. continue…
  • 44.
    One Class ToAnotherClass Type objX = objY ; // objects of different types • objX is an object of class X and objY is an object of class Y. • The class Y type data is converted to the class X type data and the converted value is assigned to the objX. • Conversion is takes place from class Y to class X. • Y is known as source class. • X is known as destination class.
  • 45.
    One ClassToAnotherClassType • Conversionbetween objects of different classes can be carried out by either a constructor or a conversion function. • Choosing of constructor or the conversion function depends upon where we want the type-conversion function to be located in the source class or in the destination class. continue…
  • 46.
    One ClassToAnotherClassType operator typename() • Converts the class object of which it is a member to typename. • The typename may be a built-in type or a user-defined one. • In the case of conversions between objects, typename refers to the destination class. • When a class needs to be converted, a casting operator function can be used at the source class. • The conversion takes place in the source class and the result is given to the destination class object. continue…
  • 47.
    One ClassToAnotherClassType Consider aconstructor function with a single argument • Construction function will be a member of the destination class. • The argument belongs to the source class and is passed to the destination class for conversion. • The conversion constructor be placed in the destination class. continue…