0% found this document useful (0 votes)
28 views86 pages

Unit II Classes and Objects, Constructors and Destructors-1

Uploaded by

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

Unit II Classes and Objects, Constructors and Destructors-1

Uploaded by

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

CLASSES AND

OBJECTS,
CONSTRUCTORS AND
DESTRUCTORS
Unit - II

M. Parameswari
Assistant Professor,
Department of Information Technology,
Sona College of Technology, Salem.
Classes and Objects: Class specification- Member
function definition- Nested member function- Access
qualifiers- Static data members and member functions -
Instance creation- Array of objects- Dynamic objects-
Static Objects- Objects as arguments- Returning objects.

Constructors and Destructors: Constructors –


Parameterized constructors- Overloaded Constructors-
Constructors with default arguments-Copy constructors-
Dynamic constructors-Dynamic initialization using
constructors- Destructors.
Classes and Objects
Introduction
• Defining variables of a class data type is known as a
class instantiation and such variables are called objects.
(Object is an instance of a class.)
• A class encloses both the data and functions that
operate on the data, into a single unit as shown in
Figure.
• The variables and functions enclosed in a class are
called data members and member functions respectively.
• Member functions define the permissible operations on
the data members of a class.
• Class follows the principle that the information about a
module should be private to the module unless it is
specifically declared public.
Class specification
Class specification
• A class can be described as a collection of data
members along with member functions.
• This property of C++, which allows the association of
data and functions into a single unit, is called
encapsulation.
Data Members

Member Functions
• The keyword class indicates that the name which
follows(ClassName) is an abstract data type.
• The body of a class contains declaration of variables
and functions, collectively known as members.
• These members are usually grouped under two
sections, private and public, which define the visibility of
members.
• The members in the beginning of a class without any
access specifier are private by default.
• Hence, the first use of the keyword private in a class is
optional.
• It is a general practice to declare data members as
private and member functions as public.
Point to remember
• The data member name appears in the student class
(E.g roll.No) can appear in the another class
declarations also, but their scope is limited to their
respective classes.
• However, more than one class with the same
class_name in a program is an error.
• A class can have multiple member functions (but not
data members) with the same name as long as they
differ in terms of signature; this feature is known as
method overloading.
Class Object
• A class specification only declares the structure of objects
and it must be instantiated in order to make use of the
services provided by it.
• An example of class instantiation for creating objects is
shown below:
class student s1; //class keyword is optional.
or
student s1;
• It creates the object s1 of the class student. More than one
object can be created with a single statement as follows:
class student s1, s2, s3, s4;
or
student s1, s2, s3, s4;
• It creates multiple objects of the class student.
• Objects can also be created by placing their names
immediately after the closing brace like in the creation
of the structure variables.
class student
{
....
....
} s1, s2, s3, s4;
Accessing Class Members
• To access data members of a class we can use
member access operator dot(.). The syntax as follows:
• E.g
s1.setdata(10, “Rajkumar”);
s1.outdata();
#include<iostream> int main()
#include<string> {
#include<cstring> student s1;
using namespace std;
student s2;
class student
{
s1.setdata(1, "Tejaswi");
private:
s2.setdata(10, "Rajkumar");
int roll_no;
char name[ 20 ];
public: cout << "Student details..." << endl;
void setdata(int roll_no_in, char
*name_in) { s1.outdata();
roll_no = roll_no_in;
s2.outdata();
strcpy( name, name_in);
}
}
void outdata() {
cout << "Roll No = "<< roll_no << endl;
cout << "Name = "<< name << endl;
} };
Member function
Defining Member function
• The data members of a class must be declared within
the body of the class, whereas the member functions
of the class can be defined in any one of the following
ways:
• Inside the class specification
• Outside the class specification
Member Functions Inside the Class Body
• The syntax for specifying a member function
declaration is similar to a normal function definition
except that it is enclosed within the body of a class.
• All the member functions defined within the body of a
class are treated as inline by default.
Member Functions Outside the Class Body
• Another method of defining a member function is to
declare a function prototype within the body of a class
and then define it outside the body of a class.
• The mechanism to binding the functions to the class to
which they belong is done by using the scope
resolution operator(::).
// date.cpp void date::show() // definition
#include <iostream> {
using namespace std;
cout << day << "-"<< month << "-"
class date << year << endl;
{ }
private:
int main()
int day;
{
int month;
date d1, d2, d3;
int year;
public: d1.set( 26, 3, 1958 );
void set(int DayIn, int MonthIn, int YearIn); d2.set( 14, 4, 1971 );
//declaration d3.set( 1, 9, 1973 );
void show(); // declaration
cout << "Birth Date First Author: ";
};
d1.show();
void date::set(int DayIn, int MonthIn, int
YearIn) //definition cout << "Birth Date Second Author:
{
";
day = DayIn; d2.show();
month = MonthIn; cout << "Birth Date Third Author: ";
year = YearIn; d3.show();
}
Outside Member Functions as inline
• It is a good practice to declare the class specification
first and then implement class member functions
outside the class specification.
• Member functions declared outside the class
declaration can be made inline by prefixing the inline to
its definition as shown below.
When to Use inline Functions
• In general, inline functions should not be used.
• Defining inline functions can be considered once a fully
developed and tested program runs too slowly and
shows bottlenecks in certain functions.
• It is only useful to implement an inline function if the
time spent during a function call is more compared to
the function body execution time.
Nested member function
Accessing Member Functions within the Class
• A member function of a class can call any other
member function of its own class irrespective of its
privilege and this situation is called nesting of member
functions.
// nesting.cpp // Nesting of member function
#include <iostream> void ShowMax()
using namespace std;
{
class NumberPairs
// calls member function max()
{
int num1, num2; // private by default cout << "Maximum = " << max();
public: }
void read() };
{ int main()
cout << "Enter First Number: ";
{
cin >> num1;
NumberPairs n1;
cout << "Enter Second Number: ";
cin >> num2; n1.read();
} n1.ShowMax();
int max() }
{
if(num1 > num2)
return num1;
else
return num2;
}
Access qualifiers
Access specifiers / Access qualifiers
• Access specifiers define how the members
(attributes and methods) of a class can be
accessed.
• In C++, there are three access specifiers:
• public - members are accessible from outside the class
• private - members cannot be accessed (or viewed) from
outside the class
• protected - members cannot be accessed from outside
the class, however, they can be accessed in inherited
classes.
Objects as arguments
Passing Objects as Arguments
• It is possible to have functions which accept objects of
a class as arguments, just as there are functions which
accept other variables as arguments.
• Like any other data type, an object can be passed as
an argument to a function by the following ways:
• pass-by-value, a copy of the entire object is passed to
the function
• pass-by-reference, only the address of the object is
passed implicitly to the function
• pass-by-pointer, the address of the object is passed
explicitly to the function
Passing Objects by Value
// distance.cpp: distance cout << "Enter feet: "; cin >> feet;
manipulation in feet and inches cout << "Enter inches: "; cin >> inches;
#include <iostream> }
using namespace std; void show()
class distance {
{ cout << feet << "' - " << inches << "\"";
private: }
float feet; void add(distance d1, distance d2)
float inches; {
public: feet = d1.feet + d2.feet;
void init( float ft, float in ) inches = d1.inches + d2.inches;
{ if(inches >= 12.0)
feet = ft; {
inches = in; // 1 foot = 12.0 inches
} feet = feet + 1.0;
void read() inches = inches - 12.0;
{ }
}
};
Passing Objects by Value
int main()
{
class distance d1, d2, d3;
d2.init(11.0, 6.25 );
d1.read();
cout << "d1 = "; d1.show();
cout << "\nd2 = "; d2.show();
d3.add(d1, d2); // d3 = dl + d2
cout << "\nd3 = d1+d2 = "; d3.show();
}
Passing Objects by Reference
//reference.cpp int main()
#include <iostream> {
using namespace std; int a =10;
class ref_fun{ cout<<"Value of A: "<<a<<endl;

public: ref_fun f1;


void fun(int &b); f1.fun(a);
}; cout<<"Value of A after calling
member function: "<<a<<endl;
void ref_fun::fun(int &b)
return 0;
{
}
b=20;
}
Passing Objects by Pointer
• The above program requires the following changes if
parameters are to be passed by pointer:
1. The prototype of the member function fun() has to be
changed to:
void fun(int *b);
2. The definition of the member function fun() has to be
changed to:
void ref_fun::fun(int *b)
{
*b=20;
}
3. The Calling function changed to: f1.fun(&a);
Returning objects
Returning Objects from Functions
• Similar to sending objects as parameters to functions, it
is also possible to return objects from functions.
• The return type of the function is declared as the return
object type.
return (Obj_Name);
Friend Function
Instance creation
Instance creation
• An Object is an instance of a Class. When a class is
defined, no memory is allocated but when it is
instantiated.
• To use the data and access functions defined in the
class, you need to create objects.
• When an object passes value/arguments then an
instance is created.

Static data members and
member functions
Static Objects
Static data members
• C++ allows defining static data members within a class
using the static keyword.
• When a data member is declared as static, then we
must keep the following note in mind:

• Irrespective of the number of objects created, only a


single copy of the static member is created in memory.
• All objects of a class share the static member.
• All static data members are initiated to zero when the
first object of that class is created.
• The static data members can be initialized during their
definition outside all the member functions, in the same
way as global variables are initialized.
Without static keyword
#include <iostream> int main()
using namespace std;
class MyClass{
{
private: MyClass S1, S2, S3;
int count = 0; S1.set_count();
public:
S1.show_count();
void set_count() S2.set_count();
{
S2.show_count();
count++;
} S3.set_count();
void show_count() S3.show_count();
{
}
cout << count << '\n';
}
};
static keyword
#include <iostream> int MyClass::count = 0;
using namespace std;
class MyClass{
private: int main()
static int count; {
MyClass S1, S2, S3;
public:
void set_count() S1.set_count();
{ S1.show_count();
count++;
}
S2.set_count();
void show_count() S2.show_count();
{ S3.set_count();
cout << count << '\n';
}
S3.show_count();
}; }
Static Member Functions
• Static functions can access only the static
members(data or function) declared in the same class;
non static data are unavailable to these functions.
• Static data members must be defined and initialized like
global variables, otherwise the linker generates errors.
• Static members defined as public can either be
accessed through the scope-resolution operator as
ClassName::MemberName
or through the object of a class as
ObjectName.MemberName
// dirs.cpp: static data and void Directory::setpath(char
member functions of a class const *newpath)
#include <iostream> {
#include <string> strcpy( path, newpath);
#include <cstring> }
using namespace std; int main()
class Directory {
{ cout << "Path: " <<
Directory::path << endl;
public:
Directory::setpath ("/usr");
static char path []; cout << "Path: " <<
static void setpath( char Directory::path << endl;
const *newpath ); Directory dir;
}; dir.setpath("/etc");
char Directory::path [199] = cout << "Path: " << dir.path;
"/usr/raj"; }
• The static member functions are special functions used
to access the static data members or other static
member functions.
• A member function is defined using the static keyword.
A static member function shares the single copy of the
member function to any number of the class' objects.
• We can access the static member function using the
class name or class' objects. If the static member
function accesses any non-static data member or non-
static member function, it throws an error.
#include <iostream>
using namespace std;
class Note
{
// declare a static data member
static int num;

public:
// create static member function
static int func ()
{
return num;
}
};
int Note :: num = 5;

int main ()
{
// access static member function using the class name a
nd the scope resolution
cout << " The value of the num is: " << Note:: func () <<
endl;
return 0;
}
Array of objects
Array of objects
• C++ allows the user to create an array of any data type
including user-defined data types.
• Thus, an array of variables of a class data type can
also be defined, and such variables are called an array
of objects.
class student void main()
{ {
private: int i, roll_no;
int roll_no; char name[20];
char name[ 20 ]; student s[10]; // array of 10
Public: objects
void setdata( int roll_no_in, char for (i = 0; i < 10; i++)
*name_in ){ {
roll_no = roll_no_in; cout << “Enter Roll no. of student:
strcpy( name, name_in ); “;
} cin >> roll_no;
void outdata() cout << “Enter Name of student: “;
{cout << “Roll No = “ << roll_no << cin >> name;
end1; s[i].setdata( roll_no, name );
cout << “Name = “ << name <<
}
end1;
------------
}
-------------
};
}
Constructors and Destructors
Constructors
Constructors
• Constructor in C++ is a special method that is invoked
automatically at the time of object creation.
• It is used to initialize the data members of new objects
generally.
• The constructor in C++ has the same name as the
class or structure. Constructor is invoked at the time of
object creation.
• Constructor does not have a return value, hence they
do not have a return type.
• The prototype of Constructors is as follows:
<class-name> (list-of-parameters);
• Constructors can be defined inside or outside the class
declaration:-
• The syntax for defining the constructor within the class:
<class-name> (list-of-parameters)
{ // constructor definition }
• The syntax for defining the constructor outside the
class:
<class-name>: :<class-name> (list-of-parameters)
{ // constructor definition}
// defining the constructor within the class void display()
#include <iostream> {
using namespace std; cout << endl << rno << "\t" << name << "\
class student { t" << fee;

int rno; }

char name[10]; };

