0% found this document useful (0 votes)
20 views34 pages

CTUC103 Unit 02

The document provides a comprehensive overview of classes and objects in C++, covering key concepts such as visibility modes, member functions, constructors, and access specifiers. It explains the structure of class declarations, the creation and manipulation of objects, and the use of static members and arrays within classes. Additionally, it highlights the importance of encapsulation and access control in object-oriented programming.

Uploaded by

lakshrajsinh188
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views34 pages

CTUC103 Unit 02

The document provides a comprehensive overview of classes and objects in C++, covering key concepts such as visibility modes, member functions, constructors, and access specifiers. It explains the structure of class declarations, the creation and manipulation of objects, and the use of static members and arrays within classes. Additionally, it highlights the importance of encapsulation and access control in object-oriented programming.

Uploaded by

lakshrajsinh188
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Smt.

Chandaben Mohanbhai Patel Institute of


Computer Applications
CHAROTAR UNIVERSITY OF SCIENCE AND TECHNOLOGY

B.Sc. (IT) (Semester-2)


CTUC103 || Introduction to Object-Oriented Programming

Unit-2: Classes and Object


 Classes and objects in C++,
 Visibility Modes,
 Static Member
 Friend Function
 Constructors:
o Default,
o Parameterized,
o Copy constructor
o Constructor overloading
o Destructor
 Access specifiers, implementing and accessing class members.
 this keyword
Class Specification:
 A class is a way to bind the data and its associated functions together.
 It allows the data and functions to be hidden from external use, if necessary. Class
is an Abstract Data Type.
Generally, the class specification has two parts:
1. Class Declaration
2. Class Function Definition

Class Declaration:
 The class declaration describes the type and scope of its members.
 The class function definition describes how the class functions are implemented.
Syntax of Class Declaration:
class class-name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
 The class is a keyword that specifies that what follows is an abstract data of type
class-name.
 The body of the class is enclosed within braces and terminated by a semicolon.
 The class body contains the declaration of variables and functions.
 These functions and variables are collectively called class members.
 Class members are usually grouped into two sections, namely private and public
to denote which members are private and which members are public.
 The keywords private and public are known as visibility labels followed by a colon.
 The use of private keywords is optional. The default visibility label is private. If
both the labels are missing, then all the members are private. Such a class is
completely hidden from the outside world.

1|Page
 The class members that have been declared as private can be accessed only from
within the class.
 The public members can be accessed from the outside class also.
 The variables declared inside the class are called data members and the functions
are called member functions.
 Only the member functions can have access to the private data members and
private functions.
 The public members (both data and functions) can be accessed from outside the
class.
 The binding of the data and functions together into a single class-type variable is
called Encapsulation.
class simple
{
private:
int no;
char name[10];
public:
void getdata(); //function declaration
void putdata(); //function declaration
};
 The class simple contains two private data members and two public member
functions.
 The function getdata() can be used to assign values to the variable no and name.
 The function putdata() can be used to display their values.

Defining Member Functions:


Member functions can be defined in two places:
1. Outside the class definition
2. Inside the class definition

Outside the Class Definition:


 Member functions that are declared inside the class have to be defined separately
outside the class.
2|Page
 Member functions should have a function header and a function body.
 An important difference between a normal function and a member function is that
a member function includes a membership ‘identity label’ in the header. This label
tells the compiler which class the function belongs to.
Syntax:
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. This means the scope of the function is
restricted to the class-name specified in the header line.
 The symbol :: is called the scope resolution operator.

void simple:: getdata()


{
cin>>no;
cin>>name;
}
void simple:: putdata()
{
cout<<no;
cout<<name;
}

Characteristics of Member Functions:


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.
3. A member function can call another member function directly, without using the
dot operator.

3|Page
Inside the Class Definition:
Another method of defining a member function is to replace the function declaration with
the actual function definition inside the class.
class simple
{
private:
int no;
char name[10];
public:
void getdata() //function definition
{
cin>>no;
cin>>name;
}
void putdata() //function definition
{
cout<<no;
Cout<<name;
}
};

Creating Objects:
 Once a class has been declared we can create variables of that type using the class
name. For example, the statement simple s1; creates a variable s1 of type simple.
Thus the variable s1 is called an object of the type simple.
 We can declare more than one object in one statement.
