SlideShare una empresa de Scribd logo
1 de 33
1
CSC241: Object Oriented Programming
Lecture No 04
2
Previous Lecture
• Constructor – example program
• Placing class in separate file
• Destructor – example program
• Constructor with arguments – example
program
3
Today’s Lecture
• Overloaded function
– Constructor
• const (constant)
– object
– member function
– data member
– object as function argument
• friend function
• this pointer
4
Objects as Function Arguments
class Distance { //Distance class
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) : feet(ft),
inches(in)
{ }
void getdist(){
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist(){
cout << feet << “:” << inches<<endl ;
}
void add_dist( Distance, Distance );
};
void Distance::add_dist(Distance d2,
Distance d3) {
inches = d2.inches + d3.inches;
feet = 0;
if(inches >= 12.0) {
inches -= 12.0;
feet++;
}
feet += d2.feet + d3.feet;
}
main()
{
Distance dist1, dist3;
Distance dist2(11, 6.5);
dist1.getdist();
dist3.add_dist(dist1, dist2);
cout << “ndist1 = “; dist1.showdist();
cout << “ndist2 = “; dist2.showdist();
cout << “ndist3 = “; dist3.showdist();
}
5
Overloaded Constructors
• It’s convenient to be able to give variables of type
Distance a value when they are first created
Distance dist2(11, 6.25);
• which defines an object, and initializes it to a value of
11 for feet and 6.25 for inches.
• Distance dist1, dist2; then No-argument constructor
is called/invoked (the default constructor)
• Since there are now two constructors with the
same name, Distance(), we say the constructor is
overloaded
6
Member Functions Defined Outside the
Class
• Such functions, needs to have a
prototype/declaration within the class
• The function name, add_dist(), is preceded by the
class name, Distance, and a new symbol—the
double colon (::). This symbol is called the scope
resolution operator.
• 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”
void Distance::add_dist(Distance d2, Distance d3)
7
Structures and Classes
• We used structures as a way to group data
and classes as a way to group both data and
functions
• In fact, you can use structures in almost
exactly the same way that you use classes
• The only formal difference between class and
struct is that in a class the members are
private by default, while in a structure they
are public by default.
8
Classes, Objects, and Memory
9
const (constant) object
• Some objects need to be modifiable and some
do not
• Keyword const is used to specify that an
object is not modifiable
• Any attempt to modify the object should
result in a compilation error
• declares a const object noon of class Time and
initializes it to 12 noon
10
const (constant) member function
• Constant member function will not allow to
modify private data member
class aClass
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{ alpha = 99; } //OK
void conFunc() const //const member function
{ alpha = 99; } //ERROR: can’t modify a member
};
11
Example – Time class
• Data members
• Member functions
program
12
const Objects as Function Arguments
class Distance { //Distance class
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist(){
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist(){
cout << feet << “:” << inches<<endl ;
}
Distance add_dist(const Distance&) const;
};
Distance Distance::add_dist(const
Distance& d2) const
{
Distance temp;
inches = 0;
temp.inches = inches + d2.inches;
if(temp.inches >= 12.0) {
temp.inches -= 12.0;
temp.feet = 1;
}
temp.feet += feet + d2.feet;
return temp;
}
13
Cont.
main()
{
Distance dist1, dist3;
Distance dist2(11, 6.25);
dist1.getdist();
dist3 = dist1.add_dist(dist2);
cout << "ndist1 = "; dist1.showdist();
cout << "ndist2 = "; dist2.showdist();
cout << "ndist3 = "; dist3.showdist();
}
feet
inches
dist1
0
0.0
feet
inches
dist3
0
0.0
feet
inches
dist2
11
6.5
void getdist(){
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
5
7.0
Distance Distance::add_dist(const Distance& d2) const {
Distance temp;
temp.inches = inches + d2.inches;
if(temp.inches >= 12.0) {
temp.inches -= 12.0;
temp.feet = 1;
}
temp.feet += feet + d2.feet;
return temp;
}
feet
inches
temp
d2
13.5
1.5
1
17
void showdist(){
cout << feet << “:” << inches<<endl ;
}
dist1 = 5 : 7.0
dist2 = 11 : 6.5
dist3 = 17 : 1.5
Go to program
17
1.5
14
Initializing a const Data Member
• Constant data member must be initialized
using member initializer list
private:
int count;
const int increment;
• const data member must be initialized as soon
as the object is created
15
Example
Go to program
16
Common errors while using const
• Following are compilation errors
– Defining as const a member function that
modifies a data member of an object
– Defining as const a member function that calls a
non-const member function of the class on the
same instance of the class
– Invoking a non-const member function on a const
object
17
friend Functions
• A friend function of a class is defined outside
that class's scope
• It has the right to access the non-public (and
public) members of the class
• Prototypes for friend functions appear in the
class definition but friends are not member
functions
• They are called just like a normal functions
18
Cont.
• Friend function can be declaration can be
placed any where in class definition
• Place all friendship declarations first inside the
class definition's body
19
Example – Count class
Go to program
20
Using this pointer
• Object's member functions can manipulate
the object's data
• How do member functions know which
object's data members to manipulate?
• Every object has access to its own address
through a pointer called this
• this pointer is passed (by the compiler) as an
implicit argument to each of the object's non-
static member functions
21
Cont.
• An object's this pointer is not part of the
object itself
• The size of the memory occupied by the this
pointer is not reflected in the result of a sizeof
operation on the object
• Objects use this pointer implicitly or explicitly
to reference their data members and member
functions
22
Type of this pointer
• The type of the this pointer depends on the
type of the object
– non constant member function of class Employee,
the this pointer has type Employee * const
– constant member function of the class Employee,
the this pointer has the data type const Employee
* const
23
Implicitly and Explicitly Use this Pointer
Go to program
24
Cascading function calls using this pointer
• Multiple member functions are invoked in the same
statement
25
Cont.
• Why does the technique of returning *this as a
reference work?
• The dot operator (.) associates from left to right
• so line 14 first evaluates t.setHour( 18 ) then returns
a reference to object t
• The remaining expression is then interpreted as
– t.setMinute( 30 ).setSecond( 22 );
• t.setMinute( 30 ) call executes and returns a
reference to the object t.
– t.setSecond( 22 ); Go to program
26
static Data Members
• Each object of a class has its own copy of all
the data members of the class
• In certain cases, only one copy of a variable
should be shared by all objects of a class
• A static data member is used
• If a data item in a class is declared as static,
only one such item is created for the entire
class, no matter how many objects there are
27
Cont.
• A member static variable 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
• A static data item is useful when all objects of
the same class must share a common item of
information
28
Uses of static data member
• Suppose an object needed to know how many
other objects of its class were in the program
• In a road-racing game, for example, a race car
might want to know how many other cars are
still in the race
• In this case a static variable count could be
included as a member of the class
• All the objects would have access to this
variable
29
Example – Race class
class Race
{
private:
static int count;
int carNo;
public:
Race()
{ count++; carNo=0; }
void setCarNo(int no)
{ carNo = no; }
void printData() {
cout<<“Total car = ”<< count;
cout<<“,Car No. = ”<<carNo<<endl;
}
};
int Race::count = 0;
main()
{
Race c1, c2, c3; //create three objects
c1.setCarNo(10); c2.setCarNo(11);
c3.setCarNo(12);
c1.printData();
c2.printData(); c3.printData();
}
main()
{
Race c1, c2; //create three objects
c1.setCarNo(10); c2.setCarNo(11);
c1.printData();
c2.printData();
Race c3; c3.setCarNo(12);
c3.printData();
}
Total car = 3, Car No. 10
Total car = 3, Car No. 11
Total car = 3, Car No. 12
Total car = 2, Car No. 10
Total car = 2, Car No. 11
Total car = 3, Car No. 12
30
Composition – Objects as Members of Classes
• An AlarmClock object needs to know when it
is supposed to sound its alarm
• So why not include a Time object as a
member of the AlarmClock class
• It is refer as has-a relationship
• We will see how an object's constructor can
pass arguments to member-object
constructors
31
Example program
Date.h
Date class
Employee.h
Employee class
Date birthday
Date hiredate
Source_emp.cpp
Employee manager
Go to program
firstname
lastname
manager
birthday
day
month
year
hireday
day
month
year
32
33
Dynamic Memory Management
• C++ enables programmers to control the
allocation and deallocation of memory in a
program for any built-in or user-defined type
• Performed with operators new and delete

Más contenido relacionado

Similar a OOP.pptx

Function class in c++
Function class in c++Function class in c++
Function class in c++
Kumar
 
object oriented programming part inheritance.pptx
object oriented programming part inheritance.pptxobject oriented programming part inheritance.pptx
object oriented programming part inheritance.pptx
urvashipundir04
 

Similar a OOP.pptx (20)

14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Python-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdfPython-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdf
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
 
Python for data analysis
Python for data analysisPython for data analysis
Python for data analysis
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
Python for Data Analysis.pdf
Python for Data Analysis.pdfPython for Data Analysis.pdf
Python for Data Analysis.pdf
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptxstatic MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptx
 
02.adt
02.adt02.adt
02.adt
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
object oriented programming part inheritance.pptx
object oriented programming part inheritance.pptxobject oriented programming part inheritance.pptx
object oriented programming part inheritance.pptx
 

Último

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

OOP.pptx

  • 1. 1 CSC241: Object Oriented Programming Lecture No 04
  • 2. 2 Previous Lecture • Constructor – example program • Placing class in separate file • Destructor – example program • Constructor with arguments – example program
  • 3. 3 Today’s Lecture • Overloaded function – Constructor • const (constant) – object – member function – data member – object as function argument • friend function • this pointer
  • 4. 4 Objects as Function Arguments class Distance { //Distance class private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) : feet(ft), inches(in) { } void getdist(){ cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist(){ cout << feet << “:” << inches<<endl ; } void add_dist( Distance, Distance ); }; void Distance::add_dist(Distance d2, Distance d3) { inches = d2.inches + d3.inches; feet = 0; if(inches >= 12.0) { inches -= 12.0; feet++; } feet += d2.feet + d3.feet; } main() { Distance dist1, dist3; Distance dist2(11, 6.5); dist1.getdist(); dist3.add_dist(dist1, dist2); cout << “ndist1 = “; dist1.showdist(); cout << “ndist2 = “; dist2.showdist(); cout << “ndist3 = “; dist3.showdist(); }
  • 5. 5 Overloaded Constructors • It’s convenient to be able to give variables of type Distance a value when they are first created Distance dist2(11, 6.25); • which defines an object, and initializes it to a value of 11 for feet and 6.25 for inches. • Distance dist1, dist2; then No-argument constructor is called/invoked (the default constructor) • Since there are now two constructors with the same name, Distance(), we say the constructor is overloaded
  • 6. 6 Member Functions Defined Outside the Class • Such functions, needs to have a prototype/declaration within the class • The function name, add_dist(), is preceded by the class name, Distance, and a new symbol—the double colon (::). This symbol is called the scope resolution operator. • 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” void Distance::add_dist(Distance d2, Distance d3)
  • 7. 7 Structures and Classes • We used structures as a way to group data and classes as a way to group both data and functions • In fact, you can use structures in almost exactly the same way that you use classes • The only formal difference between class and struct is that in a class the members are private by default, while in a structure they are public by default.
  • 9. 9 const (constant) object • Some objects need to be modifiable and some do not • Keyword const is used to specify that an object is not modifiable • Any attempt to modify the object should result in a compilation error • declares a const object noon of class Time and initializes it to 12 noon
  • 10. 10 const (constant) member function • Constant member function will not allow to modify private data member class aClass { private: int alpha; public: void nonFunc() //non-const member function { alpha = 99; } //OK void conFunc() const //const member function { alpha = 99; } //ERROR: can’t modify a member };
  • 11. 11 Example – Time class • Data members • Member functions program
  • 12. 12 const Objects as Function Arguments class Distance { //Distance class private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) : feet(ft), inches(in) { } void getdist(){ cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist(){ cout << feet << “:” << inches<<endl ; } Distance add_dist(const Distance&) const; }; Distance Distance::add_dist(const Distance& d2) const { Distance temp; inches = 0; temp.inches = inches + d2.inches; if(temp.inches >= 12.0) { temp.inches -= 12.0; temp.feet = 1; } temp.feet += feet + d2.feet; return temp; }
  • 13. 13 Cont. main() { Distance dist1, dist3; Distance dist2(11, 6.25); dist1.getdist(); dist3 = dist1.add_dist(dist2); cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); cout << "ndist3 = "; dist3.showdist(); } feet inches dist1 0 0.0 feet inches dist3 0 0.0 feet inches dist2 11 6.5 void getdist(){ cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } 5 7.0 Distance Distance::add_dist(const Distance& d2) const { Distance temp; temp.inches = inches + d2.inches; if(temp.inches >= 12.0) { temp.inches -= 12.0; temp.feet = 1; } temp.feet += feet + d2.feet; return temp; } feet inches temp d2 13.5 1.5 1 17 void showdist(){ cout << feet << “:” << inches<<endl ; } dist1 = 5 : 7.0 dist2 = 11 : 6.5 dist3 = 17 : 1.5 Go to program 17 1.5
  • 14. 14 Initializing a const Data Member • Constant data member must be initialized using member initializer list private: int count; const int increment; • const data member must be initialized as soon as the object is created
  • 16. 16 Common errors while using const • Following are compilation errors – Defining as const a member function that modifies a data member of an object – Defining as const a member function that calls a non-const member function of the class on the same instance of the class – Invoking a non-const member function on a const object
  • 17. 17 friend Functions • A friend function of a class is defined outside that class's scope • It has the right to access the non-public (and public) members of the class • Prototypes for friend functions appear in the class definition but friends are not member functions • They are called just like a normal functions
  • 18. 18 Cont. • Friend function can be declaration can be placed any where in class definition • Place all friendship declarations first inside the class definition's body
  • 19. 19 Example – Count class Go to program
  • 20. 20 Using this pointer • Object's member functions can manipulate the object's data • How do member functions know which object's data members to manipulate? • Every object has access to its own address through a pointer called this • this pointer is passed (by the compiler) as an implicit argument to each of the object's non- static member functions
  • 21. 21 Cont. • An object's this pointer is not part of the object itself • The size of the memory occupied by the this pointer is not reflected in the result of a sizeof operation on the object • Objects use this pointer implicitly or explicitly to reference their data members and member functions
  • 22. 22 Type of this pointer • The type of the this pointer depends on the type of the object – non constant member function of class Employee, the this pointer has type Employee * const – constant member function of the class Employee, the this pointer has the data type const Employee * const
  • 23. 23 Implicitly and Explicitly Use this Pointer Go to program
  • 24. 24 Cascading function calls using this pointer • Multiple member functions are invoked in the same statement
  • 25. 25 Cont. • Why does the technique of returning *this as a reference work? • The dot operator (.) associates from left to right • so line 14 first evaluates t.setHour( 18 ) then returns a reference to object t • The remaining expression is then interpreted as – t.setMinute( 30 ).setSecond( 22 ); • t.setMinute( 30 ) call executes and returns a reference to the object t. – t.setSecond( 22 ); Go to program
  • 26. 26 static Data Members • Each object of a class has its own copy of all the data members of the class • In certain cases, only one copy of a variable should be shared by all objects of a class • A static data member is used • If a data item in a class is declared as static, only one such item is created for the entire class, no matter how many objects there are
  • 27. 27 Cont. • A member static variable 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 • A static data item is useful when all objects of the same class must share a common item of information
  • 28. 28 Uses of static data member • Suppose an object needed to know how many other objects of its class were in the program • In a road-racing game, for example, a race car might want to know how many other cars are still in the race • In this case a static variable count could be included as a member of the class • All the objects would have access to this variable
  • 29. 29 Example – Race class class Race { private: static int count; int carNo; public: Race() { count++; carNo=0; } void setCarNo(int no) { carNo = no; } void printData() { cout<<“Total car = ”<< count; cout<<“,Car No. = ”<<carNo<<endl; } }; int Race::count = 0; main() { Race c1, c2, c3; //create three objects c1.setCarNo(10); c2.setCarNo(11); c3.setCarNo(12); c1.printData(); c2.printData(); c3.printData(); } main() { Race c1, c2; //create three objects c1.setCarNo(10); c2.setCarNo(11); c1.printData(); c2.printData(); Race c3; c3.setCarNo(12); c3.printData(); } Total car = 3, Car No. 10 Total car = 3, Car No. 11 Total car = 3, Car No. 12 Total car = 2, Car No. 10 Total car = 2, Car No. 11 Total car = 3, Car No. 12
  • 30. 30 Composition – Objects as Members of Classes • An AlarmClock object needs to know when it is supposed to sound its alarm • So why not include a Time object as a member of the AlarmClock class • It is refer as has-a relationship • We will see how an object's constructor can pass arguments to member-object constructors
  • 31. 31 Example program Date.h Date class Employee.h Employee class Date birthday Date hiredate Source_emp.cpp Employee manager Go to program firstname lastname manager birthday day month year hireday day month year
  • 32. 32
  • 33. 33 Dynamic Memory Management • C++ enables programmers to control the allocation and deallocation of memory in a program for any built-in or user-defined type • Performed with operators new and delete