0% found this document useful (0 votes)
7 views

C++ Unit 3

This document covers the concepts of classes and objects in programming, detailing class definitions, member functions, and data members. It explains constructors, destructors, and the use of static data members, along with methods for passing objects to functions and the role of friend functions. Additionally, it provides examples of default, parameterized, and copy constructors, illustrating how to create and manipulate objects in a class.

Uploaded by

nithyaselvam394
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)
7 views

C++ Unit 3

This document covers the concepts of classes and objects in programming, detailing class definitions, member functions, and data members. It explains constructors, destructors, and the use of static data members, along with methods for passing objects to functions and the role of friend functions. Additionally, it provides examples of default, parameterized, and copy constructors, illustrating how to create and manipulate objects in a class.

Uploaded by

nithyaselvam394
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/ 53

UNIT - 3

SYLABUS

Classes and Objects : Class – Defining


member functions – Static Data Member –
Passing Objects to Function – Returning
Objects – Friend Function – Default
Arguments – Constructor – Types of
constructor – Destructor.
CLASS
CLASS
Class:
Class is a user-defined data-type. It is the blueprint from which
individual objects are created. A class can be defined as a
template/blueprint that describes the behavior/state of the object.
A class contains members like data members and member functions .
Data members are variables of the class.
Member functions are the methods that are used to manipulate
data members.
Data members define the properties of the class whereas the
member functions define the behavior of the class.
CLASS
class is a way to bind the data and itse associated function together. It
allows the data and function to be hidden from external use, if necessary.

Class specification has two parts:


1. Class declaration.
2. Class function definitions.

Class Declaration:

Class declaration describes the type and scope of its members.


CLASS
Syntax:

Class class_name
{
Private:
Variable declaration;
Function declaration;

Public:
Variable declaration;
Function declaration;
}
CLASS
The body of the class enclosed within braces and terminated by a
semicolon. The class body contains the declaration of variables and
functions. These functions and vasraibles are collectively called as class
members.
The class members that have been declared as private can be
accessed only from with in the class and public members can be
accessed from outside the class.

Note: by default, means access specifiers is not given, the class members
are considered as private.
CLASS
CLASS
CLASS
Eg: If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.

Example:
public class Dog
{
String breed; // Data Member
int age; // Data Member
String color; // Data Member
void barking() // Member Function
{
}
void hungry() // Member Function
{
}

void sleeping() // Member Function

{
}
}
CLASS
Class function Definition:
It describes how the class functions are implemented. Methods
are functions that belongs to the class.

There are two ways to define functions that belongs to a class:


Inside class definition – Defining the function inside the class.
Outside class definition – Defining the function outside the class.
CLASS
Inside class definition:
Another method of defining a member function is to replace the
function declaration by the actual function definition inside the class.

Example:
Class item
{
Int number;
Float cost;
Public:
Void getdata(int a, float b);
Void putdata(void)
{
Cout<<number<<”\n”;
Cout<<cost<<”\n”;
}
};
CLASS
Outside class definition:
Here Member functions are only declared inside the class and should be
defined ouside the class.

Syntax:
returnType class_name :: function_name ( argument declaration)
{
Function body
}
CLASS
Example:
void item :: getdata ( int a, float b)
{
Number = a;
Cost = b;
}

Void item :: putdata(void)


{
Cout<< “number :” << number<<”\n”;
Cout<<”cost:”<< cost<<”\n”
}
CLASS
Creating Objects:
Once class has been declared, we wcan create variables of that
type by using the class name. these class variables are called Objects.
Only public class members can be accessed.

Objects: bulldog, German Sheprard, golden Retriever, Pug etc

When a class is defined, no memory is allocated but when it is


instantiated (i.e. an object is created) memory is allocated.

Example:
item x;
item x, y, z;
CLASS
Accessing class members:
We can access the class members ( data members and functions) using objects.

Syntax:

objectName.functionName(actual_ arguments)

example:
x.getdata(100,75.5);
x.putdata();
example:
class alpha
{
int x;
int y;
public:
int z;
};

alpha p;
p.x = 5; // error , x is private
p.z=10 // valid.
CLASS
CLASS
Static Data Member
A data member of a class can be qualified as static. A static
member variable has certain special characteristics. These are:
1. It is initialized to zero when the first object of its class is created, no
other intialization is permitted.
2. Only one copy of that member is created for the entire class and is
shared by all the objects or class, no matter how many objects are
created.
3. It is visible only within the class, but lifetime is the entire program.

Static variables are normally used to maintain values common to


the entire class.
Example:
Static variables can be used as a counter that records the occurrences of
all the objects.
Static Data Member
Static Data Member
Static Data Member
Passing Objects to Functions
Passing Objects to Functions
Object as function Arguments: ( Passing Objects to Functions):
Two types:
1. Pass by value - a copy of the entire object is passed to the function.
2. Pass by reference - only the address of the object is transferred to the
function.

The objects of a class can be passed as arguments to member functions


either by value or by reference.
Passing Objects to Functions
Pass by value:
When an object is passed by value, a copy of the actual object is created
inside the function. This copy is destroyed when the function terminates.
Moreover, any changes made to the copy of the object inside the function are
not reflected in the actual object.

Pass by value example:


#include <iostream>
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
Passing Objects to Functions
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
Demo d1; //object declarations
Demo d2;
Demo d3;

d1.set(10); //assigning values to the data member of objects


d2.set(20);

d3.sum(d1,d2); //passing object d1 and d2