For example, simple s1, s2, s3;
 The class specification provides only a template and does not create any memory
space for the objects.
 Objects can also be created when a class is defined by placing their names
immediately after the closing brace.
class simple
{
private:
int no;
char name[10];
4|Page
public:
void getdata(); //function declaration
void putdata(); //function declaration
}s1, s2, s3;

Accessing Class Members:


The private data of a class can be accessed only through the member functions of that
class. The main() cannot contain statements that access the no and name directly.
Syntax: object-name . function-name (actual arguments);
Example: s.getdata();
The above function call will assign the values inputted by users for the data members' no
and name. Similarly, s.putdata(); will display the values of these data members. The
above statement sends a message to the objects requesting it to display its contents.
Example:
class simple
{
private:
int no;
char name[10];
public:
void getdata()
{
cin>>no;
cin>>name;
}
void putdata()
{
cout<<no;
cout<<name;
}
};
int main()
{
simple s;
s.getdata();
s.putdata();
return 0;
}
5|Page
Nesting of Member Functions:
A member function can be called by using its name inside another member function of
the same class. This is known as nesting of member functions.
class simple
{
private:
int no;
char name[10];
public:
void getdata()
{
cin>>no;
cin>>name;
putdata(); //calling a member function
}
void putdata()
{
cout<<no;
cout<<name;
}
};
int main()
{
simple s;
s.getdata();
return 0;
}
A member function putdata() is called inside another member function getdata()
without using an object and dot operator.

Private Member Functions:


 It is normal practice to place all the data members in a private section and all the
member functions in a public section.
 But sometimes, we may require certain functions to be hidden from the outside
calls. Eg. Tasks such as deleting an account in a customer file or providing an
increment to an employee are serious events and therefore the functions handling

6|Page
such tasks should have restricted access. We can place these functions in the
private section.
 A private member function can only be called by another function that is a member
of its class. An object cannot invoke a private member function using the dot
operator.
class simple
{
private:
int a;
void read(); //private member function
public:
void putdata();
};
 If s is an object of simple then s.read(); will not work because the objects cannot
access the private member.
 However, the function read() can be called by the function putdata() using the
concept of nesting of member function.
void simple :: putdata()
{
read();
}

Array within a class:


The arrays can be used as member variables in a class.
class student
{
private:
int rno, marks[3],
char name[10];
public:
void getdata()
{
cout<<"Enter Roll NO. :: ";
cin>>rno;
cout<<"Enter Name :: ";
cin>>name;

7|Page
cout<<"\nEnter marks of 3 subjects : \n";
for(int i=0;i<3;i++)
{
cout<<"\n Marks of subject "<<i+1<<" :: ";
cin>>marks[i];
}
}
void putdata()
{
cout<<"\nRoll No : "<<rno;
cout<<"\nName : "<<name;
cout<<"\nMarks of 3 subjects are :";
for(int i=0;i<3;i++)
{
cout<<"\nMarks of subject "<<i+1<<" :: "<<marks[i];
}
}
};
int main()
{
student s;
s.getdata();
s.putdata();
return 0;
}
 The array variable marks[ ] declared as a private member of a class student can
be used in the member functions. We can perform any operation on it.
 In the above program getdata() reads the value for roll no, name, and marks of
three subjects. It also calculates the total of three subjects. And finally, it calculates
the percentage.
 The putdata() displays the values. Here marks is an integer-type array.

Memory Allocation for Objects:


 The memory space for objects is allocated when they are declared but not when
the class is specified.

8|Page
 This statement is only partly true. The member functions are created and placed
in the memory space only once when they are defined as part of the class
specification.
 Since all the objects belonging to that class use the same member functions, no
separate space is allocated for member functions when the objects are created.
 Only space for memory variables is allocated separately for each object.
 Separate memory locations are necessary because the memory variables will hold
different data values for different objects.

Visibility Modes or Access Specifiers


 Each user has different access privileges to the object. A class differentiate
between access privileges by partitioning its contents and associating each one of
them with any one of the following keyword: - private protected – public. These
keywords are called access control specifiers or Visibility modes.
 If no keyword is specified, then the members by default have private privilege. The
