Professional Documents
Culture Documents
Functions
Object Oriented Programming
• Object
– Collection of Data and Functions
– May represent a person, thing or place in real world
4
Core concept of OOP
OBJECT
set of methods
Operations (member functions)
6
Features of OOP
• Classes
– Designed for creating objects.
– All properties and functions of an object are specified in classes
• Real-world Modeling
– In real world, things have properties and working capability
– Similarly, objects have data and functions
– Data represent properties and functions represent working of
objects
7
Features of OOP (cont..)
• Reusability
– Inheritance is a technique that allows a programmer to use the code
of existing program to create new program.
• Information Hiding
– OOP allows the programmer to hide important data from the user. It
is performed by encapsulation.
• Polymorphism
– Ability of an object to behave in multiple ways
8
Objects
– An object represents an entity in the real world such as person, thing or
concept etc.
– An object is identified by its name
– An object consists or the following two things:
– Properties: Characteristics of an object
– Functions: Actions that can be performed by an object
• Example:
– Properties of Person Object are: Name, Age, Weight
– Properties of Car Object are: Color, Price, Model
• Example:
– Functions of Car Object are:
– Start
– Stop/Reverse
9
Class
• A collection of objects with same properties and function is known as class
• A Class is used to define the characteristics of the objects.
• It is used as a model for creating different objects of same type
• For Example, a class Person can be used to define the characteristics and
functions of a person. It can be used to create many objects of type Person
such as Ali, Usman, Abdullah etc.
• All objects of Person class will have same characteristics and functions
• Each object of class is known as an instance of its class.
• Ali, Usman and Abdullah are three instances of a class Person.
10
Defining a class
Components of a Class
• The data variables are called “data members”
• The functions of the class are called member functions
• Usually data items are set as private
• Member functions are set as public
• Hence, member functions can access data items to change their values.
Data items of a Class
• Can be any data type.
• They are declared private by default
• The private data members can only be accessed by member functions
Functions
Member Functions of a Class
• Used to
– access the values of the data members
– perform operations on the data members
• Are declared inside the class body
• Their definition can be placed inside the class body, or outside
the class body
• Can access both public and private members of the class
• Can be referred to using dot or arrow member access operator
14
Define a Class Type
……
int length;
public:
void set(int w, int l);
int area(); int a;
};
17
Declaration of an Object
};
19
A Simple Class
#include <iostream> int main()
using namespace std;
{
class smallobj //define a class
{ smallobj s1, s2;
private: s1.setdata(1066);
int somedata; //class data
s2.setdata(1776);
public:
void setdata(int d) //member function to set data s1.showdata();
{ somedata = d; } s2.showdata();
void showdata() //member function to display data return 0;
{ cout << “Data is “ << somedata << endl; }
}
};
• The first member
function sets the value
of the data items and
the second function
displays their values.
• Each object is called an
instance of the class.
Define a Member Function outside the Class
• It is a way of specifying what class something is associated with. In this
situation, Distance::add_dist() means “the add_dist() member function of the Distance
class.”
Functions
Define a Member Function outside the
Class
class Rectangle
{
private:
int width, length;
class name
public:
void set (int w, int l);
int area() {return width*length; } member function name
};
int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display(); 24
}
Class Exercise
• Make a class named part
• Declare data members as
– Modelnumber
– Partnumber
– Cost
• Declare members functions as
– Setpart (return type is void, input arguments are 3 data members to be set)
– Showpart (return type is void, input arguments are void)
Example
}
28
Object Initialization
#include <iostream.h>
class circle
{ 2. By Public Member Functions
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor 29
}
Constructor
• Automatic initialization is carried out using a special member function
called a constructor.
• A constructor is a member function that is executed automatically
whenever an object is created.
• A constructor is a member function having the same name as the class
• No return type is used for constructors.
• One of the most common tasks a constructor carries out is initializing
data members.
Definition of a constructor
And
Functions
Overloaded constructors calling
• Distance length; // calls first constructor
• Distance width(11, 6.0); // calls second constructor
Functions
Objects as function arguments
• Constructor overloading • Defining member functions outside the class
private: and Objects as function arguments
int feet;
float inches; void add_dist( Distance, Distance );
public: //prototype declared inside the class
Distance() : feet(0), inches(0.0)
{} //function definition outside the class
Distance(int ft, float in) : feet(ft), void Distance::add_dist(Distance d2, Distance d3)
inches(in){ } { inches = d2.inches + d3.inches;
feet = 0;
• Declaring the Object if(inches >= 12.0)
– Distance width; { inches -= 12.0;
– Distance width(5, 6.25); feet++;
}
feet += d2.feet + d3.feet; //add the feet
}
– (::) scope resolution operator.
Functions
Object Initialization
3. By Constructor
class Rectangle
{
private: • Default constructor
int width; • Copy constructor
int length;
• Constructor with parameters
public:
Rectangle();
Rectangle(const Rectangle &r); They are publicly accessible
Rectangle(int w, int l); Have the same name as the class
void set(int w, int l); There is no return type
int area(); Are used to initialize class data
} members
They have different signatures
36
Object Initialization
When a class is declared with no constructors,
the compiler automatically assumes default
class Rectangle constructor and copy constructor for it.
{
• Default constructor
private:
int width;
Rectangle :: Rectangle() { };
int length;
public:
• Copy constructor
void set(int w, int l);
int area(); Rectangle :: Rectangle (const
Rectangle & r)
}; {
width = r.width; length = r.length;
}; 37
The Default Copy Constructor
#include <iostream> void showdist() //display distance
using namespace std; { cout << feet << “\’-” << inches << ‘\”’; }
class Distance //English Distance class };
{ private:
int feet; int main()
float inches; { Distance dist1(11, 6.25); //two-arg constructor
public: Distance dist2(dist1); //one-arg constructor
Distance() : feet(0), inches(0.0) Distance dist3 = dist1; //also one-arg constructor
{} cout << “\ndist1 = “; dist1.showdist();
Distance(int ft, float in) : feet(ft), inches(in) cout << “\ndist2 = “; dist2.showdist();
{}
cout << “\ndist3 = “; dist3.showdist();
cout << endl; Declare two objects of type
void getdist() //get length from user
return 0; Distance, dist2 and dist3,
{
} initializing both to the value
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches; of dist1.
}
Functions
Object Initialization
• Initialize with default constructor
class Rectangle
Rectangle r1;
{
Rectangle *r3 = new Rectangle();
private:
int width;
• Initialize with copy constructor
int length;
public: Rectangle r4;
void set(int w, int l); r4.set(60,80);
int area(); Rectangle r5 = r4;
} Rectangle r6(r4);
Rectangle *r7 = new Rectangle(r4);
39
Object Initialization
40
Object Initialization
Write your own constructors
class Rectangle
{ Rectangle :: Rectangle()
private: {
int width; width = 20;
length = 50;
int length;
};
public:
Rectangle();
Rectangle(int w, int l); Rectangle *r7 = new Rectangle();
void set(int w, int l);
int area(); r7
6000
} 5000
5000
???
width = 20
length = 50
41
Objects as Function Arguments
An object can be used as a function argument like
any other data type.
Two ways:
A copy of the entire object is passed to the function. (
Pass-by-Value)
Only the address of the object is transferred to the
function. (Pass-by-Reference)
The pass-by-reference method is more efficient
since it requires to pass only the address of the
object and not the entire object.
#include <iostream>
using namespace std;
class Demo
{
private: int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
return 0;
}
Objects as Function Arguments
if(inches >= 12.0) //if total exceeds 12.0,
#include <iostream> void getdist()
{ //then decrease inches
{ inches -= 12.0; //by 12.0 and
using namespace std; cout << “\nEnter feet: “; cin >> feet; feet++; //increase feet
class Distance cout << “Enter inches: “; cin >> inches; } //by 1
{ } feet += d2.feet + d3.feet; //add the feet
private: void showdist() //display distance }
{ cout << feet << “\’-” << inches << ‘\”’; } int main()
int feet; {
void add_dist( Distance, Distance );
float inches; //declaration Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25);
public: //constructor (no args) };
dist1.getdist(); //get dist1 from user
Distance() : feet(0), inches(0.0) void Distance::add_dist(Distance d2, dist3.add_dist(dist1, dist2);
Distance d3)
{} cout << “\ndist1 = “; dist1.showdist();
{ cout << “\ndist2 = “; dist2.showdist();
//constructor (two args) inches = d2.inches + d3.inches; //add the cout << “\ndist3 = “; dist3.showdist();
Distance(int ft, float in) : feet(ft), inches cout << endl;
inches(in) feet = 0; //(for possible carry) return 0;
{} }
Functions
#include <iostream> void Distance::add_dist(Distance d2, Distance d3)
using namespace std; { inches = d2.inches + d3.inches; //add the inches
class Distance feet = 0; //(for possible carry)
{ private: if(inches >= 12.0) //if total exceeds 12.0,
int feet; { inches -= 12.0; //by 12.0 and
float inches; feet++; //increase feet
public: //constructor (no args) } //by 1
Distance() : feet(0), inches(0.0) feet += d2.feet + d3.feet; //add the feet
{ } }
Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args) int main()
{} { Distance dist1, dist3; //define two lengths
void getdist() //get length from user Distance dist2(11, 6.25); //define and initialize dist2
{ cout << “\nEnter feet: “; cin >> feet; dist1.getdist(); //get dist1 from user
cout << “Enter inches: “; cin >> inches; dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2
} cout << “\ndist1 = “; dist1.showdist();
Enter feet: 17
void showdist() //display distance cout << “\ndist2 = “; dist2.showdist();
Enter inches: 5.75
{ cout << feet << “\’-” << inches << ‘\”’; } cout << “\ndist3 = “; dist3.showdist(); dist1 = 17’-5.75”
void add_dist( Distance, Distance ); //declaration cout << endl; dist2 = 11’-6.25”
}; return 0; dist3 = 29’-0”
}
Functions
Functions
• Since add_dist() is a member function of the • In the following statement, what objects can
Distance class add_dist() access?
– It can access the private data in any object of class – dist3.add_dist(dist1, dist2);
Distance – Besides dist3, the object for which it was called, it
– Using dist1.inches and dist2.feet. can also access dist1 and dist2, because they are
• A member function is always given access to supplied as arguments.
– The object for which it was called: the object • void add_dist( Distance, Distance );
connected to it with the dot operator. – Notice that the result is not returned by the
– It may be able to access other objects as well. function. The return type of add_dist() is void.
– The result is stored automatically in the dist3
object.
• Every call to a member function is associated
with a particular object
• The function has direct access to all the
members, whether private or public, of that
object.
Functions
How to return an object from the function?
Returning Objects from Functions
Distance Distance::add_dist(Distance d2)
#include <iostream>
{ Distance temp;
using namespace std;
temp.inches = inches + d2.inches;
class Distance
if(temp.inches >= 12.0)
{ private:
int feet; { temp.inches -= 12.0;
float inches; temp.feet = 1;
public: }
Distance() : feet(0), inches(0.0) {} temp.feet += feet + d2.feet;
Distance(int ft, float in) : feet(ft), inches(in) { } return temp;
void getdist() }
{ cout << “\nEnter feet: “; cin >> feet; int main()
cout << “Enter inches: “; cin >> inches; { Distance dist1, dist3;
} Distance dist2(11, 6.25);
void showdist() dist1.getdist();
{ cout << feet << “\’-” << inches << ‘\”’; dist3 = dist1.add_dist(dist2);
} cout << “\ndist1 = “; dist1.showdist();
Distance add_dist(Distance); //add cout << “\ndist2 = “; dist2.showdist();
}; cout << “\ndist3 = “; dist3.showdist(); cout << endl;
return 0;
}
Functions
Functions
Destructors
• Destructor function is called automatically when an object is destroyed
• Its name is the class name preceded by a ~ (tilde)
• It has no argument
Functions
Another example
class Y {
private:
char * string;
int number;
public:
Y(const char*, int);
~Y()
{
delete[] string;
}
};
Functions
class Y { Y::Y(const char* n, int a) {
private: string = strcpy(new char[strlen(n) + 1 ], n);
char * string; number = a;
int number;
cout<<string<<endl;
public:
cout<<a;
Y(const char*, int);
}
~Y() { cout<<"\n I am deleting string bye";
delete[] string; } int main ()
}; {
Y yobj = Y("somestring", 10);
getch();
return 0;
}
Functions
Data Members of Class
• Can be of any type, built-in or user-defined
• non-static data member
– Each class object has its own copy
• static data member
– Acts as a global variable
– One copy per class type, e.g. counter
60
Static data item
• A static data item is useful when all objects of the same class must share
a common item of information.
• It is visible only within the class, but its lifetime is the entire program.
• It continues to exist even if there are no objects of the class.
• Declaration
– static int count;
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
count
int length;
static int count; r1 r2
public: width width
length length
void set(int w, int l);
int area(); width
r3 length
} 62
Example
#include <iostream> int foo::count = 0;
using namespace std; int main()
class foo { foo f1, f2, f3;
{ private: cout << “count is “ ;
static int count; cout<< f1.getcount() << endl;
public: cout << “count is “ ;
foo() { count++; } cout<< f2.getcount() << endl;
int getcount() cout << “count is “;
{ return count; } cout << f3.getcount() << endl;
}; return 0;
}
// what will be the output
Defining constant
• const keyword
– Constant data member
– Constant object
– Constant member function
– Constant input argument
Functions
const Member Functions
• A const member function class aClass
guarantees that it will never { private:
modify any of its class’s member int alpha;
data.
public:
void nonFunc()
The non-const function nonFunc() can
modify member data alpha, but the { alpha = 99; }
constant function conFunc() can’t. If it tries void conFunc() const
to, a compiler error results.
{ alpha = 99; } //ERROR: can’t modify
a member
};
Example const
Distance Distance::add_dist(const Distance& d2) const
{ Distance temp; //temporary variable
feet = 0; //ERROR: can’t modify this
d2.feet = 0; //ERROR: can’t modify d2
temp.inches = inches + d2.inches; //add the inches
if(temp.inches >= 12.0) //if total exceeds 12.0,
{ temp.inches -= 12.0; //by 12.0 and
temp.feet = 1; //increase feet The const function cannot modify
} temp.feet += feet + d2.feet; //add the feet by 1 the input parameters as well as
the data members of the object
but it can modify the data
return temp; variables declared within it’s
} scope
Functions
Example of const object
#include <iostream> int main()
using namespace std; {
class Distance //English Distance class const Distance football(300, 0);
{ private:
football.getdist(); //ERROR: football is const
int feet;
float inches;
cout << “football = “;
public: //2-arg constructor football.showdist(); //OK
Distance(int ft, float in) : feet(ft), inches(in){ } cout << endl;
void getdist() //user input; non-const func return 0;
{ cout << “\nEnter feet: “; cin >> feet; }
cout << “Enter inches: “; cin >> inches;
}
void showdist() const //display distance; const func
{ cout << feet << “\’-” << inches << ‘\”’; }
};
Class Definition - Access Control
• Information/data hiding
– To prevent the internal representation
from direct access from outside the class
• Access Specifiers
– public
• may be accessible from anywhere within a
program
– private
• may be accessed only by the member
functions, and friends of this class
– protected
• acts as public for derived classes
• behaves as private for the rest of the
program
70
Class Definition - Access Control
• The default access specifier is private
71
Access of non member functions to
public member functions continue…
However ……. ?
Friend Functions continue…
Special Characteristics:
int frifunc(alpha a, beta b)
Unlike member functions, it cannot access the //function definition
member names directly and has to use an object {
return( a.data + b.data );
name and dot membership operator with each }
member name.
It can be declared either in the public or private part
of a class without affecting its meaning.
Usually, it has objects as arguments.
Friend Functions continue…
class X class Y
{ {
… …
… …
int fun1 ( ); friend int X : : fun1 ( );
… …
}; };
Example of friend function outside the class
#include <iostream>
int frifunc(alpha a, beta b) //function definition
using namespace std;
{
class beta; //needed for frifunc declaration
return( a.data + b.data );
class alpha
}
{ private:
int data;
public:
int main()
alpha() : data(3) { } //no-arg constructor
{
friend int frifunc(alpha, beta); //friend function alpha aa;
}; beta bb;
class beta cout << frifunc(aa, bb) << endl; //call the
{ private:
function
int data;
return 0;
public: }
beta() : data(7) { } //no-arg constructor
friend int frifunc(alpha, beta); //friend function
};
Example of friend function outside the class
class beta; //needed for frifunc declaration
int alpha :: frifunc(alpha a, beta b) //function
class alpha definition
{ private: { return( a.data + b.data );
int data;
}
public:
alpha() : data(3) { } //no-arg constructor
int frifunc(alpha, beta); //member function
int main()
};
{ alpha aa;
class beta beta bb;
{ private: cout << aa.frifunc(aa, bb) << endl;
int data; //call the function
public: getch();
beta() : data(7) { } //no-arg constructor return 0;
friend int alpha :: frifunc(alpha, beta); //friend }
function
};
Friend Class continue…