d1.print(); //printing the values
d2.print();
d3.print();

return 0;
}
Passing Objects to Functions
Output:
value of A: 10
value of A: 20
value of A: 30
Passing Objects to Functions
Pass by reference:
In pass by reference, only a reference ( address of the object) to that
object (not the entire object) is passed to the function. Thus, the changes made
to the object within the function are also reflected in the actual object.

Example:
#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
Passing Objects to Functions
void sum(Demo &ob1, Demo &ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
Passing Objects to Functions
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1,d2);

//printing the values


d1.print();
d2.print();
d3.print();

return 0;
}
Passing Objects to Functions
Output:
value of A: 10
value of A: 20
value of A: 30
Friend Function
Friend function:

A friend function is a function that is specified outside a class but


has the ability to access the protected and private data of a class. A
friend can be a member’s function of a class. In special cases when a
class’s private data needs to be accessed directly without using
objects of that class, we need friend functions.
Friend Function
Special features of friend functions:
 A friend function does not fall within the scope of the class for which it
was declared as a friend. Hence, functionality is not limited to one
class.
 The friend function can be a member of another class or a function that
is outside the scope of the class.
 A friend function can be declared in the private or public part of a class
without changing its meaning.
 Friend functions are not called using objects of the class because they
are not within the class’s scope.
 Without the help of any object, the friend function can be invoked like a
normal member function.
 Friend functions can use objects of the class as arguments.
 A friend function cannot explicitly access member names directly.
Friend Function
Syntax:
class className
{
//Friend function declaration
Friend returnType functionName(arg list);
};

Eg:
#include<iostream.h>
#include<conio.h>
class sample
{
int a;
Public:
void get(), put();

//Friend Function Declaration


friend void exchange(sample &s1,sample &s2);
};
Friend Function
void exchange(sample &s1,sample &s2)
{
int t=s1.a;
s1.a=s2.a;
s2.a=t;
}
void sample::get()
{
cout<<"\nEnter an Integer value=";
cin>>a;
}

void sample::put()
{
cout<<"\nThe value is ="<<a<<endl;
}
Friend Function
int main()
{
cout<<"\n\t\tSWAPPING OF VALUES";
Sample x,y;
x.get();
y.get();
cout<<"\nBefore swapping\n";
x.put();
y.put();
exchange(x,y);
cout<<"\nAfter swapping\n";
x.put();
y.put();
getch();
return 0;
}
Friend Function
Output:
SWAPPING OF VALUES
Enter an Integer value= 5
Enter an Integer value= 6

Before swapping
The value is = 5
The value is = 6

After swapping
The value is = 6
The value is = 5
Returning Objects
Returning Objects:
A function can receive the object as an argument and can also return the
object to the called function.

Example:
#include <iostream>
using namespace std;

class Student
{
public:
double marks1, marks2;
};

Student createStudent()
{
Student student;
student.marks1 = 96.5;
student.marks2 = 75.0;
Returning Objects
// print member variables of Student
cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;
return student;
}

int main()
{
Student student1;

// Call function
student1 = createStudent();

return 0;
}
Returning Objects
Output:

Mark1 = 96.5
Mark2 = 75.6
CONSTRUCTOR
CONSTRUCTOR
Constructor:
A constructor is a special type of member function of a
class which initializes objects of a class. In C++, Constructor is
automatically called when object (instance of class) is created. It is a
special member function of the class because it does not have any return
type.

How are constructors different from a normal member function?


 A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself.
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 It must be placed in public section of class.
 If we do not specify a constructor, C++ compiler generates a default
constructor for object.
CONSTRUCTOR
Types of Constructor
Types of Constructors
1. Default Constructors: Default constructor is the constructor which doesn’t take
any argument. It has no parameters.

Example:
#include <iostream>

class sample
{
public:
int a, b;

// Default Constructor
sample()
{
a = 10;
b = 20;
}
};
Types of Constructor
int main()
{
// Default constructor called automatically when the object is created
sample c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 0;
}

Output:
a: 10
b: 20
Types of Constructor
2. Parameterized Constructors:
It is possible to pass arguments to constructors. Typically, these arguments
help initialize an object when it is created.

// parameterized constructors
#include <iostream>

class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
Types of Constructor
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}

Output:
p1.x = 10, p1.y = 15
Types of Constructor
Uses of Parameterized constructor:
 It is used to initialize the various data elements of different objects with
different values when they are created.
 It is used to overload constructors.
3.Copy Constructor:
A copy constructor is a member function which initializes an object
using another object of the same class.

Example:
#include <iostream>
class sample
{
public:
int x;
sample(int a) // parameterized constructor.
{
x=a;
}
Types of Constructor
sample(sample &i) // copy constructor
{
x = i.x;
}
};

int main()
{
sample a1(20); // Calling the parameterized constructor.
sample a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Output:
20
DESTRUCTOR
DESTRUCTOR
Destructor:

Destructor works opposite to constructor; it destroys the objects


of classes. It can be defined only once in a class. Single destructor will
destroy any number of objects created within a class. Like constructors,
it is invoked automatically.
A destructor is defined like a constructor. It must have the same
name as class. But it is prefixed with a tilde sign (~). C++ destructor
cannot have parameters.
DESTRUCTOR
Example:
#include <iostream>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};

int main(void)
{
Employee e1; //creating an object of Employee
DESTRUCTOR
Employee e2; //creating an object of Employee
return 0;
}

Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

You might also like