unit 2- Objects Classes & Constructor (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Object Oriented Programming using c++

Unit 2: Object, Classes & Constructor


Class
1. In C++, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }

2. 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;
3. 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.

C++ Object and Class Example

Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

Mrs. P.D.Titavekar 1
Object Oriented Programming using c++

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }

Output:

201
SonooJaiswal

Function
A function is a set of statements that take inputs, perform some specific computation, and produce
output. The idea to use functions is to perform some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and again for different inputs.
The general form of a function is in the below format:
return_type function_name([ arg1_type arg1_name, ... ])
{
// Perform Operations
}
1. There are two types of function:
1) Standard Library Functions: Predefined in C++
2) User-defined Function: Created by users

C++ User-defined Function

C++ allows the programmer to define their own function.

Mrs. P.D.Titavekar 2
Object Oriented Programming using c++

A user-defined function groups code to perform a specific task and that group of code is given a name

(identifier).

When the function is invoked from any part of the program, it all executes the codes defined in the

body of the function.

2. C++ Function Declaration


A function declaration tells the compiler about a function's name, return type, and parameters.

The syntax to declare a function is:

returnType functionName(parameter1, parameter2,...); // fuction declaration

Here's an example of a function declaration.


Void greet();

3. Function definition:-

A function definition provides the actual body of the function.

syntax:-

return_type function_name( parameter list ) {


body of the function
}

Void greet();
{
cout<<"Hello World";
}

4. Calling a Function

In the above program, we have declared a function named greet(). To use the greet() function, we

need to call it.