following table specifies control of privileges.
Access Accessible to
Specifier Own Class Derived Class Other Class Object of a
Member Member member Class
Private Yes No No No
Protected Yes Yes No No
Public Yes Yes Yes Yes

Private Member:
The private members of a class have strict access control. Only the member functions of
the same class can access these members. The private members of a class are inaccessible
outside the class.
Protected Member:
The access control of the protected members is similar to that of private members and
has more significance in inheritance. The member function of the derived class can access

9|Page
the protected data member. Only class member and derived class member can access
protected data, other class member cannot access.
Public Member:
The members of class, which are to be visible (accessible) outside the class, should be
declared in public section. All data members and functions declared in the public section
of the class can be accessed without any restriction from anywhere in the program, either
by function that belongs to the class or by those external to the class.

Static Data Members:


A data member of a class can be declared as static.
A static member variable has the following characteristics:
 It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
 Only one copy of that member is created for the entire class and it is shared by all
the objects of that class.
 It is visible only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. For
example, a static data member can be used as a counter that records the occurrences of
all the objects.
Example:
class simple
{
private:
int code;
static int count;
public:
void getcode(int x)
{
code=x;
count++;
}
void displaycount()
{
cout<<"\nCOUNT : "<<count;
10 | P a g e
}
};
int simple :: count; //definition of static data member
int main()
{
simple s1,s2,s3;
cout<<"\nValue of Count Before Reading Data:";
s1.displaycount();
s2.displaycount();
s3.displaycount();
s1.getcode(100);
s2.getcode(200);
s3.getcode(300);
cout<<"\nValue of Count After Reading Data:";
s1.displaycount();
s2.displaycount();
s3.displaycount();
return 0;
}
The output would be as follows:
Value of Count Before Reading Data:
COUNT : 0
COUNT : 0
COUNT : 0
Value of Count After Reading Data:
COUNT : 3
COUNT : 3
COUNT : 3
 The type and scope of each static member variable must be defined outside the
class definition.
 This is necessary because the static data members are stored separately rather
than as a part of an object. They are associated with the class itself only so that
they are also called class variables.
 The static variable count is initialized to zero when the objects are created. The
count is incremented whenever the data is read into an object. Because the data is

11 | P a g e
read into an object three times, the count is incremented three times. Since there
is only one copy of the count shared by all three objects, all three output
statements display the value 3.
 We can also assign some initial value to the static variable.
 Eg. int simple :: count = 5;

Static Member Functions:


Like static variables, we can also have static member functions.
 A static member function has the following properties:
 A static function can have access to only other static members (functions or
variables) declared in the same class.
 A static member function can be called using the class name but not by using the
object.
Syntax: class-name :: function-name;
class simple
{
private:
int code;
static int count;
public:
void getcode()
{
code = ++count;
}
void displaycode()
{
cout<<"\nCODE :: "<<code;
}
static void displaycount()
{
cout<<"\nCOUNT :: "<<count;
}
};
int simple :: count; //definition of static data member
int main()
{
12 | P a g e
simple s1,s2;
s1.getcode();
s2.getcode();
simple::displaycount();
simple s3;
s3.getcode();
simple::displaycount();
s1.displaycode();
s2.displaycode();
s3.displaycode();
return 0;
}
The following function definition will not work:
static void displaycode()
{
cout<<code; //code is not static
}

Arrays of Objects:
We can have arrays of variables that are of type class. Such variables are called arrays of
objects.
class employee
{
private:
int eno;
char name[10];
public:
void getdata();
void putdata();
};
The identifier employee is a user-defined data type and can be used to create objects that
relate to different categories of employees. Examples are:
employee manager[3]; // array of manager
employee worker[30]; // array of worker
 The array manager contains three objects, namely manager[0], manager[1], and
manager[2]of type employee.

13 | P a g e
 Similarly, the foreman array contains 25 objects and the worker array contains 30
objects.
 Since an array of objects behaves like any other array, we can use the usual array
accessing methods to access individual elements and then the dot member
operator to access the member function.
For example, manager[i].getdata();
 will display the data of the ith element of the array manager.
class employee
{
private :
int eno;
char name[10];
public:
void getdata()
{
cout<<"\nEnter Employee No. :: ";
cin>>eno;
cout<<"Enter Name :: ";
cin>>name;
}
void putdata()
{
cout<<"\nRoll No : "<<eno;
cout<<"\nName : "<<name;
}
};
int main()
{
employee e[3];
for(int i=0;i<3;i++)
{
cout<<"\n Details of Manager"<<":"<<i+1;
e[i].getdata();
}
for(i=0;i<3;i++)
{
cout<<"\nMANAGER "<<i+1;
e[i].putdata();
14 | P a g e
}
return 0;
}
Objects as Function Arguments:
Objects may be used as a function argument. This can be done in two ways.
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function.
The first method is called pass-by-value. Since a copy of the object is passed to the
function, any changes made to the object inside the function do not affect the object used
to call the function. The second method is called pass-by-reference. When an address of
the object is passed, the called function works directly on the actual object used in the
call. This means that any changes made to the object inside the function will reflect in the
actual object. This method is more efficient because it requires to pass only the address
of the object and not the entire object.
The following program shows the use of objects as function arguments. It performs the
addition of time in the hour and minutes format.
class time
{
private:
int hours;
int minutes;
public:
void getdata(int h, int m)
{
hours=h;
minutes=m;
}
void putdata()
{
cout<<"\tHOURS : "<<hours;
cout<<"\tMINUTES : "<<minutes;
}
void sum(time t1,time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;

15 | P a g e
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
};
int main()
{
time t1,t2,t3;
t1.getdata(2,45);
t2.getdata(3,30);
cout<<"\nT1 = ";t1.putdata();
cout<<"\nT2 = ";t2.putdata();
t3.sum(t1,t2);
cout<<"\nT3 = ";
t3.putdata();
return 0;
}
The member function sum() is invoked by the object t3, with the objects t1 and t2 as
arguments. So that it can directly access the hours and minutes variable of t3. But the
members of t1 and t2 can be accessed only by using the dot operator like
(t1.mitues or t2.minutes). Therefore inside the function sum(), the variables hours and
minutes refer to t3 and t1.miutes and t2.minutes refer to t2.

Returning Objects:
A function cannot only receive objects as arguments but also can return them.
The following program shows how an object can be created (within a function) and
returned to another function.
class time
{
private:
int hours;
int minutes;
public:
void getdata(int h,int m)
{
hours=h;
minutes=m;
}
16 | P a g e
void putdata()
{
cout<<"\tHOURS : "<<hours;
cout<<"\tMINUTES : "<<minutes;
}
time sum(time t1, time t2);
};
time time :: sum(time t1,time t2)
{
time t;
t.minutes=t1.minutes+t2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+t1.hours+t2.hours;
return t;
}
int main()
{
time t1,t2,t3;
t1.getdata(2,45);
t2.getdata(3,30);
cout<<"\nT1 = "<<t1.putdata();
cout<<"\nT2 = "<<t2.putdata();
t3=t3.sum(t1,t2);
cout<<"\nT3 = "<<t3.putdata();
return 0;
}

Friend Function:
 The concept of encapsulation and data hiding dictate that non-member functions
should not be allowed to access an object’s private and protected members.
 A friend function is a function that can access the private/protected data
members of a class in which it is declared as a friend.
 If a keyword friend is placed before any function declared inside the class, that
function is known as friend function. The friend function is declared using the
friend keyword inside the body of the class, But friend function is not a member
function.
17 | P a g e
 The friend function definition must be outside the class and do not use the
keyword friend.
Why Friend keyword is used?
It is used to tell the compiler, that it is not a member function of the class. Rather it is a
friend function. Because if you remove the keyword friend, then this function gets
processed by compiler as member function of the class.
How to call Friend function?
Friend function has no object to call it. Because it is not a member function of the class
where it is declared. And to define it, there is no any membership label gets attached while
defining the function. Therefore, to call this function from main() function, just call it as
normal function call.
Characteristics of Friend function:
1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of that
class.
3. It can be invoked like a normal function without the help of any object.
4. Unlike member functions, it cannot access the member names directly and has to
use an object name and dot membership operator with each member name.(e.g.
A.x).
5. It can be declared either in the public or the private part of a class without affecting
its meaning.
6. Usually, it has the objects as arguments.
Example of Friend Function:
#include<iostream>
using namespace std;
class maths
{
private:
int a,b;
public:
void getdata(int x,int y)
{
a=x;

18 | P a g e
b=y;
}
friend void sum(maths m);
};
void sum(maths m)
{
int ans;
ans=m.a+m.b;
cout<<"\nAddition : "<<ans;
}
int main()
{
maths m;
m.getdata(10,20);
sum(m);
return 0;
}

Example of Friend Function with Multiple Classes:


#include<iostream>
using namespace std;
class XYZ;
class ABC
{
private:
int a;
public:
void geta()
{
a=10;
}
void puta()
{
cout<<"\n\nA IS : "<<a;
}
friend void sum(ABC,XYZ);
};
class XYZ
{

19 | P a g e
private:
int b;
public:
void getb()
{
b=20;
}
void putb()
{
cout<<"\n\nB IS : "<<b;
}
friend void sum(ABC,XYZ);
};
void sum(ABC p,XYZ q)
{
int c;
c=p.a+q.b;
cout<<"\n\nADDITION IS : "<<c;
}
int main()
{
clrscr();
ABC p;
XYZ q;
p.geta();
q.getb();
p.puta();
q.putb();
sum(p,q);
return 0;
}
Output: ADDITION IS : 30

Constructor:
One of the aims of C++ is to create user-defined data types such as classes that behave
like a built-in types. This means that we should be able to initialize a class type variable
i.e. object when it is declared, much the same way as the initialization of an ordinary
variable. For example,
20 | P a g e
int a=10;
A constructor is a special member function whose task is to initialize the objects of its
class. It is special because its name is the same as the class name. The constructor is
invoked whenever an object of its associated class is created. It is called a constructor
because it constructs the values of the data members of the class.
How the Constructors Are Different From A Member Function?
 Constructor can be called automatically when an object is created.
 The constructor name is same as of the class.
 It does not have the return type.
 If the constructor is not specified than the compiler will generate a default
constructor.
A constructor can be declared and defined as follows:
class simple
{
private:
int a, b;
public:
simple (); // constructor declared
void putdata ()
{
cout<<"\an = "<<a;
cout<<"\nab = "<<b;
}
};
simple :: simple() //constructor defined
{
a=10;
b=20;
}
Now, the declaration simple s; not only creates the object s of type simple but also
initializes its data members a and b to 10 and 20 respectively. There is no need to write
any statement to invoke the constructor function.

Characteristics of Constructor:
1. Constructor is declared in the public section.
21 | P a g e
2. Constructor is invoked automatically when the objects are created.
3. Constructors do not have return types, not even void and therefore, and they cannot
return values.
4. Constructor cannot be inherited, though a derived class can call the base class
constructor.
5. Like other C++ functions, constructor can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to constructor’s address.
8. An object with a constructor (or destructor) cannot be used as a member of a union.
9. They make ‘implicit calls’ to the operators new and delete when memory allocation is
required.

Types of Constructor:
1. Default Constructor
2. Parameterized constructor
3. Copy constructor

Default Constructor:
A constructor that accepts no parameters is called the default constructor. In the above
program simple() is a default constructor. It is also known as “Zero Argument/ Zero
Parameter Constructor”.
Similarly, the default constructor for the class A is A :: A(). If no such constructor is
defined, then a compiler supplies a default constructor. Therefore, the statement such as
A a;
invokes the default constructor of the compiler to create the object a.
Example:
#include<iostream>
using namespace std;
class simple
{
private:
int a,b;

22 | P a g e
public:
simple()
{
a=10;
b=20;
}
void putdata()
{
cout<<"\nA IS : "<<a;
cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s;
s.putdata();
return 0;
}

Parameterized Constructors:
The constructors that can take arguments are called parameterized constructors.
class simple
{
private:
int a,b;
public:
simple(int x, int y) // parameterized constructor
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{

23 | P a g e
simple s(10,20);
s.putdata();
return 0;
}

When a constructor has been parameterized, then we must pass the initial values as
arguments to the constructor function when the object is declared. This can be done in
three ways.
1. By calling the constructor explicitly (clearly called).
2. By calling the constructor implicitly (not clearly).
3. Initialization at the time of declaration with = operator

Implicit call:
The declaration of the object is followed by an argument list enclosed in parentheses. This
method is called shorthand method.
Example:
class simple
{
private:
int a,b;
public:
simple(int x, int y) // parameterized constructor
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
simple s(10,20); ;//Implicit Call
s.putdata();

24 | P a g e
return 0;
}
Explicit call:
The declaration of an object is followed by assignment operator; constructor name and
argument list are enclosed in parenthesis.
Example:
#include<iostream>
using namespace std;
class simple
{
private:
int a,b;
public:
simple(int x,int y)
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA IS : "<<a;
cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s=simple(10,20);//Explicit Call
s.putdata();
return 0;
}

Initialization at the time of declaration with = operator:


This way of calling is used for the constructor with exactly one argument. In this method,
declaration is followed by assignment operator and value to be initialized.
Example:
#include<iostream>
using namespace std;

25 | P a g e
class simple
{
private:
int a;
public:
simple(int x)
{
a=x;
}
void putdata()
{
cout<<"\nA IS : "<<a;
}
};
int main()
{
simple s=5;
s.putdata();
return 0;
}

Copy Constructor:
A copy constructor is used to declare and initialize an object from another object. For
example, the statement,
simple s2 (s1);
would create the object s2 and at the same time initialize it to the value of s1.
This can be done by another method as follows.
simple s4 = s1;
The process of initializing through a copy constructor is called copy initialization.
Now consider the following statement
s4 = s2;
This statement will not invoke the copy constructor. However, if s4 and s2 are objects,
this statement is legal and simply assigns the values of s2 to s4, member-to-member.
A reference variable can be used as an argument to the copy constructor. We cannot pass
the argument by value to the copy constructor.

26 | P a g e
When no copy constructor is defined, the compiler supplies its copy constructor.

Example:
class simple
{
private:
int a,b;
public:
simple() // default constructor
{
a=10;
b=20;
}
simple(int x,int y) // parameterized constructor
{
a=x;
b=y;
}
simple(simple &s) // copy constructor
{
a=s.a;
b=s.b;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
simple s1;
cout<<"OBJECT 1"<< s1.putdata();
simple s2(30,40);
cout<<"\nOBJECT 2"<<s2.putdata();
simple s3(s1);
cout<<"\nOBJECT 3"<<s3.putdata();
simple s4;
s4=s2;

27 | P a g e
cout<<"\nOBJECT 4"<<s4.putdata();
return 0;
}
Output would be as follows:
OBJECT 1 OBJECT 2 OBJECT 3 OBJECT 4
A=10 A=30 A=10 A=30
B=20 B=40 B=20 B=40

Multiple Constructors in a Class or Constructor Overloading:


When more than one constructor function is defined in a class then this process is known
as constructor overloading. Consider the following statements:
simple(); // no arguments
simple(int x, int y); // two arguments
In the first case, it supplies the data values, and no values are passed by the calling
program.
In the second case, the function call passes the appropriate values from main().
We can use these two constructor functions in the same class.
class simple
{
private:
int a,b;
public:
simple() //Default Constructor
{
a=10;
b=20;
}
simple(int x,int y) // Parameterized Constructor
{
a=x;
b=y;
}
simple(simple &s) //Copy constructor
{
a=s.a;
b=s.b;
}
28 | P a g e
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
simple s1;
cout<<"Object 1";
s1.putdata();
simple s2(30,40);
cout<<"\nObject 2";
s2.putdata();
simple s3(s1);
cout<<"\nObject 3";
s3.putdata();
return 0;
}
 The declaration simple s1; would automatically invoke the first constructor and
set both a and b of s1 to 10 and 20.
 The statement simple s2(30,40); would call the second constructor and set both
a and b of s2 to 30 and 40 respectively.
 Finally, the statement simple s3(s1); would invoke the third constructor which
copies the values of s1 into s3. Such a constructor is called a copy constructor.

Constructor with Default Arguments:


 It is possible to define constructors with default arguments. For example, the
constructor simple can be declared as:
simple( int x, int y, int z=30);
the default value of the argument z is 30. then the statement simple s(10,20);
assigns the value 10 to x, 20 to y and 30 to z.
 However, the statement simple s (10,20,50); assigns the value 10 to x, 20 to y, and
50 to z.
 When an actual parameter is specified it overrides the default value.
 The missing arguments must be the trailing ones.
29 | P a g e
Ambiguity between default constructor and constructor with default arguments:
class simple
{
private:
int a;
public:
simple (int x=10) //Constructor with Default Arguments
{
a = x;
}
simple() //Default Constructor
{
a = 20;
}
};
As shown above, when both default constructor and constructor with default argument
are used it causes an ambiguity when an object is created as follows.
simple s;
An ambiguity is whether to call simple () or simple (int x=10).

Destructors:
A destructor is used to destroy the objects that have been created by a constructor.
A destructor is a member function whose name is the same as the class name but
proceeded by a tilde symbol.
Eg. A destructor for the class simple can be defined as follows:
~ simple ();
A destructor never takes any argument. it does not return any value. It will be invoked
implicitly by the compiler upon exit from the block or function or a program as the case
may be to clean up the storage.
It is good practice to use a destructor in a program because it releases the memory space
for future use.
Characteristics of Destructor:
1. Destructor is also a special member function like constructor.
2. Destructor destroys the memory of class objects’ created by constructor.

30 | P a g e
3. Destructor has the same name as their class name preceded by a tilde (~) symbol.
4. It is not possible to define more than one destructor.
5. Destructors take no arguments. Therefore, destructors cannot be overloaded.
6. Destructor neither requires any returns value.
7. It is automatically called to destroy the memory of object.
8. Destructor release memory space occupied by the objects created by constructor.
9. In destructor, objects are destroyed in the reverse order of an object creation.
class simple
{
private:
static int count;
public:
simple ()
{
count++;
cout<<"\nNumber of Objects created : "<<count;
}
~simple()
{
cout<<"\nNumber of Objects destroyed :"<<count;
count - - ;
}
};
int simple::count;
int main()
{
simple s1,s2,s3,s4;
{
cout<<"\n\n\t BLOCK 1";
simple s5;
}
{
cout<<"\n\n\t BLOCK 2";
simple s6;
}
cout<<"\n\n\t MAIN BLOCK";
return 0;
}
31 | P a g e
 As the objects are created and destroyed, they increase and decrease the value of
the count. When a closing brace of a scope is encountered, the destructor is called.
 After the first group of objects is created, s5 is created and then it is destroyed.
 Then s6 is created and then destroyed. Finally, the rest of the objects are
destroyed.
 The objects are destroyed in the reverse order of creation.
Difference between Construcor and Destrctor:
Constructor Destructor
1. Constructor is a special member 1. Constructor is a special member function,
function, which is called automatically which is called automatically when an object
when an object is created. is destroyed
2. Syntax: classname (arguments) 2. Syntax: ~classname()
3. Example: simple() 3. Example: ~simple()
4. Arguments can be passed to the 4. Arguments cannot be passed to the
constructor. destructor.
5. Constructors cannot be virtual. 5. Destructor can be virtual.
6. It has the same name as its class 6. It has the same name as its class but is
prefixed by ~(Tilde) character.
7. A class can have more than one 7. A class cannot have more than one
constructor destructor
8. A constructor can be overloaded. 8. The destructor cannot be overloaded.
9. It is used to allocate the resources to 9. It is used to release all the resources
the object of a class. allocated to the object of a class.

this Keyword:
 In C++, this is a special pointer available inside non-static member functions of a
class. It points to the current instance of the class that invoked the member
function.
Key Features of this Keyword:
 Accessing the Current Object: This holds the address of the object that called the
member function.
32 | P a g e
 Resolving Name Conflicts: Used to differentiate between instance variables and
parameters with the same name.
 Returning the Current Object: Enables function chaining by returning the object
itself.
 Accessing Members of the Current Object: this->member is equivalent to
member but explicitly refers to the instance variable.
Example:
class simple
{
private:
int a;
int b;
public:
void getdata(int a,int b)
{
this->a = a;
this->b = b;
}
void putdata()
{
cout<<"\nA IS : "<<a; cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s;
s.getdata(10,20);
s.putdata();
return 0;
}
Explanation:
 this is a pointer that refers to the current object.
 In getdata(int a, int b), local parameters a and b have the same names as class
members.
 this->a = a; differentiates the instance variable a from the parameter a.
 Similarly, this->b = b; assigns the value to the instance variable b.

33 | P a g e

You might also like