double fee;
public: int main()

student() {

{ student s;

cout << "Enter the RollNo:"; s.display();

cin >> rno; return 0;

cout << "Enter the Name:"; }

cin >> name;


cout << "Enter the Fee:";
cin >> fee;
}
• A constructor has the following characteristics:
• It has the same name as that of the class to which it
belongs.
• It is executed automatically whenever the class is
instantiated.
• It does not have any return type.
• It is normally used to initialize the data members of a
class.
• It is also used to allocate resources such as memory to
the dynamic data members of a class.
Dynamic objects
Dynamic objects
• A class can be instantiated at runtime and objects
created by such instantiation are called dynamic
objects.
• The program must guarantee that each dynamic object is
deleted when it is no longer needed, and certainly before it
becomes garbage.
• For each dynamic allocation, a policy that determines the
object’s lifetime must be found by the programmer and
implemented.
• Objects with scoped lifetimes are created in the stack memory.
• Objects with arbitrary lifetimes are created in the heap
memory.
Pointers to Objects
• The C++ language defines two operators which are
specific for the allocation and deallocation of memory.
• These operators are new and delete.
• A pointer to a variable can be defined to hold the
address of an object, which is created statically or
dynamically.
• Such pointer variables can be used to access data or
function members of a class using the * or -> operators.
• New – used to get the address of the allocated
memory.
• Delete - operator is used to release the memory
allocated to the dynamic object by the new operator.
Pointer to Object
• Pointer to Object –
• Accessing Members of Objects –
• Creating and Deleting Dynamic Objects –
• Dereferencing Pointers –
• Reference to Dynamic Objects –
Accessing Members of Objects
Creating and Deleting Dynamic Objects
• A dynamic object can be created by the execution of a
new operator expression.
ptr_to_object = new ClassName;
• Once a pointer is holding the address of a dynamic
object, its members can be accessed by using the ->
operator.
• The syntax of the delete operator releasing memory
allocated to a dynamic object is as follows:
delete ptr_to_object;
Destructors
Destructors
• When an object is no longer needed, it can be destroyed.
• Destructor is a member function having the character
~(tilde).
• Similar to constructors, a destructor must be declared in the
public section of a class so that it is accessible to all its
users.
• A class cannot have more than one destructor.
// ptrobj.cpp: pointer to object, pointing to void show()
dynamically created objects
{
# include <iostream>
cout << "data1 = " <<
using namespace std; data1<<endl;
class someclass cout << " data2 = " << data2
{ << endl;
public: }
int data1; };
char data2; int main (void)
someclass() {
{ someclass *ptr;
cout << "Constructor cout << "Creating dynamic
someclass() is invoked\n"; object..." << endl;
data1 = 1; data2 = 'A'; ptr = new someclass();
} cout << "Accessing dynamic
~someclass() object through ptr->show()..." << endl;
{ ptr->show();
cout << "Destructor cout << "Destroying dynamic
~someclass() is invoked\n"; object..." << endl;
} delete ptr;
Parameterized constructors
Parameterized constructors
• It is possible to pass arguments to constructors.
Constructors with arguments are called parameterized
constructors.
• 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.
// parameterized constructors int getX() { return x; }
#include <iostream> int getY() { return y; }
using namespace std; };