Here's how we can call the above greet() function.
Int main(){

// calling a function

greet();

Mrs. P.D.Titavekar 3
Object Oriented Programming using c++

Function Arguments in C++

If a function take any arguments, it must declare variables that accept the values as a arguments.
These variables are called the formal parameters of the function. There are two ways to pass value
or data to function in C++ language which is given below;

 call by value

 call by reference

1. Call by value

In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only
but it not change the value of variable inside the caller function such as main().
Program Call by value in C++

#include<iostream.h>
#include<conio.h>

void swap(int a,int b)


{
int temp;
temp=a;
a=b;
b=temp;

Mrs. P.D.Titavekar 4
Object Oriented Programming using c++

void main()
{
int a=100, b=200;
clrscr();
swap(a, b);// passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}

2. Call by reference

In call by reference, original value is changed or modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, any value changed inside the function, is reflected inside as well as
outside the function.
Example Call by Reference in C++

#include<iostream.h>
#include<conio.h>

void swap(int*a,int*b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

void main()
{
int a=100, b=200;
clrscr();
swap(&a,&b);// passing value to function
cout<<"Value of a"<<a;

Mrs. P.D.Titavekar 5
Object Oriented Programming using c++

cout<<"Value of b"<<b;
getch();
}

3. C++ Programming Default Arguments (Parameters)


In C++ programming, we can provide default values for function parameters.
If a function with default arguments is called without passing arguments, then the default parameters
are used.
However, if arguments are passed while calling the function, the default arguments are ignored.

Working of default arguments

Example: Default Argument


#include <iostream>
using namespace std;

// defining the default arguments


void display(char = '*', int = 3);

Mrs. P.D.Titavekar 6
Object Oriented Programming using c++

int main() {
int count = 5;

cout<< "No argument passed: ";


// *, 3 will be parameters
display();

cout<< "First argument passed: ";


// #, 3 will be parameters
display('#');

cout<< "Both arguments passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}

void display(char c, int count) {


for(int i = 1; i <= count; ++i)
{
cout<< c;
}
cout<<endl;
}

Calling Function:-

While creating a C++ function, you give a definition of what the function has to do. To use a function,
you will have to call or invoke that function.

Mrs. P.D.Titavekar 7
Object Oriented Programming using c++
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when it’s return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example –

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result −

Max value is : 200

Inline Functions in C++


C++ provides inline functions to reduce the function call overhead. An inline function is a function
that is expanded in line when it is called. When the inline function is called whole code of the inline
function gets inserted or substituted at the point of the inline function call. This substitution is

Mrs. P.D.Titavekar 8
Object Oriented Programming using c++
performed by the C++ compiler at compile time. An inline function may increase efficiency if it is
small.

Syntax:
inline return-type function-name(parameters)
{
// function code
}

Inline function in c++


Remember, inlining is only a request to the compiler, not a command. The compiler can ignore the
request for inlining.
The compiler may not perform inlining in such circumstances as:

 If a function contains a loop. (for, while and do-while)


 If a function contains static variables.
 If a function is recursive.
 If a function return type is other than void, and the return statement doesn’t exist in a function
body.
 If a function contains a switch or goto statement.

Ex.-
#include <iostream>
using namespace std;
Mrs. P.D.Titavekar 9
Object Oriented Programming using c++
inline int cube(int s) { return s * s * s; }
int main()
{
cout <<"The cube of 3 is: "<< cube(3) <<"\n";
return 0;
}
Output
The cube of 3 is: 27

Scope rules of functions and variables in c++


Scope determines visibility of identifiers across function/procedure boundaries, code blocks and
source files. The scope rules of a language decide in which part(s) of the program a particular piece of
code or data item can be accessed.
There are five types of scopes in C++
1. Function
2. File
3. Block
4. Function Prototype
5. Class
Function Scope
Identifiers declared in the outermost block of a function have function scope. They can be accessed
only in the function that declares them. Labels, which are identifiers followed by a colon, have
function scope. Labels contained in a function can be used anywhere in that function, but are not
visible outside that function.eg.:- goto statement.

#include <iostream>

using namespace std;

void Test()

goto lable1;

cout<<"First lable"<<endl;

// break;

lable1:

Mrs. P.D.Titavekar 10
Object Oriented Programming using c++
cout<<"second lable"<<endl;

// break;

int main() {

using namespace std;

Test();

// goto lable1; //This will create an error because lable1 is in Test() scope

return 0;

File Scope
Identifiers declared outside all blocks and functions have file scope. It can be used in all the blocks
and functions written inside the file in which the variable declaration appears. These identifiers are
known from their point of declaration until the end of file.
Identifiers with file scope are:
1. Global variables
2. Function definitions
3. Function prototypes placed outside all functions.
Block scope
Blocks are portions of C++ code contained within curly braces( {....} ). Identifiers declared within a
block have block scope and are visible from their points of definition to the end of the innermost
containing block. A duplicate identifier name in a block hides the value of an identifier with the same
name defined outside the block.
A variable name declared in a block is local to that block. It can be used only in it and the other blocks
contained under it.
Function prototype scope
Variables appearing in the parameter lists of function prototypes have function - prototype scope.
These variables are only placeholders, no storage is allocated or reserved. they are not visible outside
the function prototype. Variable identifiers in function prototypes are optional; only types are
required.
Class scope
A class member is local to its class and has a class scope.
Scope of Variables
the scope of variables within a function or any other block of instructions is only the own function or
the own block of instructions and cannot be used outside of them.

Mrs. P.D.Titavekar 11
Object Oriented Programming using c++
The scope of local variables is limited to the same nesting level in which they are declared.
Nevertheless global variables can be declared that would be visible from any point of the code, inside
and outside any function.
Figure illustrating the scope of variables
#include<iostream.h>
int integer; // Global variable
char aCharacter; // Global variable
char string(20); // Global variable
unsigned int number; // Global variable
main()
{
unsigned short age; // locall variable
float anumber, bnumber; // local variable
cout<<"enter your Age"; // instruction
cin>>Age; // instructions
}

Member function:-
Definition:- A method is a function that belongs to a class.
There are two ways to define a procedure or function that belongs to a class:
 Inside Class Definition
 Outside Class Definition

1. Inside Class Definition


The member function is defined inside the class definition it can be defined directly. Similar to
accessing a data member in the class we can also access the public member functions through the
class object using the dot operator (.).
Syntax:
class class_name{
public:
return_type Method_name() // method inside class definition
{
// body of member function
}
};
// C++ program for Inside Class Definition
#include <iostream>
using namespace std;

Mrs. P.D.Titavekar 12
Object Oriented Programming using c++
class rectangle {
private:
int length;
int breadth;
public:
// Constructor
rectangle(int length, int breadth)
{
this->length = length; // this pointer
this->breadth = breadth;
}
// area() function inside class
int area() { return (length * breadth); }
// perimeter() function outside class
int perimeter() { return 2 * (length + breadth); }
};
int main()
{
// Creating object
rectangle r(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}

Output
perimeter: 10
area: 6

2. Outside Class Definition

Mrs. P.D.Titavekar 13
Object Oriented Programming using c++
The member function is defined outside the class definition it can be defined using the scope
resolution operator. Similar to accessing a data member in the class we can also access the public
member functions through the class object using the dot operator (.).
Syntax:
class Class_name{
public:
return_type Method_name(); // method outside class definition
};

// Outside the Class using scope resolution operator


return_type Class_name :: Method_name()
{
// body of member function
}
Example: In the following code, a rectangle class, in which member function area() and member
function perimeter() is defined outside the class by using the scope resolution operator.
// C++ program for Outside the Class Definition
#include <iostream>
using namespace std;
class rectangle {
private:
int length;
int breadth;
public:
// Constructor
rectangle(int length, int breadth)
{
this->length = length; // this pointer
this->breadth = breadth;
}

// area() function defined outside the class


int area();

// perimeter() function defined outside the class


int perimeter();
Mrs. P.D.Titavekar 14
Object Oriented Programming using c++
};

// function defining using scope resolution operator "::"


int rectangle::area() { return (length * breadth); }
int rectangle::perimeter()
{
return 2 * (length + breadth);
}
int main()
{
// Creating object
rectangle r(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}

Accessing members from Objects:-


Accessing a data member depends solely on the access control of that data member. This access
control is given by Access modifiers in C++.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class
members, i.e., they set some restrictions on the class members so that they can’t be directly accessed
by the outside functions.
Access modifiers are used to implement an important aspect of Object-Oriented Programming known
as Data Hiding.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected

The public data members are accessed directly by the object however the private data members are
not allowed to be accessed directly by the object.
Consider a real-life example:
The Research and Analysis Wing (R&AW), having 10 core members, has come into possession of
sensitive confidential information regarding national security. Now we can correlate these core
members to data members or member functions of a class, which in turn can be correlated to the R&A
Wing. These 10 members can directly access the confidential information from their wing (the class),
but anyone apart from these 10 members can’t access this information directly, i.e., outside functions
other than those prevalent in the class itself can’t access the information (that is not entitled to them)
without having either assigned privileges (such as those possessed by a friend class or an inherited

Mrs. P.D.Titavekar 15
Object Oriented Programming using c++
class, as will be seen in this article ahead) or access to one of these 10 members who is allowed direct
access to the confidential information (similar to how private members of a class can be accessed in
the outside world through public member functions of the class that have direct access to private
members). This is what data hiding is in practice.

1.Public: All the class members declared under the public specifier will be available to everyone. The
data members and member functions declared as public can be accessed by other classes and
functions too. The public members of a class can be accessed from anywhere in the program using the
direct member access operator (.) with the object of that class.
// C++ program to demonstrate public
// access modifier
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;

// accessing public datamember outside class


obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}

Output:
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius is declared as public so it could be accessed outside the
class and thus was allowed access from inside main().

2. Private: The class members declared as private can be accessed only by the member functions
inside the class. They are not allowed to be accessed directly by any object or function outside the
class. Only the member functions or the friend functions are allowed to access the private data
members of the class.
Example:
// C++ program to demonstrate private
// access modifier

#include<iostream>
Mrs. P.D.Titavekar 16
Object Oriented Programming using c++
using namespace std;

class Circle
{
// private data member
private:
double radius;

// public member function


public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}

};

// main function
int main()
{
// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();


return 0;
}

Output:
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^
The output of the above program is a compile time error because we are not allowed to access the
private data members of a class directly from outside the class. Yet an access to obj.radius is
attempted, but radius being a private data member, we obtained the above compilation error.
However, we can access the private data members of a class indirectly using the public member
functions of the class.
// C++ program to demonstrate private
// access modifier

#include<iostream>
using namespace std;

Mrs. P.D.Titavekar 17
Object Oriented Programming using c++
class Circle
{
// private data member
private:
double radius;

// public member function


public:
void compute_area(double r)
{ // member function can access private
// data member radius
radius = r;

double area = 3.14*radius*radius;

cout << "Radius is: " << radius << endl;


cout << "Area is: " << area;
}

};

// main function
int main()
{
// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.compute_area(1.5);
return 0;
}

Output:
Radius is: 1.5
Area is: 7.065

3.Protected: The protected access modifier is similar to the private access modifier in the sense that it
can’t be accessed outside of its class unless with the help of a friend class. The difference is that the
class members declared as Protected can be accessed by any subclass (derived class) of that class as
well.
// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;

// base class
class Parent
{
// protected data members
protected:
Mrs. P.D.Titavekar 18
Object Oriented Programming using c++
int id_protected;

};

// sub class or derived class from public base class


class Child : public Parent
{
public:
void setId(int id)
{

// Child class is able to access the inherited


// protected data members of base class

id_protected = id;

void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};

// main function
int main() {

Child obj1;

// member function of the derived class can


// access the protected data members of the base class

obj1.setId(81);
obj1.displayId();
return 0;
}

Output:
id_protected is: 81

Constructor and Destructor:-


Introduction
While programming, sometimes there might be the need to initialize data members and member
functions of the objects before performing any operations. Data members are the variables declared in
any class by using fundamental data types (like int, char, float, etc.) or derived data types (like class,
structure, pointer, etc.). The functions defined inside the class definition are known as member
functions.
Suppose you are developing a game. In that game, each time a new player registers, we need to assign
their initial location, health, acceleration, and certain other quantities to some default value.

Mrs. P.D.Titavekar 19
Object Oriented Programming using c++
This can be done by defining separate functions for each quantity and assigning the quantities to the
required default values. For this, we need to call a list of functions every time a new player registers.
Now, this process can become lengthy and complicated.
What if we can assign the quantities along with the declaration of the new player automatically? A
constructor can help do this in a better and simpler way.
Moreover, when the player deletes his account, we need to deallocate the memory assigned to him.
This can be done using a destructor.

Constructor in C++
A Constructor is a special member function of a class and shares the same name as of class, which
means the constructor and class have the same name. Constructor is called by the compiler whenever
the object of the class is created, it allocates the memory to the object and initializes class data
members by default values or values passed by the user while creating an object. Constructors don’t
have any return type because their work is to just create and initialize an object.
Syntax of Constructor:
class scaler {
public:
// Constructor
scaler() {
// Constructor body.
}
};

Characteristics of Constructors in C++


A constructor can be made public, private, or protected per our program's design. Constructors are
mostly made public, as public methods are accessible from everywhere, thus allowing us to create the
object of the class anywhere in the code. When a constructor is made private, other classes cannot
create instances of the class. This is used when there is no need for object creation. Such a case arises
when the class only contains static member functions(i.e., the functions that are independent of any
class object and can be accessed using a class name with scope resolution operator, i.e. ::).
A constructor in C++ cannot be inherited. However, a derived class can call the base class
constructor. A derived class(i.e., child class) contains all members and member functions(including
constructors) of the base class.
Constructor functions are not inherited, and their addresses cannot be referenced.
The constructor in C++ cannot be virtual. A virtual table(also called vtable) is made for each class
having one or more virtual functions. Virtual functions ensure that the correct function is called for an
object regardless of the type of reference used for the function call. Whenever an object is created of
such a class, it contains a ‘virtual-pointer’ that points to the base of the corresponding vtable.
Whenever there is a virtual function call, the vtable refers to the function address.
But when a class constructor is executed, there is no virtual table created yet in the memory, meaning
no virtual pointer is defined yet. As a result, a constructor cannot be declared virtual.

Types of Constructors in C++


There are four types of constructors in C++:
1. Default Constructors
2. Parameterized Constructors
3. Copy Constructors
4. Dynamic Constructors

1. Default Constructor:

Mrs. P.D.Titavekar 20
Object Oriented Programming using c++
A constructor which does not receive any parameters is called a Default Constructor or a Zero
Argument Constructor. Every class object is initialized with the same set of values in the default
constructor.
Even if a constructor is not defined explicitly, the compiler will provide a default constructor
implicitly.
Syntax:
#include <bits/stdc++.h>
using namespace std;

class Employee {
public:
int age;

// Default constructor.
Employee() {
/* Data member is defined with the help of the
default constructor.*/
age = 50;
}
};

int main() {
// Object of class Employee declared.
Employee e1;
// Prints value assigned by default constructor.
cout << e1.age;
return 0;
}
o/p:
50

2. Parameterized Constructor
A Parameterized Constructor is a constructor that can accept one or more arguments. This helps
programmers assign varied initial values to an object at the creation time.
#include <iostream>

using namespace std;

class Employee {
public:
int age;
// Parameterized constructor
Employee(int x) {
/* Age assigned to value passed as an argument
while object declaration.*/
age = x;
}
};

int main() {
/* Object c1 declared with argument 40, which
Mrs. P.D.Titavekar 21
Object Oriented Programming using c++
gets assigned to age.*/
Employee c1(40);
Employee c2(30);
Employee c3(50);
cout << c1.age << "\n";
cout << c2.age << "\n";
cout << c3.age << "\n";
return 0;
}
o/p:-
40
30
50

3. Copy Constructor
A Copy constructor in C++ is a type of constructor used to create a copy of an already existing object
of a class type. The compiler provides a default Copy Constructor to all the classes. A copy
constructor comes into the picture whenever there is a need for an object with the same values for data
members as an already existing object. A copy constructor is invoked when an existing object is
passed as a parameter.
#include<iostream>
using namespace std;

class Employee {
private:
// Data members
int salary, experience;

public:
// Parameterized constructor
Employee(int x1, int y1) {
salary = x1;
experience = y1;
}

// Copy constructor
Employee(const Employee &new_employee) {
salary = new_employee.salary;
experience = new_employee.experience;
}

void display() {
cout << "Salary: " << salary << endl;
cout << "Years of experience: " << experience << endl;
}
};

// main function
int main() {
// Parameterized constructor
Employee employee1(34000, 2);
Mrs. P.D.Titavekar 22
Object Oriented Programming using c++
// Copy constructor
Employee employee2 = employee1;
cout << "Employee1 using parameterized constructor : \n";
employee1.display();
cout << "Employee2 using copy constructor : \n";
employee2.display();
return 0;
}
o/p:-
Employee1 using the parameterized constructor :
Salary: 34000
Years of experience: 2
Employee2 using copy constructor :
Salary: 34000
Years of experience: 2

4. Dynamic Constructor
When the allocation of memory is done dynamically (i.e., Memory is allocated to variables at run-
time of the program rather than at compile-time) using a dynamic memory allocator new in a
constructor, it is known as a Dynamic constructor. By using this, we can dynamically initialize the
objects.
#include <iostream>
using namespace std;

class Employee {
int* due_projects;

public:
// Default constructor.
Employee() {
// Allocating memory at run time.
due_projects = new int;
*due_projects = 0;
}

// Parameterized constructor.
Employee(int x) {
due_projects = new int;
*due_projects = x;
}

void display() {
cout << *due_projects << endl;
}
};

// Main function
int main() {
// Default constructor would be called.
Employee employee1 = Employee();
cout << "Due projects for employee1:\n";
Mrs. P.D.Titavekar 23
Object Oriented Programming using c++
employee1.display();

// Parameterized constructor would be called.


Employee employee2 = Employee(10);
cout << "Due projects for employee2:\n";
employee2.display();
return 0;
}

o/p:-
Due projects for employee1:
0
Due projects for employee2:
10

Destructor in C++
A Destructor is a member function that is instantaneously called whenever an object is destroyed. The
destructor is called automatically by the compiler when the object goes out of scope, i.e., when a
function ends, the local objects created within it are also destroyed. The destructor has the same name
as the class name, but the name is preceded by a tilde(~). A destructor has no return type and receives
no parameters.
Syntax of Destructor:
class scaler {
public:
//constructor
scaler();
//destructor
~scaler();
};

Characteristics of a Destructor in C++


A destructor deallocates memory occupied by the object when it’s deleted.
A destructor cannot be overloaded. In function overloading, functions are declared with the same
name in the same scope, except that each function has a different number of arguments and different
definitions. But in a class, there is always a single destructor that does not accept any parameters.
Hence, a destructor cannot be overloaded.
A destructor is always called in the reverse order of the constructor. In C++, variables and objects are
allocated on the Stack. The Stack follows the LIFO (Last-In-First-Out) pattern. So, the deallocation of
memory and destruction is always carried out in the reverse order of allocation and construction. This
can be seen in the code below.
A destructor can be written anywhere in the class definition. But to bring an amount order to the code,
a destructor is always defined at the end of the class definition.
#include <iostream>

using namespace std;


class Department {

public:
Department() {
// Constructor is defined.
cout << "Constructor Invoked for Department class" << endl;
Mrs. P.D.Titavekar 24
Object Oriented Programming using c++
}

~Department() {
// Destructor is defined.
cout << "Destructor Invoked for Department class" << endl;
}
};
class Employee {

public:
Employee() {
// Constructor is defined.
cout << "Constructor Invoked for Employee class" << endl;
}

~Employee() {
// Destructor is defined.
cout << "Destructor Invoked for Employee class" << endl;
}
};
int main(void) {
// Creating an object of Department.
Department d1;
// Creating an object of Employee.
Employee e2;
return 0;
}

o/p:-
Constructor Invoked for Department class
Constructor Invoked for Employee class
Destructor Invoked for Employee class
Destructor Invoked for Department class

Difference Between Constructors and Destructors


S.
Constructors Destructors
No.
Constructor is invoked to initialize the object of a Destructor is invoked when the instance is
1
class by the compiler. destroyed.
Declared as Class_Name(arguments if
2 Declared as ~Class_Name(){}.
any){//constructor body}.
3 Constructor can receive parameters. Destructor cannot accept any parameters.
Constructor is used to initialize an object of the
While destructor is used to deallocate the
4 class and assign values to data members
memory of an object of a class.
corresponding to the class.
There can be multiple constructors for the same
5 In a class, there is always a single destructor.
class.
6 Constructor can be overloaded. Destructor can’t be overloaded.

Mrs. P.D.Titavekar 25
Object Oriented Programming using c++

Static Class Members :-

Static Data Members:-


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;

Static members are only declared in a class declaration, not defined. They must be explicitly defined
outside the class using the scope resolution operator.

Let us try the following example to understand the concept of static data members −
#include <iostream>

using namespace std;

class Box {
public:
static int objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;

// Increase every time object is created


objectCount++;
}
double Volume() {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

Mrs. P.D.Titavekar 26
Object Oriented Programming using c++

// Print total number of objects.


cout << "Total objects: " << Box::objectCount << endl;

return 0;
}

Output:-
Constructor called.
Constructor called.
Total objects: 2

// C++ Program to demonstrate


// Static member in a class
#include <iostream>
using namespace std;

class Student {
public:
// static member
static int total;

// Constructor called
Student() { total += 1; }
};

int Student::total = 0;

int main()
{
// Student 1 declared
Student s1;
cout << "Number of students:" << s1.total << endl;

// Student 2 declared
Student s2;
cout << "Number of students:" << s2.total << endl;

// Student 3 declared
Student s3;
cout << "Number of students:" << s3.total << endl;
return 0;
}

Output
Number of students:1
Number of students:2
Number of students:3

Mrs. P.D.Titavekar 27
Object Oriented Programming using c++

Static Member Function in C++ :-

Static Member Function in a class is the function that is declared as static because of which function attains
certain properties as defined below:
 A static member function is independent of any object of the class.
 A static member function can be called even if no objects of the class exist.
 A static member function can also be accessed using the class name through the scope resolution operator.
 A static member function can access static data members and static member functions inside or outside of
the class.
 Static member functions have a scope inside the class and cannot access the current object pointer.
 You can also use a static member function to determine how many objects of the class have been created.

The reason we need Static member function:


 Static members are frequently used to store information that is shared by all objects in a class.
 For instance, you may keep track of the quantity of newly generated objects of a specific class type using
a static data member as a counter. This static data member can be increased each time an object is
generated to keep track of the overall number of objects.

// C++ Program to show the working of


// static member functions
#include <iostream>
using namespace std;

class Box
{
private:
static int length;
static int breadth;
static int height;

public:

static void print()


{
cout << "The value of the length is: " << length << endl;
cout << "The value of the breadth is: " << breadth << endl;
cout << "The value of the height is: " << height << endl;
}
};

// initialize the static data members

int Box :: length = 10;


int Box :: breadth = 20;
int Box :: height = 30;

// Driver Code

int main()
{

Box b;

Mrs. P.D.Titavekar 28
Object Oriented Programming using c++

cout << "Static member function is called through Object name: \n" << endl;
b.print();

cout << "\nStatic member function is called through Class name: \n" << endl;
Box::print();

return 0;
}

Output
Static member function is called through Object name:

The value of the length is: 10


The value of the breadth is: 20
The value of the height is: 30

Static member function is called through Class name:

The value of the length is: 10


The value of the breadth is: 20
The value of the height is: 30

friend function and friend classes :-


A friend class can access private and protected members of other classes in which it is declared as a friend. It
is sometimes useful to allow a particular class to access private and protected members of other classes. For
example, a LinkedList class may be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.

Syntax:
friend class class_name; // declared in the base class

Mrs. P.D.Titavekar 29
Object Oriented Programming using c++

// C++ Program to demonstrate the


// functioning of a friend class
#include <iostream>
using namespace std;

class GFG {
private:
int private_variable;

protected:
int protected_variable;

public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}

// friend class declaration


friend class F;
};

// Here, class F is declared as a


// friend inside class GFG. Therefore,
// F is a friend of class GFG. Class F
// can access the private members of
// class GFG.
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};

// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}

Output
The value of Private Variable = 10
Mrs. P.D.Titavekar 30
Object Oriented Programming using c++

The value of Protected Variable = 99

Friend Function
Like a friend class, a friend function can be granted special access to private and protected members of a
class in C++. They are the non-member functions that can access and manipulate the private and protected
members of the class for they are declared as friends.
A friend function can be:
1. A global function
2. A member function of another class

Syntax:
friend return_type function_name (arguments); // for a global function
or
friend return_type class_name::function_name (arguments); // for a member function of
another class

1. Global Function as Friend Function


We can declare any global function as a friend function.
// C++ program to create a global function as a friend
// function of some class
#include <iostream>
using namespace std;

class base {
private:
int private_variable;

protected:
int protected_variable;

public:
base()
{
private_variable = 10;
protected_variable = 99;
}

// friend function declaration


friend void friendFunction(base& obj);
};
Mrs. P.D.Titavekar 31
Object Oriented Programming using c++

// friend function definition


void friendFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
base object1;
friendFunction(object1);

return 0;
}

Output
Private Variable: 10
Protected Variable: 99

2. Member Function of Another Class as Friend Function


We can also declare a member function of another class as a friend function in C++.
// C++ program to create a member function of another class
// as a friend function
#include <iostream>
using namespace std;

class base; // forward definition needed


// another class in which function is declared
class anotherClass {
public:
void memberFunction(base& obj);
};

// base class for which friend is declared


class base {
private:
int private_variable;

protected:
int protected_variable;

public:
base()
{
private_variable = 10;

Mrs. P.D.Titavekar 32
Object Oriented Programming using c++
protected_variable = 99;
}

// friend function declaration


friend void anotherClass::memberFunction(base&);
};

// friend function definition


void anotherClass::memberFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);

return 0;
}

Output
Private Variable: 10
Protected Variable: 99

Features of Friend Functions


 A friend function is a special function in C++ that in spite of not being a member function of a class has
the privilege to access the private and protected data of a class.
 A friend function is a non-member function or ordinary function of a class, which is declared as a friend
using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions
are given to the function.
 The keyword “friend” is placed only in the function declaration of the friend function and not in
the function definition or call.
 A friend function is called like an ordinary function. It cannot be called using the object name and dot
operator. However, it may accept the object as an argument whose value it wants to access.
 A friend function can be declared in any section of the class i.e. public or private or protected.

Advantages of Friend Functions


 A friend function is able to access members without the need of inheriting the class.
 The friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operators.
 It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
 Friend functions have access to private members of a class from outside the class which violates
the law of data hiding.
 Friend functions cannot do any run-time polymorphism in their members.

Mrs. P.D.Titavekar 33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy