unit 2- Objects Classes & Constructor (1)
unit 2- Objects Classes & Constructor (1)
unit 2- Objects Classes & Constructor (1)
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.
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
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
3. Function definition:-
syntax:-
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
// calling a function
greet();
Mrs. P.D.Titavekar 3
Object Oriented Programming using 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>
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();
}
Mrs. P.D.Titavekar 6
Object Oriented Programming using c++
int main() {
int count = 5;
return 0;
}
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;
return 0;
}
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 −
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
}
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
#include <iostream>
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() {
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
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
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
};
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;
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;
};
// main function
int main()
{
// creating object of the class
Circle obj;
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;
};
// main function
int main()
{
// creating object of the class
Circle obj;
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;
};
id_protected = id;
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
// main function
int main() {
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}
Output:
id_protected is: 81
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.
}
};
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>
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();
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();
};
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
Mrs. P.D.Titavekar 25
Object Oriented Programming using c++
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>
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;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
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++
return 0;
}
Output:-
Constructor called.
Constructor called.
Total objects: 2
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 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.
class Box
{
private:
static int length;
static int breadth;
static int height;
public:
// 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:
Syntax:
friend class class_name; // declared in the base class
Mrs. P.D.Titavekar 29
Object Oriented Programming using c++
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// 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++
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
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
// driver code
int main()
{
base object1;
friendFunction(object1);
return 0;
}
Output
Private Variable: 10
Protected Variable: 99
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
Mrs. P.D.Titavekar 32
Object Oriented Programming using c++
protected_variable = 99;
}
// driver code
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
return 0;
}
Output
Private Variable: 10
Protected Variable: 99
Mrs. P.D.Titavekar 33