Object Oriented Programming
Object Oriented Programming
W3 - L3
Agenda
Assessment
C++ Data types
Constructor
Default Constructor
Parameterized Constructor
Copy constructor
Constructor overloading
Private constructor
Static Constructor
Destructor
Examples
Example for Revision
Step#1
#include <iostream>
#include <string>
using namespace std;
int a = 5 ;
ABC a = 10 ;
// ABC is class_name
// a is object
Constructor is a special member function which is used to initialize the
value of variable inside an object.
Major points:
int main()
{
MyClass myObj;
}
Output: (cont.)
Hello World!
Example 2:
write a class that contains two integer data members which are
initialized to 100 when an object is created. It has a member
function avg that displays the average of data members.
Solution:
5
15/06/202
#include<iostream.h> cout<<“x=“<<x<<endl;
#include<conio.h> cout<<“y=“<<y<<endl;
class Number cout<<“Average=“<<(x+y)/
2<<endl;
{
}
private:
};
int x,y;
void main()
public:
{
Number(){
Number n;
x=y=100;
n.avg();
}
getch();
void avg(){
}
Find Errors:
5
15/06/202
Class A
Void main()
{ {
Private:
int a ; A obj;
A()
Obj.show();
{
a=5;
} }
void show()
{
cout<<a;
}
};
Solution:
5
15/06/202
Class A Void main()
{
Private:
{
int a ;
Public:
A obj;
A()
{ obj.show();
a=5;
} Output: ?
void show()
}
{
cout<<a;
}
};
CONSTRUCTORS EXAMPLE
#include <iostream>
5
15/06/202
using namespace std;
class Counter
{
private:
int count;
public:
Counter() : count(0) //constructor
{
/*empty body*/ }
void inc_count() //increment count
{ count++; }
int get_count() //return count
{ return count; } };
int main()
{
5
15/06/202
Counter c1, c2; //define and initialize
cout << "\nc1=" << c1.get_count(); //display
cout << "\nc2=" << c2.get_count();
c1.inc_count(); //increment c1
c2.inc_count(); //increment c2
c2.inc_count(); //increment c2
cout << "\nc1=" << c1.get_count(); //display again
cout << "\nc2=" << c2.get_count();
cout << endl;
return 0;
}
Output:
5
15/06/202
c1=0
c2=0
c1=1
c2=2
1.Default Constructor:
5
15/06/202
A constructor that accepts no parameters is called default
constructor.
Syntax:
Class_name()
{
// code
}
Example:
Default Constructor
5
15/06/202
Class A Void main() Output:
{ {
Private: A obj; 10
int a ;
}
Public:
A()
{
a= 10 ;
cout<<a;
}
}
Task # 1
5
15/06/202
Write a program that initialize two integer variables x and y,
assign both variables with value 100 by creating constructor
member function inside the class , create another member
function that calculate average of these two numbers and display
it.
Solution:
5
15/06/202
Void main ()
Class Number
{ {
Int x , y ;
Public: Number n ;
Number() n.avg() ;
{
x = y = 100}
Void avg()
}
{
Cout<<“x is =” << x;
Cout<< “y is =” << y;
Cout << “average is
=”x+y/2 ; }};
Task # 2
5
15/06/202
Write a program that initialize two integer variables x and y,
assign both variables with value 100 by creating constructor
member function outside the class , create another member
function that calculate average of these two numbers and display
it.
Solution:
5
15/06/202
Class Number Number :: Number()
{ {
Int x , y ; x = y = 100}
Public:
Number(); Void main ()
{
void avg()
{ Number n ;
Cout<<“x is =” << x;
n.avg() ;
Cout<< “y is =” << y;
Cout << “average is
=”x+y/2 ; }}; }
2. Parameterized Constructor
5
15/06/202
A constructor that accepts or receive parameters is called
parameterized constructor.
Syntax:
class_name(parameter1, parameter2 ---parameter n)
{
// code
}
Example:
Parameterized constructor:
5
15/06/202
Class A Void show() Void main()
{ { {
Private: Cout<<a<<“”<< A obj(10,20);
int a, b ; b; Obj.show();
Public: } }
A(int x , int y)
{
}; Output:
a= x; 10 20
b =y;
}
Task#3
5
15/06/202
Write a program to create a parameterized constructor Wall() that has 2 parameters: double
len and double hgt.
The values contained in these parameters are used to initialize the member
variables length and height.
When we create an object of the Wall class, we pass the values for the member variables as
arguments.
5
15/06/202
using namespace std; Wall(double len, double hgt) {
// declare a class { return length * height;
class Wall length = len; }
{ height = hgt; };
private: } int main()
double length; {
double height; Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " <<
wall1.calculateArea() << endl;
cout << "Area of Wall 2: " <<
wall2.calculateArea(); return 0;}
Output:
5
15/06/202
Area of Wall 1: 90.3
Area of Wall 2: 53.55
Task#4:
5
15/06/202
Write a class TV that contains the attributes Brand
Name, Model and Retail Price.
Write a method to display all attributes and a
method to change the attributes. Also write a
constructor to initialize all the attributes by using
parameterized constructor.
5
15/06/202
Displaying objects before change…
Brand name: Samsung
Model: HDTV
Price: 45000
Displaying objects after change…
Brand name: Apple
Model: HDTV
Price: 55000
Step # 1
5
15/06/202
Class TV
{
Private:
Char brandname[];
Char Model[];
Float retail_Price;
Public:
TV(char brand[] , char model1[] , float price);
Void change(char brand[] , char model1[] , float price);
Void display();
};
Step#2
5
15/06/202
TV :: TV (char brand[] , char model1[] , float price)
{
Strcpy(Brandname , brand);
Strcopy(Model , model1);
Retail_price = price;
}
Step#3
5
15/06/202
void TV :: change (char brand[] , char model1[] , float price)
{
Strcopy(Brandname , brand);
Strcopy(Model , model1);
Retail_price = price;
}
Step#4
5
15/06/202
void TV :: display ()
{
Cout << “” Brand name is: << Brandname <<endl;
Cout << “” Model is: ” << model1 << endl;
Cout << “” retail price is : “ << retail_price ;
}
Step# 5 :
5
15/06/202
void main ()
Test. Change(“Apple” ,
{ “HDTV” , “35000”) ;
TV test(“samsung” , “HDTV” , 25000) ;
}
}
3.Copy Constructor
5
15/06/202
A constructor that is used to copy or initialize the value of one
object into another object of same type is called copy
constructor.
5
15/06/202
{ {
Int a ;
Cout << value of a is: “ << a;
Public:
} int main ()
//Default Constructor
{
Demo()
{ }; demo aa;
a = 10; demo bb(aa) ;
} demo cc = bb;
//copy Constructor
Demo( Demo &z)
aa.print();
{ Output:
a = z.a; bb.print(); 10
10
} cc.print();
10
Example: // CC initialize object into another object
Copy Constructor:
5
15/06/202
Class A A(A &ref) Void main()
{ { {
private:
a = ref.a ; A obj(10, 20);
int a , b ;
public:
B = ref.b; A obj2 = obj;
A(int x , int } obj.show();
y);
}
{
a=x; Void show()
b=y; {
}
Cout<<a <<b;
}
};
Output:
5
15/06/202
// result of parameterized constructor
10 20
Example: // CC initialize object into another object
Copy Constructor:
5
15/06/202
Class A A(A &ref) Void main()
{ { {
private:
a = ref.a ; A obj(10, 20);
int a , b ;
public:
B = ref.b; A obj2 = obj;
A(int x , int } obj.show();
y);
obj2.show()
{
a=x; Void show() }
b=y; {
}
Cout<<a <<b;
}
};
Output:
5
15/06/202
// result of parameterized & copy constructor
10 20
10 20
Task#5:
5
15/06/202
Write a
1. Class wall that contains the attributes length and
height .
2. Initialize variables with parameterized
constructor
3. Create copy constructor with a Wall object as
parameter
4.Create member function that calculate Area
5.Print area of wall1 and wall2.
// copy constructor with a Wall object as
Solution: parameter
// copies data of the obj parameter
#include <iostream>
5
15/06/202
using namespace std; Wall(Wall &obj)
// declare a class {
class Wall length = obj.length;
{ height = obj.height;
private: }
double length; double calculateArea()
double height; {
public: return length * height;
// initialize variables with parameterized }
constructor Wall(double len, double hgt) };
{ int main()
length = len; {
height = hgt; // create an object of Wall class
} Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea()
<< endl; cout << "Area of Wall 2: " <<
Output:
5
15/06/202
Area of Wall 1: 90.3
Area of Wall 2: 90.3
Constructor Overloading:
5
15/06/202
Constructors can be overloaded in a similar way as function
overloading.
5
15/06/202
constructor overloading
}
#include <iostream>
int getAge()
using namespace std;
{
class Person
return age;
{
}
private:
};
int age;
public:
int main()
// 1. Constructor with no
{
arguments
Person person1, person2(45);
Person()
cout << "Person1 Age = " << person1.getAge()
{
<<endl;
age = 20;
cout << "Person2 Age = " << person2.getAge()
}
<< endl;
return 0;
}
Output:
5
15/06/202
Person1 Age = 20
Person2 Age = 45
Task # 6:
5
15/06/202
•Write a class room that contain two attributes length and breadth ,
5
15/06/202
#include public: // 3. Constructor with one
<iostream> // 1. Constructor with no argument Room(double len)
arguments Room() {
using namespace { length = len;
std; length = 6.9; breadth = 7.2;
class Room breadth = 4.2; }
} double calculateArea()
{ {
// 2. Constructor with two return length * breadth;
private:
arguments Room(double l, }
double length; double b) };
{
double breadth; length = l;
breadth = b;
}
Solution Task 6 cont..
5
15/06/202
int main()
{
Room room1, room2(8.2, 6.6), room3(8.2);
cout << "When no argument is passed: " << endl;
cout << "Area of room = " << room1.calculateArea() << endl;
cout << "\nWhen (8.2, 6.6) is passed." << endl;
cout << "Area of room = " << room2.calculateArea() << endl;
cout << "\nWhen breadth is fixed to 7.2 and (8.2) is passed:" << endl;
cout << "Area of room = " << room3.calculateArea() << endl;
return 0;
}
Constructor overloading
Examples:
5
15/06/202
numbers_sum(int n1, int n2) and
numbers_sum(double n1, double n2) is
legal in constructor overloading.
numbers_sum(int n1, int n2) and
numbers_sum(int n1, double n2) is legal in
constructor overloading.
numbers_sum(int n1, int n2) and
numbers_sum(double n1, int n2) is legal in
constructor overloading.
5
15/06/202
numbers_sum(int n1, int n2) and numbers_sum(int n1, int n2) is
illegal in constructor overloading.
numbers_sum(double n1, double n2) and numbers_sum(double
n1, double n2) is illegal in constructor overloading.
numbers_sum(int n1) and numbers_sum(int n1, int n2) is legal in
constructor overloading.
numbers_sum(int n1, int n2) and numbers_sum(int n1) is legal in
constructor overloading.
Initializer List:
5
15/06/202
Just another way to initialize data members in
constructors.(Using list)
Initializer List is used in initializing the data members
of a class.
The list of members to be initialized is indicated with
constructor as a comma-separated list followed by a
colon.
A constructor will "build" an instance when it is
call. And the initializer will be call on the load of the
class
Example 1:
Class Test
5
15/06/202
{
Int a , b;
Public:
}
Destructors:
A type of member function that is executed
5
15/06/202
automatically when an object of that class is
destroyed.
Memory is allocated for objects according to
the data members when objects are created .
Upon quitting a program memory allocation
for objects is cleared.
Last
function of program that executes
automatically.
No return type
Same name as class name
Difference between Constructor & Destructor
5
15/06/202
Example: Void main()
Class Test
{
5
15/06/202
{
Private: Test a , b ;
int n ;
Public: }
Test()
{
cout<<“Object Created” ;
Run this inTurbo C++
} Then alt f5 to see the object
~Test() destroyed
{
Cout<<“object Destroyed”}
}
};
15/06/202
5
15/06/202
5
Example program 1 – function call by value
Memory
main()
1 2
a b
0
6504
0
7505
change_value(
)
2
1 4
2
x y
0
3205
0
4350
Program
a = 10 b =
Output
Go to x = 20 y =
20
program a
40= 10 b =
Press
20 any key to
Call by Reference:
5
15/06/202
15/06/202
5
Example program 1 – function call by address
Memory
change_value(6504,
7505); main()
1
2 4
2
a b
0
6504
0
7505
change_value(
)
650
*x 4 *y 7505
3205 4350
Program
a = 10 b =
Output =*(650
Go to x = 20 y =
20 *x = 10
a 4)
program 40= 20 b =
40