0% found this document useful (0 votes)
7 views67 pages

Object Oriented Programming

The document provides an overview of Object Oriented Programming in C++, focusing on constructors, destructors, and data types. It explains various types of constructors such as default, parameterized, and copy constructors, along with examples of their implementation. Additionally, it covers the initialization of class attributes and includes tasks for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views67 pages

Object Oriented Programming

The document provides an overview of Object Oriented Programming in C++, focusing on constructors, destructors, and data types. It explains various types of constructors such as default, parameterized, and copy constructors, along with examples of their implementation. Additionally, it covers the initialization of class attributes and includes tasks for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

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;

class MyClass { // class


public: // Access specifier
int age; // Attribute (int variable)
string name; // Attribute (string variable)
};
Step#2
int main()
{
// Create an object of MyClass
MyClass myObj;
// Access attributes and set values
myObj.age = 15;
myObj.name = “Zahid";
// Print values
cout << myObj.age << "\n";
cout << myObj.name;
return 0;
}
WHAT IS CONSTRUCTOR?

 A constructor is a member function that is executed


automatically whenever an object is created.
 If you do not specify a constructor, the compiler generates a
default constructor for you (expects no parameters and has an
empty body).
 You must supply the arguments to the constructor when a new
instance is created.
 It is normally defined in classes to initialize data members.
 Built in data types:

int a = 5 ;

 User defined-data types:


Like in class & object

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.

 We can’t initialize value using class name and object.


ABC a = 10 ;

 Instead , To initialize the values of a object we have to create a method


like input() or we have to use object to initialize data members.
a.input()
a. age = 10 ;
a.name = “ali”;
We want to initialize the values to data members like normal variables
without creating and calling functions .

Major points:

1. Constructors name is same as the class name.


2. A constructor is automatically invoked.
3. A constructor can have only one access modifier that is public.
4. A constructor is never inherited nor overridden.
5. It does not have any return value.
6. Each and every C++ class has a constructor either it is provided by
compiler by default or explicitly created by user.
Why we use Constructor?

Constructor is a special member function of


class which is used to initialize an object.
The constructor can work as a normal function
but it cannot return any value.
Where?

 Initialization of a class’s data members is done in the class’s


constructor.
 The constructor of a class is a special method of the class that
runs when a variable of that class is instantiated
count()
{
count = 0;
}
This is not the preferred approach (although it does work).

Here’s how you should initialize a data member:


count() : count(0)
{}
The initialization takes place following the member function
declarator but before the function body. It’s preceded by a colon.
Example 1:
#include <iostream>
using namespace std;
class MyClass
{
public:
// Constructor
MyClass()
{
cout << "Hello World!";
}
};
Example 1: (cont.)

int main()
{

// Create an object of MyClass (this will call the constructor)

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.

// create atleast 2 objects


Solution
#include <iostream> public: double calculateArea()

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.

Create constructor and methods outside the


class
Output:

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) ;

Cout<< ” Displaying values


Cout<< “Displaying objects before
after change”
change…”

Test. Display(); Test. Display();

}
}
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.

 // pass object as an argument


 Syntax:
Class_name(class_name &ref)
{
//code
}
Calling of copy constructor:
Class-name target-object(source-object);
Class-name target-object=source-object;
Example: //Member Function
Class Demo Void print()

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.

 Overloaded constructors have the same name (name of the


class) but
1. They must have different number of arguments. Or
2. If parameters are same, type of parameters must be different. Or
3. If arguments and type is same then order of parameters must be
different .
Example: // 2. Constructor with an argument
Person(int a)
{
// C++ program to demonstrate
age = a;

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 ,

•When room1 is created, the first constructor is called. length is initialized


to 6.9 and breadth is initialized to 4.2.
•When room2 is created, the second constructor is called. We have passed the
arguments 8.2 and 6.6. length is initialized to the first argument 8.2 and breadth is
initialized to 6.6.
•When room3 is created, the third constructor is called. We have passed one
argument 8.2. length is initialized to the argument 8.2. breadth is initialized to
the 7.2 by default.
Solution Task 6

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:

Test (int x , int y ) : a(x) , b(y){

}
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

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