class Point { int main()


private: {
int x, y; Point p1(10, 15);
public: cout << "p1.x = " << p1.getX() <<
// Parameterized ", p1.y = " << p1.getY();
Constructor return 0;
Point(int x1, int y1) }
{
x = x1;
y = y1;
}
Overloaded Constructors
Overloaded Constructors
• An interesting feature of the constructors is that a class can
have multiple constructors. This is called constructor
overloading.
• All the constructors have the same name as the
corresponding class, and they differ only in terms of their
signature (in terms of the number of arguments, or data
types of their arguments, or both)
class AccClass AccClass(int acval, float bal) //
Constructor no.3
{
{
private:
---------------
int accno;
}
float balance;
void main()
public:
{
AccClass() // Constructor no.1
int trans_money;
{
---------
AccClass acc1; // uses constructor 1
--------- AccClass acc2(10); // uses constructor 2
} AccClass acc3( 20, 750.5 ); //costr 3
AccClass(int an) // Constructor no.2 ------------
{ ------------
------------------- ---------
} }
Constructors with default
arguments
Constructors with default arguments
• Constructors can also be defined with default arguments.
• If any arguments are passed during the creation of an
object, the compiler selects the suitable constructor with
default arguments.
class AccClass AccClass(int acval, float bal) //
Constructor no.3
{
{
private:
---------------
int accno;
}
float balance;
void main()
public:
{
AccClass() // Constructor no.1
int trans_money;
{
---------
AccClass acc1; // uses constructor 1
--------- AccClass acc2(10); // uses constructor 2
} AccClass acc3( 20, 750.5 ); //costr 3
AccClass(int an=5) // Constructor ------------
no.2
------------
{
---------
-------------------
}
}
Dynamic initialization using
constructors
Dynamic initialization through constructors
• Object’s data members can be dynamically initialized
during runtime, even after their creation.
• The advantage of this feature is that it supports
different initialization formats using overloaded
constructors.
// name.cpp: object with different name name::name( char *FirstName, char
pattern *MiddleName, char *LastName )
#include <iostream> {
#include <string> strcpy( first, FirstName );
#include<cstring> strcpy( middle, MiddleName );
using namespace std; strcpy( last, LastName );
class name }
{ void name::show( char *msg )
private: {
char first[15]; cout << msg << endl;
char middle[15]; cout << "First Name: " << first << endl;
char last[15]; if( middle[0] )
public: cout << "Middle Name: " << middle << endl;
name() if( last[0] )
{ cout << "Last Name: " << last << endl;
first[0] = middle[0] = last[0] = '\0'; }
} int main()
name( char *FirstName ); {
name( char *FirstName, char *MiddleName ); name nl, n2, n3;
name( char *FirstName, char *MiddleName, nl = name( "Raj" );
char *LastName); n2 = name( "Sheela", "S" );
void show( char *msg ); n3 = name( "Venkat", "K", "R" );
};
inline name::name( char *FirstName ) nl.show( "First person details..." );
//constructor outside the class n2.show( "Second person details..." );
{ n3.show( "Third person details..." );
strcpy( first, FirstName ); };
middle[0] = last[0] = '\0';
}
inline name::name(char *FirstName, char
*MiddleName)
{
strcpy( first, FirstName );
strcpy( middle, MiddleName );
last[0] = '\0';
}
Copy constructors
Copy constructors
• A Copy constructor is an overloaded constructor used to
declare and initialize an object from another object and it is a
member function that initializes an object using another
object of the same class.
• In simple terms, a constructor which creates an object by
initializing it with an object of the same class, which has
been created previously is known as a copy constructor.
Classname (classname & objectname)
// C++ program a COPY // Copy constructor
CONSTRUCTOR Point(Point& p1)
{
#include <iostream>
x = p1.x;
using namespace std;
y = p1.y;
class Point { }
private:
int getX() { return x; }
int x, y;
int getY() { return y; }
public:
};
Point(int x1, int y1)
{ int main()

x = x1; {
Point p1(10, 15);
y = y1;
Point p2 = p1;
} cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX()
<< ", p2.y = " << p2.getY();
return 0;
}
Dynamic Constructors
Dynamic Constructors
• When allocation of memory is done dynamically using
dynamic memory allocator new in a constructor, it is known
as dynamic constructor. By using this, we can dynamically
initialize the objects.
#include <iostream>
using namespace std; void display()
{
class dynamic { cout << p << endl;
const char* p; }
};
public:
dynamic() int main()
{ {
// allocating memory at run dynamic obj;
time obj.display();
p = new char[20]; }
p = "Dynamic Value";
}

You might also like