Unit 2 - OOP
Unit 2 - OOP
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;
Accessing data members and member functions: The data members and member functions
of class can be accessed using the dot(‘.’) operator with the object. For example if the name of
object is obj and you want to access the member function with the name printName() then you
will have to write obj.printName() .
#include <iostream>
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Output
Area of Room = 1309
Volume of Room = 25132.8
Access specifier
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Output:
error: y is private
Member function
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member, and has access to all the members of a class for that
object.
Member functions can be defined within the class definition or separately
using scope resolution operator,: −. Defining a member function within the class
definition declares the function inline, even if you do not use the inline specifier. So
either you can define Volume() function as below −
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
class Node {
private:
int key;
Node* next;
};
#include<iostream>
class integer
{
Static int a, b;
public:
void set_value()
{
a=50;
b=30;
}
friend int mean(integer s); //declaration of friend
function
};
int mean(integer s)
{
return int(s.a+s.b)/2.0; //friend function definition
}
int main()
{
integer c;
c.set_value();
cout<< "Mean value:" <<mean(c);
return 0;
}
Syntax:
include <iostream>
class MyClass
{
int x;
public:
void setX(int i)
x = i;
}
int getX()
return x; }
};
void main()
{
MyClass obs[4];
int i;
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";
getch();
1. Call by value: In this method a copy of entire object is created to pass into another
function. When we make changes in the object inside calling function then only local copy of the
object will be affected, there is no change in called function. Both copies of the object will be
identical.
2. Call by reference: In this method no separate copy of the object is created, instead we
are passing address (&) of object to the function. When an object is modified inside the calling
function then the actual object is also affected in the called function. Call by reference method
can be used by passing argument via reference variable or pointer.
Constructors in C++
What is 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) create. It is special member function of the class
because it does not have any return type.
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Types of Constructors
1. Default Constructors: Default constructor is the constructor which
doesn’t take any argument. It has no parameters.
CPP
// concept of Constructors
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
construct() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20
Output:
p1.x = 10, p1.y = 15
When an object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function. The normal way
of object declaration may not work. The constructors can be called explicitly
or implicitly.
Example e = Example(0, 50); // Explicit call
CPP
// Illustration
#include "iostream"
using namespace std;
class point
{
private:
double x, y;
public:
// Non-default Constructor &
// default Constructor
point (double px, double py)
{
x = px, y = py;
}
};
int main(void)
{
// Define an array of size
// 10 & of type point
// This line will cause error
point a[10];
// Remove above line and program
// will compile without error
point b = point(5, 6);
}
Output:
Error: point (double px, double py): expects 2 arguments, 0
provided
\\copy contructor ex 2
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{ Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
Multiple constructor: Multiple constructors is a category of constructor in which a
class can have more than one constructor. This is also known as constructor overloading. All
constructors are defined with the same name as the class name they belong to. Each of the
constructors contains different number of arguments. Depending upon the number of arguments
and their data type, the compiler executes appropriate constructor.
Example:-
#include<iostream.h>
#include<conio.h>
class integer
int m, n;
public:
integer()
{
m = 0;
n = 0;
}// constructor 1
integer(int a, int b)
{
m = a;
n = b;
cout<<"value of m="<<a;
cout<<"value of n="<<b;
} // constructor 2
};
void main()
{
clrscr();
integer i1;
integer i2(20,40);
getch();
In the above example, two constructors are defined and invoked; this is referred as multiple
constructors.
The first constructor does not accept any argument and the second accepts two integer arguments.
In void main( ):
integer i1; - This statement invokes first constructor.
integer i2 (20, 40); -This statement invokes second constructor.
Whereas, Destructor on the other hand is used to destroy the class object.
Before moving forward with Constructors and Destructors in C++ language, check these
topics out to understand the concept better:
Function in C++
Class and Objects in C++
Data Members
Let's start with Constructors first, following is the syntax of defining a constructor function in
a class:
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
Copy
While defining a contructor you must remeber that the name of constructor will be same as
the name of the class, and contructors will never have a return type.
Constructors can be defined either inside the class definition or outside class definition using
class name and scope resolution :: operator.
class A
{
public:
int i;
A(); // constructor declared
};
// constructor definition
A::A()
{
i = 1;
}
Copy
Types of Constructors in C++
Constructors are of three types:
1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor
Default Constructors
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax:
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Copy
For example:
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Copy
10
In this case, as soon as the object is created the constructor is called which initializes its data
members.
A default constructor is so important for initialization of object members, that even if we do
not define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
public:
int side;
};
int main()
{
Cube c;
cout << c.side;
}
Copy
0 or any random value
In this case, default constructor provided by the compiler will be called which will initialize
the object data members to default value, that will be 0 or any random integer value in this
case.
Parameterized Constructors
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
For example:
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
Copy
10
20
30
By using parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.
Copy Constructors
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object. We will study copy constructors in
detail later.
int main()
{
// student A initialized with roll no 10 and name None
Student A(10);
Destructors in C++
Destructor is a special class function which destroys the object as soon as the scope of object
ends. The destructor is called automatically by the compiler when the object goes out of
scope.
The syntax for destructor is same as that for the constructor, the class name is used for the
name of destructor, with a tilde ~ sign as prefix to it.
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};
Copy
Destructors will never have any arguments.
Example to see how Constructor and Destructor are called
Below we have a simple class A with a constructor and destructor. We will create object of
the class and see when a constructor is called and when a destructor gets called.
class A
{
// constructor
A()
{
cout << "Constructor called";
}
// destructor
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Copy
Constructor called
Constructor called
Destructor called
Destructor called
When an object is created the constructor of that class is called. The object reference is
destroyed when its scope ends, which is generally after the closing curly bracket } for the
code block in which it is created.
The object obj2 is destroyed when the if block ends because it was created inside the if block.
And the object obj1 is destroyed when the main() function ends.
Example:-
#include<iostream.h>
#include<conio.h>
class integer
int m, n;
public:
integer()
m = 0;
n = 0;
}// constructor 1
integer(int a, int b)
{
m = a;
n = b;
cout<<"value of m="<<a;
cout<<"value of n="<<b;
} // constructor 2
};
void main()
clrscr();
integer i1;
integer i2(20,40);
getch();
In the above example, two constructors are defined and invoked; this is referred as
multiple constructors.
The first constructor does not accept any argument and the second accepts two
integer arguments.
In void main( ):