You are on page 1of 35

OBJECT ORIENTED PROGRAMMING LANGUAGE

UNIT II:Classes and Objects Hours:15


Declaring Objects – Defining Member Functions – Static Member variables and functions – array of
objects –friend functions – Overloading member functions – Bit fields and classes – Constructor and
destructor with static members.
2.1 CLASS:
 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used to manipulate
these variables together, these data members and member functions define the properties and
behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc, and
member functions can be applying brakes, increasing speed, etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.

2.1.1 Defining Class and Declaring Objects


A class is defined in C++ using the keyword class followed by the name of the class. The body of
the class is defined inside the curly brackets and terminated by a semicolon at the end.

Declaring Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions: The data members and member functions of the
class can be accessed using the dot(„.‟) operator with the object. For example, if the name of the
object is obj and you want to access the member function with the name printName() then you will
have to write obj.printName().
Access to class members: The object can access the public data member and member functions
1 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE

of a class by using dot (.) and arrow (->) operators. The syntax is as follows:
[Object name][Operator][Member name]
To access data members of class the statement would be as follows:
Employee e, *a;
e.readData();

Where e is an object and readData() is a member function. The dot operator is used
because a is a simple object.

In statement
a->readData();
*a is pointer to class item; therefore, the arrow operator is used to access the member.

Access Specifiers:
1. Public: The keyword public can be used to allow objects to access the member variables
of a class directly like structures in C.
2. Private: The private keyword is used to prevent direct access of member variables by the
object. The class by default produces this effect. i.e., a data member can only be
accessed by the member functions of the class.
3. Protected: The members which are declared under protected section, can be accessed by
the member functions of the class and those of the class which is immediately
derived from it. No other class can access the protected data elements.

Accessing Data Members


The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member depends
solely on the access control of that data member. This access control is given by Access modifiers
in C++. There are three access modifiers: public, private, and protected.
 C++

// C++ program to demonstrate accessing of data members


#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:

2 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

// Data Members
string geekname;
// Member Functions()
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}

Output

Geekname is:Abhi

2.2 Defining of Member Functions of Class in C++


Member functions can be defined at any one of the following two places:

1. Outside the Class


2. Inside the Class
It is obvious that, irrespective of the place of definition, the function should perform the same task.
Therefore, the code for the function body would be identical in both the cases. However, there is a
subtle difference in the way the function header is defined. Both these approaches are discussed in
detail as follows:

1. Outside the Class Definition:


Member functions that are declared (with the help of prototypes) inside a class have to be
defined separately outside the class. Their definitions are very much like the normal functions.
They should have a function header and a function body.However, an important difference
between a member function and a normal function is that a member function incorporates a

3 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

membership “Identity label” in the header. This labels tells the compiler which class the function
belongs to.
The general form of a member function definition outside the class is:

return-type class-name::function-name(argument declaration)


{
function-body
}

The membership label class-name:: tells the compiler that the function function-name belongs to
the class class-name. That is, the scope of the function is restricted to the class-name specified in
the header line. The symbol :: is called the scope resolution operator.
For instance, consider the member functions getdata() and putdata(). They may be coded
(outside the class item) as follows:

void item :: getdata(int a, float b)


{
number = a;
cost = b;
}

void item :: putdata()


{
cout << "Number :" << number << endl;
cout << "Cost :" << cost << endl;
}

Since, these functions do not return any value, their return-type is void.

Note:
1) Several different classes can use the same function name. The membership label will resolve
their scope
2) Member functions can access the private data of the class. A non-member function cannot do
so. (However, an exception to this rule is a friend function discussed later)
3) A member function can call another member function directly, without using the dot operator
(The use of dot operator in case of class is discussed later)
2. Inside the Class Definition:
Another method of defining a member function is to replace the function declaration by the

4 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

actual function definition inside the class. For example, we could define the item class as
follows:

class item
{
int number;
float cost;
public:
void getdata(int a, float b) //declaration
void putdata() //definition
{ //inline function
cout << "Number :" << number << endl;
cout << "Cost :" << cost << endl;
}

When a function is defined inside a class, it is treated as an inline function. Therefore, all the
restrictions and limitations that apply to an inline function are also applicable here.

2.3 Static Member Variables

A data member of a class can be qualified as static. A static member variable has certain special
characteristics. These are:

 It is initialized to zero when the first object of its class is created.


 Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
 It is visible only within the class, but its lifetime is the entire program.
 The static data members are associated with the class and not with any object.
 Static variables are normally used to maintain values common to the entire class.

5 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Syntax:

1. static <variable definition> ;


Ex.
static int c; // For example in class item
int item::c=10;

2. static <function definition>;


/* C++ Program illustrates the use of a static data member.*/

#include <iostream>
using namespace std;

class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: "<< count <<"\n";
}
};
int item :: count;

int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();

a.getdata(100);
b.getdata(200);
c.getdata(300);

cout << "After reading data"<<"\n";

a.getcount();
b.getcount();

6 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Output:

c.getcount(); Count: 0
return 0; Count: 0
} Count: 0
After reading data
Count: 3
Count: 3
Count: 3
static Member Functions

Like member variables, function can also be declared as static. When a function is defined as
static, it can access only static member variables and functions of the same class. The not-static
members are not available to these functions. The static member function declared in public
section can be invoked using its class name without using its objects. The programmer must
follow the following points while declaring static function:

1. Just one copy of a static member is created in the memory for entire class. All objects of
the class share the same copy of static member.
2. static member function can access only static data members or functions.
3. A static member function can be called with the class name as follows:

class-name :: function-name;

class-name :: function-name;

In the following code the static function getcount() displays the number of objects created
till that moment.
#include <iostream>
using namespace std;

class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;

7 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

count ++;
}
void getcount(void)
{
cout << "Count: "<< count <<"\n";
}
static void show_count()
{
cout << "Count: "<< count <<"\n";
}
};
int item :: count;

int main()
{
item a,b,c;
item::show_count();

a.getdata(100);
b.getdata(200);
c.getdata(300);

cout << "After reading data"<<"\n";

item::show_count();
return 0;
}

Output:
Count: 0
After reading data
Count: 3
2.4 Array of Objects in C++ with Examples:

An array in C/C++ or be it in any programming language is a collection of similar data items


stored at contiguous memory locations and elements can be accessed randomly using indices of an
array. They can be used to store the collection of primitive data types such as int, float, double,
char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as
structures, pointers, etc

Example:
Let‟s consider an example of taking random integers from the user.

8 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Array

Array of Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of objects.
Example#1:
Storing more than one Employee data. Let‟s assume there is an array of objects for storing
employee data emp[50].

Below is the C++ program for storing data of one Employee:

 C++

// C++ program to implement


// the above approach
#include<iostream>
using namespace std;

class Employee

9 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;

Objects as Function Arguments

The following are the three methods to pass argument to a function:


 Pass-by-value – A copy of object (actual object) is sent to function and assigned to the
object of callee function (formal object). Both actual and formal copies of objects are
stored at different memory locations. Hence, changes made in formal object are not
reflected to actual object.
 Pass-by-reference – Address of object is implicitly sent to function.
 Pass-by-address – Address of the object is explicitly sent to function.
In pass-by-reference and pass-by-address methods, an address of actual object is passed to the
function. The formal argument is reference/pointer to the actual object. Hence, changes made in
the object are reflected to actual object. These two methods are useful because an address is
passed to the function and duplicating of object is prevented.

10 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

2.5 Friend function and Friend class

The main concept of OOP paradigm is data hiding and data encapsulation. Whenever data
variables are declared in a private category of a class, these members are restricted from
accessing by non-member functions. The private data values can be neither read nor written by
non-member functions. If an attempt is made directly to access these members, the compiler will
display an error message “inaccessible data type”. The best way to access private member is to
change access specifier to public group. But it violates the concept of data hiding. To solve this
problem, a friend function/class can be declared to have access these data members. Friend is a
special mechanism for letting non-member functions access private data. The keyword friend
inform the compiler it is not a member of the class.

The general syntax is:


friend return_type function_name(parameters);

Example: friend function

class myclass int sum(myclass a)

{ {

int num1,num2; int n=a.num1+a.num2;

public: return n;

myclass(int,int); void }
printvalues();
int main() {
friend int sum(myclass);
myclass m(10,20);
}; m.printvalues();
cout<<"Sum of values in
myclass::myclass(int n1,int n2)
object:"<<sum(m)<<endl;
{
return 0;
num1=n1;
num2=n2; }

11 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

#include <iostream>
using namespace std;

class myclass
{
int num1,num2;

public:
myclass(int,int); void printvalues();friend class math;
};
myclass::myclass(int n1,int n2)
{
num1=n1;num2=n2;
}

void myclass::printvalues()
{
cout<<"first value is:"<<num1<<endl;cout<<" second is:"<<num2<<endl;
}
class math
{
public:
int sum(myclass);
int multiply(myclass);
};
int math::sum(myclass obj)
{
return obj.num1+obj.num2;
}
int math::multiply(myclass obj)
{
return obj.num1*obj.num2;
}
int main() {
myclass mc(10,20); math m;
cout<<"The sum of two values in myclass object:"<<m.sum(mc)<<endl;
cout<<"The multiplication of two values in myclass object:"<<m.multiply(mc)<<endl;

return 0;
}

12 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

C++ Friend function

If a function is defined as a friend function in C++, then the protected and private data of a class can
be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword friend.

Declaration of friend function in C++

1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

In the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use
either the keyword friend or scope resolution operator.

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example

Let's see the simple example of C++ friend function used to print the length of a box.

1. #include <iostream>
2. using namespace std;
3. class Box
4. {
13 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE

5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }

Output:

Length of box: 10
2.6 C++ Overloading (Function and Operator)

If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:

o methods,
o constructors, and
o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:

o Function overloading
o Operator overloading

14 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

C++ Function Overloading

Function Overloading is defined as the process of having two or more function with the same name,
but different in parameters is known as function overloading in C++. In function overloading, the
function is redefined by using either different types of arguments or a different number of arguments.
It is only through these differences compiler can differentiate between the functions.

The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.

C++ Function Overloading Example

Let's see the simple example of function overloading where we are changing number of arguments of
add() method.

// program of function overloading when number of arguments vary.

1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
15 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE

14. Cal C; // class object declaration.


15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }

Output:

30
55

Let's see the simple example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5.
6.
7. int mul(int a,int b)
8. {
9. return a*b;
10. }
11. float mul(double x, int y)
12. {
13. return x*y;
14. }
15. int main()
16. {
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22. }

16 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Output:

r1 is : 42
r2 is : 0.6

Function Overloading and Ambiguity

When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.

When the compiler shows the ambiguity error, the compiler does not run the program.

Causes of Function Overloading:

o Type Conversion.
o Function with default arguments.
o Function with pass by reference.

o Type Conversion:

Let's see a simple example.

1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
17 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE

9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }

The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction. But,
this does not refer to any function as in C++, all the floating point constants are treated as double not
as a float. If we replace float to double, the program works. Therefore, this is a type conversion from
float to double.

o Function with Default Arguments

Let's see a simple example.

1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);

18 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

17.
18. return 0;
19. }

The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a, int
b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and
another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is
invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and
fun(int a,int b=9).

o Function with pass by reference

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int &);
5. int main()
6. {
7. int a=10;
8. fun(a); // error, which f()?
9. return 0;
10. }
11. void fun(int x)
12. {
13. std::cout << "Value of x is : " <<x<< std::endl;
14. }
15. void fun(int &b)
16. {
17. std::cout << "Value of b is : " <<b<< std::endl;
18. }

The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first
function takes one integer argument and the second function takes a reference parameter as an
argument. In this case, the compiler does not know which function is needed by the user as there is no
syntactical difference between the fun(int) and fun(int &).

19 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

C++ Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide


the special meaning to the user-defined data type. Operator overloading is used to overload or
redefines most of the operators available in C++. It is used to perform the operation on the user-
defined data type. For example, C++ provides the ability to add the variables of the user-defined data
type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading

1. return_type class_name : : operator op(argument_list)


2. {
3. // body of the function.
4. }

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword.

Rules for Operator Overloading

o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.

20 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

o When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit arguments.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void operator ++ ()
operator function is defined (inside Test class).

// program to overload the unary operator ++.

1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }

Output:

21 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

The Count is: 10

Let's see a simple example of overloading the binary operators.

// program to overload the binary operators.

1. #include <iostream>
2. using namespace std;
3. class A
4. {

5. int x;
6. public:
7. A(){}
8. A(int i)
9. {
10. x=i;
11. }
12. void operator+(A);
13. void display();
14. };

15. void A :: operator+(A a)


16. {

17. int m = x+a.x;


18. cout<<"The result of the addition of two objects is : "<<m;

19. }
20. int main()
21. {
22. A a1(5);
23. A a2(4);
24. a1+a2;
25. return 0;
26. }

22 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Output:

The result of the addition of two objects is : 9

Bit-Field

When we declare the members in a struct and classes, a pre-determined size is allocated for the
member variables. In C++, we can compress that allocated size using bit fields.

Bit Field is a feature in C++ for specifying the size of struct and class members so that they occupy
a specific number of bits, not the default memory size.

Bit-Field Syntax in Struct

struct StructName {
dataType fieldName : width;
// more bit-field members...
};

Bit-Field Syntax in Classes

class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
where width is the number of bits.

Bit-Field Syntax in Classes

class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
where width is the number of bits.
Note: It is to be noted that bit fields are only acceptable for integral data types.

Class with Bit Fields in C++

In the below example, we have used bit fields with classes instead of struct.

23 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

 C++

// C++ program to demonstrate the size occupied by a class


// by specifying the bits to member variables of the class
// using bit fields
#include <iostream>
using namespace std;

// Define a class with bit-fields for loan information


class Loan {
public:
// Maximum principal of 1,048,575
unsigned int principal : 20;
// Maximum interest rate of 63
unsigned int interestRate : 6;
// Maximum period of 63 months
unsigned int period : 6;
};

int main()
{
Loan loan1;
loan1.principal = 500000;
loan1.interestRate = 15;
loan1.period = 36;

// Print the size of loan1


// (20+6+6)/8 = 4 Bytes
// 1 Byte = 8 Bits
cout << sizeof(Loan) << " Bytes" << endl;

return 0;
}

Output

4 Bytes

2.7 Constructors:

A constructor is defined to be a special member function, which helps in initializing an object

24 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

while it is declared.

Characteristics of constructors:

(1) Constructor has the same name as that of the class it belongs.
(2) It should be a public member.
(3) It is invoked implicitly at the time of creation of the objects.
(4) Constructors have neither return value nor void.
(5) The main function of constructor is to initialize objects.
(6) Constructor can have default and can be overloaded.
(7) The constructor without arguments is called as default constructor.

Types of Constructors:

Constructors are classified into three types:

1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Dynamic Constructor

Default Constructor:

A constructor which does not take any arguments is called the default constructor. Suppose A
is a class, the default constructor in the class takes the following form:

A()
{

Statements;
}

The statements within the body of the function assign the values to the member data of the class.
Note that the name of the constructor is same as the class name and no return type is specified
not even void.
Example:

#include <iostream> void construct::display()


using namespace std; {
class construct cout<<"The first value is:"<<x<<endl;
{ cout<<"The second value
int x; is:"<<y<<endl;
int y; }
25 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE

public:
construct(); int main() {
void display();
}; construct dc;
construct::construct() dc.display();
{ return 0;
x=10; }
y=20;
}

Parameterized Constructor: The constructor that can take arguments are called parametrized
constructors.

Example:

#include <iostream> void construct::display()


using namespace std; {
cout<<"The first value is:"<<x<<endl;
class construct cout<<"The second value
{ is:"<<y<<endl;
int x; }
int y;
public: int main() {
construct(int,int);
void display(); construct pc(10,20),pc1(100,200);
}; pc.display();
construct::construct(int val1,int val2) pc1.display();
{ return 0;
x=val1; }
y=val2;

Multiple Constructors in a class/Constructor Overloading:

When more than one constructor is defined in a class, we say that constructor is overloaded.

#include <iostream> construct::construct(int val1,int val2)


using namespace std; {
class construct x=val1;

26 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

{ y=val2;
int x;
int y; }
public: void construct::display()
construct(); {
construct(int); cout<<"The first value is:"<<x<<endl;
construct(int,int); cout<<"The second value
void display(); is:"<<y<<endl;
}; }
construct::construct()
{ int main() {
x=10;y=20;
} construct obj1;
construct::construct(int val1) construct obj2(100);
{ construct obj3(100,200);
x=val1; //object 1
y=20; obj1.display();
} //object 2
obj2.display();
//object 3
obj3.display();
return 0;
}

Copy Constructor:

The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to:

 Initialize one object from another of the same type.

#include <iostream> x=obj.x;


using namespace std; y=obj.y;

class construct }
{ void construct::display()
int x; {
int y; cout<<"The first value is:"<<x<<endl;
public: cout<<"The second value
construct(int,int); is:"<<y<<endl;
construct(construct &); }
void display();
}; int main() {
construct::construct(int val1,int val2)
{ construct obj1(10,20);

27 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

x=val1; construct obj2(obj1);


y=val2; obj1.display();
obj2.display();
} return 0;
construct::construct(construct &obj) }
{

Dynamic Constructor:

Sometimes we may require to dynamically allocate memory for objects during their creation.
This is done with the help of dynamic constructors. The dynamic constructors use the new
operator to allocate memory for objects during runtime. A Constructor which allocates memory
and initializes an object during runtime is called a dynamic constructor.

Example:
Class Dynamic
{ int *a;
public:
Dynamic(int n)
{

a=new int[n];
}
};
Here, the member data a of the class Dynamic is a pointer to int type. The constructor takes an
argument n of int type and allocates memory for n integers. The address of the first element in
the dynamic array is assigned to the pointer a.

Example:
#include <iostream>
using namespace std;
class integer

public:

28 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

{
int *a;
int n;

}
integer(int m)

void display()
{
n=m;
a=new int[m];

int i;

for(i=0;i<n;i++)
cout<<a[i]<<endl;

void accept()
{
int i;

for(i=0;i<n;i++)
cin>>a[i];
}
};
int main() {

integer v(5),v1(10);
cout<<"Enter elements";
v.accept();
cout<<"Display elements";
v.display();
cout<<"Enter elements";
v1.accept();
cout<<"Display elements";
v1.display();
return 0;

29 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Destructors:

A destructor is defined to be a special member function of a class, which helps in releasing the
memory occupied by an object when it goes out of scope.
Characteristics:
1. It should be public member
2. The name of the destructor should as that of class name and it is preceded with ~.
3. It cannot take any arguments
4. No return type should be specified including void.
5. delete operator is to be used to de-allocate the memory allocated by new operator in the
constructor.

Example:

#include <iostream>
using namespace std;

int count=0;
class integer
{
int x;
public:
integer(int y)
{
count++;
cout<<"object"<<count<<"created<<endl";
x=y;
}
~integer()
{
cout<<"object -"<<count<<" destroyed"<<endl;
count--;
}
};
int main() {
integer a(10),b(20); Output:Object 1 created
return 0; Object 2 created
} Object -2 destroyed
object -1 destroyed

30 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Static data members are class members that are declared using static keywords. A static member
has certain special characteristics which are as follows:
 Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
 It is initialized before any object of this class is created, even before the main starts.
 It is visible only within the class, but its lifetime is the entire program.
Syntax:
static data_type data_member_name;
Below is the C++ program to demonstrate the working of static data members:

 C++

// C++ Program to demonstrate


// the working of static data member
#include <iostream>
using namespace std;

class A {
public:
A()
{
cout << "A's Constructor Called " <<
endl;
}
};

class B {
static A a;

public:
B()
{
cout << "B's Constructor Called " <<
endl;
}
};

// Driver code
int main()
{
B b;
return 0;
}

Output

31 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

B's Constructor Called

32 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

Destructors
A Destructor is the opposite of Constructor, and needless to tell you that it has the opposite
effect. A constructor is automatically called to initialize a newly-created object. Conversely, a
destructor is automatically called when an object is destroyed to de-allocate the memory portion
that was allocated to the object on its creation.

A Destructor must:

 Have the same name as its class, but will be preceded with a tilde ~
 Neither have a return value nor arguments.

Static Member Variables


Refer back to the point class that we have defined in the above example: it has two member
variables x and y. For each instance (object) created of that class, each object will have its own
“completely” separate x and y variables. In other words, a portion of memory will be reserved
for object P1 that contains 4 bytes segment for the floating-point variable x, and another 4 bytes
for the other float variable y. When another object P2 is created, another portion of memory will
be allocated for it, with 4 bytes for P2.x and 4 bytes for P2.y. This will take place for each new
object instantiated from the point class.

C++ has another type of member variables: the static member variables. Within a class
definition, if a variable is declared as static, only one copy of that variable is created for the
class, regardless of the number of objects instantiated. Static member variables provide a pretty
way to share data between objects of the same class. One common use for static data is to
maintain the number of objects created in one class.

Example
The following program uses static member variable to keep track on the number of objects
defined.

 Example
The following program uses static member variable to keep track on the number of
objects defined in destructor.
#include <conio.h>
#include <iostream.h>
class test
{
static int objcount;
public:
test()
{ objcount++;

33 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

cout << "New object created\n";


}
int getcount()
{ return objcount; }
};
int test::objcount=0;
void main()
{
clrscr();
test t1;
cout << "\t=>You have " << t1.getcount() << " objects\n";
test t2,t3;
cout << "\t=>You have " << t1.getcount() << " objects\n";
getch();
}
Let‟s compile and execute this code, and see what we will get:

 Now, to the explanation:

 To use a static member variable, two distinct statements are needed: one inside the class for
the variable declaration:

static int objcount;


And, the other outside the class for variable definition:

int test::objcount=0;

 The defined static variable objcount is incremented each time a new object is created. To do
this, the following statement is used inside the class constructor:

objcount++;

 To get the value of static member variable objcount, the member function getcount() is called:

34 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP


OBJECT ORIENTED PROGRAMMING LANGUAGE

t1.getcount()
In the above statement, the member getcount() that is associated with the object t1 is called.
After defining objects t2 and t3, either of the three objects t1, t2, or t3 could be used in the
second function call.

t1.getcount() = t2.getcount() = t3.getcount()

 One final note regarding the use of the :: operator: it is called the scope resolution operator.
This operator is used to specify the class to which a variable or a function belongs. This is
useful when defining a member function or a static variable outside the class definition.
Summary
In this article, we have continued our journey with Object-oriented programming by talking
about Destructors and Static Member Variables.

 An object can be initialized using another object of the same class. There are two syntax
forms to achieve this.
 A Destructor is the opposite of Constructor. It de-allocates memory allocated to an object that
is no longer needed.
 A Static member variable is created once for an entire class. It provides a way to share data
between objects of the same class.

35 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP

You might also like