Unit II Classes and Objects, Constructors and Destructors-1
Unit II Classes and Objects, Constructors and Destructors-1
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.
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:
// 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;
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";
}