SlideShare a Scribd company logo
1 of 65
Starting Out with C++: Early Objects 5/e Ā© 2006 Pearson Education.
All Rights Reserved
Starting Out with C++: Early Objects
5th Edition
Chapter 11
More About Classes and
Object-Oriented Programming
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 2
Ā© 2006 Pearson Education.
All Rights Reserved
Topics
11.1 The this Pointer and Constant
Member Functions
11.2 Static Members
11.3 Friends of Classes
11.4 Memberwise Assignment
11.5 Copy Constructors
11.6 Operator Overloading
11.7 Type Conversion Operators
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 3
Ā© 2006 Pearson Education.
All Rights Reserved
Topics (continued)
11.8 Convert Constructors
11.9 Object Composition
11.10 Inheritance
11.11 Protected Members and Class Access
11.12 Constructors, Destructors, and
Inheritance
11.13 Overriding Base Class Functions
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 4
Ā© 2006 Pearson Education.
All Rights Reserved
11.1 The this Pointer and
Constant Member Functions
ā€¢ this pointer:
- Implicit parameter passed to a member
function
- points to the object calling the function
ā€¢ const member function:
- does not modify its calling object
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 5
Ā© 2006 Pearson Education.
All Rights Reserved
Using the this Pointer
ā€¢ Can be used to access members that
may be hidden by parameters with
same name:
class SomeClass
{
private:
int num;
public:
void setNum(int num)
{ this->num = num; }
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 6
Ā© 2006 Pearson Education.
All Rights Reserved
Constant Member Functions
ā€¢ Declared with keyword const
ā€¢ When const follows the parameter list,
int getX()const
the function is prevented from modifying the
object.
ā€¢ When const appears in the parameter list,
int setNum (const int num)
the function is prevented from modifying the
parameter. The parameter is read-only.
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 7
Ā© 2006 Pearson Education.
All Rights Reserved
11.2 Static Members
ā€¢ Static variables:
- Shared by all objects of the class
ā€¢ Static member functions:
- Can be used to access static member
variables
- Can be called before any objects are
created
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 8
Ā© 2006 Pearson Education.
All Rights Reserved
Static Member Variables
1) Must be declared in class with keyword
static:
class IntVal
{
public:
intVal(int val = 0)
{ value = val; valCount++ }
int getVal();
void setVal(int);
private:
int value;
static int valCount;
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 9
Ā© 2006 Pearson Education.
All Rights Reserved
Static Member Variables
2) Must be defined outside of the class:
class IntVal
{
//In-class declaration
static int valCount;
//Other members not shown
};
//Definition outside of class
int IntVal::valCount = 0;
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 10
Ā© 2006 Pearson Education.
All Rights Reserved
Static Member Variables
3) Can be accessed or modified by any
object of the class: Modifications by
one object are visible to all objects of
the class:
IntVal val1, val2;
valCount
val1 val2
2
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 11
Ā© 2006 Pearson Education.
All Rights Reserved
Static Member Functions
1)Declared with static before return type:
class IntVal
{ public:
static int getValCount()
{ return valCount; }
private:
int value;
static int valCount;
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 12
Ā© 2006 Pearson Education.
All Rights Reserved
Static Member Functions
2) Can be called independently of class
objects, through the class name:
cout << IntVal::getValCount();
3) Can be called before any objects of the
class have been created
4) Used mostly to manipulate static
member variables of the class
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 13
Ā© 2006 Pearson Education.
All Rights Reserved
11.3 Friends of Classes
ā€¢ Friend function: a function that is not a
member of a class, but has access to
private members of the class
ā€¢ A friend function can be a stand-alone
function or a member function of another
class
ā€¢ It is declared a friend of a class with the
friend keyword in the function prototype
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 14
Ā© 2006 Pearson Education.
All Rights Reserved
Friend Function Declarations
1)Friend function may be a stand-alone
function:
class aClass
{
private:
int x;
friend void fSet(aClass &c, int a);
};
void fSet(aClass &c, int a)
{
c.x = a;
}
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 15
Ā© 2006 Pearson Education.
All Rights Reserved
Friend Function Declarations
2) Friend function may be a member of another
class:
class aClass
{ private:
int x;
friend void OtherClass::fSet
(aClass &c, int a);
};
class OtherClass
{ public:
void fSet(aClass &c, int a)
{ c.x = a; }
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 16
Ā© 2006 Pearson Education.
All Rights Reserved
Friend Class Declaration
3) An entire class can be declared a friend of a
class:
class aClass
{private:
int x;
friend class frClass;
};
class frClass
{public:
void fSet(aClass &c,int a){c.x = a;}
int fGet(aClass c){return c.x;}
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 17
Ā© 2006 Pearson Education.
All Rights Reserved
Friend Class Declaration
ā€¢ If frClass is a friend of aClass, then all
member functions of frClass have
unrestricted access to all members of
aClass, including the private members.
ā€¢ In general, restrict the property of
Friendship to only those functions that
must have access to the private members
of a class.
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 18
Ā© 2006 Pearson Education.
All Rights Reserved
11.4 Memberwise Assignment
ā€¢ Can use = to assign one object to
another, or to initialize an object with an
objectā€™s data
ā€¢ Examples (assuming class V):
V v1, v2;
.// statements that assign
.// values to members of v1
v2 = v1;
V v3 = v2;
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 19
Ā© 2006 Pearson Education.
All Rights Reserved
11.5 Copy Constructors
ā€¢ Special constructor used when a newly
created object is initialized to the data of
another object of same class
ā€¢ Default copy constructor copies field-to-
field
ā€¢ Default copy constructor works fine in
many cases
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 20
Ā© 2006 Pearson Education.
All Rights Reserved
Copy Constructors
Problems occur when objects contain
pointers to dynamic storage:
class CpClass
{private:
int *p;
public:
CpClass(int v=0)
{ p = new int; *p = v;}
~CpClass(){delete p;}
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 21
Ā© 2006 Pearson Education.
All Rights Reserved
Default Constructor Causes
Sharing of Storage
CpClass c1(5);
if (true)
{
CpClass c2;
c2 = c1;
}
// c1 is corrupted
// when c2 goes
// out of scope
c1.p
c2.p
5
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 22
Ā© 2006 Pearson Education.
All Rights Reserved
Problems of Sharing Dynamic
Storage
ā€¢ Destructor of one object deletes
memory still in use by other objects
ā€¢ Modification of memory by one object
affects other objects sharing that
memory
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 23
Ā© 2006 Pearson Education.
All Rights Reserved
Programmer-Defined
Copy Constructors
ā€¢ A copy constructor is one that takes a
reference parameter to another object of
the same class
ā€¢ The copy constructor uses the data in the
object passed as parameter to initialize
the object being created
ā€¢ To avoid potential for data corruption,
reference parameter should be const
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 24
Ā© 2006 Pearson Education.
All Rights Reserved
Programmer-Defined Copy
Constructors
ā€¢ The copy constructor avoids problems
caused by memory sharing
ā€¢ Can allocate separate memory to hold new
objectā€™s dynamic member data
ā€¢ Can make new objectā€™s pointer point to this
memory
ā€¢ Copies the data, not the pointer, from the
original object to the new object
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 25
Ā© 2006 Pearson Education.
All Rights Reserved
Copy Constructor Example
class CpClass
{
int *p;
public:
CpClass(const CpClass &obj)
{ p = new int; *p = *obj.p; }
CpClass(int v=0)
{ p = new int; *p = v; }
~CpClass(){delete p;}
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 26
Ā© 2006 Pearson Education.
All Rights Reserved
11.6 Operator Overloading
ā€¢ Operators such as =, +, and others can be
redefined for use with objects of a class
ā€¢ The name of the function for the overloaded
operator is operator followed by the
operator symbol, e.g.,
operator+ is the overloaded + operator, and
operator= is the overloaded = operator
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 27
Ā© 2006 Pearson Education.
All Rights Reserved
Operator Overloading
ā€¢ Operators can be overloaded as
- instance member functions, or as
- friend functions
ā€¢ Overloaded operator must have the
same number of parameters as the
standard version. For example,
operator= must have two parameters,
since the = operator takes two
parameters.
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 28
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Operators as
Instance Members
ā€¢ A binary operator overloaded as an instance
member needs only one parameter, which
represents the operand on the right:
class OpClass
{
int x;
public:
OpClass operator+(OpClass right);
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 29
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Operators as
Instance Members
ā€¢ The left operand of the overloaded binary
operator is the calling object
ā€¢ The implicit left parameter is accessed
through the this pointer
OpClass OpClass::operator+(OpClass r)
{ OpClass sum;
sum.x = this->x + r.x;
return sum;
}
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 30
Ā© 2006 Pearson Education.
All Rights Reserved
Invoking an Overloaded
Operator
ā€¢ Operator can be invoked as a member
function:
OpClass a, b, s;
s = a.operator+(b);
ā€¢ It can also be invoked in the more
conventional manner:
OpClass a, b, s;
s = a + b;
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 31
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Assignment
ā€¢ Overloading assignment operator solves
problems with object assignment when
object contains pointer to dynamic memory.
ā€¢ Assignment operator is most naturally
overloaded as an instance member function
ā€¢ Needs to return a value of the assigned
object to allow cascaded assignments such
as
a = b = c;
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 32
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Assignment
ā€¢ Assignment overloaded as a member
function:
class CpClass
{
int *p;
public:
CpClass(int v=0)
{ p = new int; *p = v;
~CpClass(){delete p;}
CpClass operator=(CpClass);
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 33
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Assignment
ā€¢ Implementation returns a value:
CpClass CpClass::operator=(CpClass r)
{
*p = *r.p;
return *this;
};
ā€¢ Invoking the assignment operator:
CpClass a, x(45);
a.operator=(x);
a = x;
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 34
Ā© 2006 Pearson Education.
All Rights Reserved
Notes on
Overloaded Operators
ā€¢ Can change the entire meaning of an
operator
ā€¢ Most operators can be overloaded
ā€¢ Cannot change the number of operands
of the operator
ā€¢ Cannot overload the following
operators:
?: . .* sizeof
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 35
Ā© 2006 Pearson Education.
All Rights Reserved
Overloading Types of Operators
ā€¢ ++, -- operators overloaded differently
for prefix vs. postfix notation
ā€¢ Overloaded relational operators should
return a bool value
ā€¢ Overloaded stream operators >>, <<
must return istream, ostream objects
and take istream, ostream objects
as parameters
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 36
Ā© 2006 Pearson Education.
All Rights Reserved
Overloaded [] Operator
ā€¢ Can be used to create classes that
behave like arrays, providing bounds-
checking on subscripts
ā€¢ Overloaded [] returns a reference to
object, not an object itself
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 37
Ā© 2006 Pearson Education.
All Rights Reserved
11.7 Type Conversion Operators
ā€¢ Conversion Operators are member
functions that tell the compiler how to
convert an object of the class type to a
value of another type
ā€¢ The conversion information provided by
the conversion operators is automatically
used by the compiler in assignments,
initializations, and parameter passing
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 38
Ā© 2006 Pearson Education.
All Rights Reserved
Syntax of Conversion
Operators
ā€¢ Conversion operator must be a member
function of the class you are converting from
ā€¢ The name of the operator is the name of the
type you are converting to
ā€¢ The operator does not specify a return type
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 39
Ā© 2006 Pearson Education.
All Rights Reserved
Conversion Operator Example
ā€¢ To convert from a class IntVal to an integer:
class IntVal
{
int x;
public:
IntVal(int a = 0){x = a;}
operator int(){return x;}
};
ā€¢ Automatic conversion during assignment:
IntVal obj(15); int i;
i = obj; cout << i; // prints 15
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 40
Ā© 2006 Pearson Education.
All Rights Reserved
11.8 Convert Constructors
ā€¢ Convert constructors are constructors
with a single parameter of a type other
than the class
class CCClass
{ int x;
public:
CCClass() //default
CCClass(int a, int b);
CCClass(int a); //convert
CCClass(string s); //convert
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 41
Ā© 2006 Pearson Education.
All Rights Reserved
Example of a Convert Constructor
ā€¢ The C++ string class has a convert
constructor that converts from C-strings:
class string
{
public:
string(char *); //convert
ā€¦
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 42
Ā© 2006 Pearson Education.
All Rights Reserved
Uses of Convert Constructors
ā€¢ Automatically invoked by the compiler to
create an object from the value passed as
parameter:
string s("hello"); //convert C-string
CCClass obj(24); //convert int
ā€¢ Compiler allows convert constructor to be
invoked with assignment-like notation:
string s = "hello"; //convert C-string
CCClass obj = 24; //convert int
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 43
Ā© 2006 Pearson Education.
All Rights Reserved
Uses of Convert Constructors
ā€¢ Convert constructors allow functions that
take the class type as parameter to take
parameters of other types:
void myFun(string s); // needs string
// object
myFun("hello"); // accepts C-string
void myFun(CCClass c);
myFun(34); // accepts int
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 44
Ā© 2006 Pearson Education.
All Rights Reserved
11.9 Object Composition
ā€¢ Object composition: A data member of a
class may itself be an object of another
class
ā€¢ Supports the modeling of ā€˜has aā€™
relationship between classes ā€“ enclosing
class ā€˜has a(n)ā€™ instance of the enclosed
class
ā€¢ Same notation as for structures within
structures
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 45
Ā© 2006 Pearson Education.
All Rights Reserved
Object Composition
class StudentInfo
{
private:
string firstName, LastName;
string address, city, state, zip;
...
};
class Student
{
private:
StudentInfo personalData;
...
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 46
Ā© 2006 Pearson Education.
All Rights Reserved
11.10 Inheritance
ā€¢ Inheritance is a way of creating a new
class by starting with an existing class and
adding new members
ā€¢ The new class can replace or extend the
functionality of the existing class
ā€¢ Inheritance models the 'is a' relationship
between classes
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 47
Ā© 2006 Pearson Education.
All Rights Reserved
Inheritance - Terminology
ā€¢ The existing class is called the base class
ā€“ Alternates: parent class, superclass
ā€¢ The new class is called the derived class
ā€“ Alternates: child class, subclass
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 48
Ā© 2006 Pearson Education.
All Rights Reserved
Inheritance Syntax and Notation
// Existing class
class Base
{
};
// Derived class
class Derived : Base
{
};
Inheritance Class
Diagram
Base Class
Derived Class
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 49
Ā© 2006 Pearson Education.
All Rights Reserved
Inheritance of Members
class Parent
{
int a;
void bf();
};
class Child : Parent
{
int c;
void df();
};
ā€¢ Objects of Parent have
members
int a; void bf();
ā€¢ Objects of Child have
members
int a; void bf();
int c; void df();
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 50
Ā© 2006 Pearson Education.
All Rights Reserved
11.11 Protected Members
and Class Access
ā€¢ protected member access specification:
A class member labeled protected is
accessible to member functions of
derived classes as well as to member
functions of the same class
ā€¢ Like private, except accessible to
members functions of derived classes
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 51
Ā© 2006 Pearson Education.
All Rights Reserved
Base Class Access
Specification
ā€¢ Base class access specification:
determines how private, protected,
and public members of base class
can be accessed by derived classes
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 52
Ā© 2006 Pearson Education.
All Rights Reserved
Base Class Access
ā€¢ C++ supports three inheritance modes, also
called base class access modes:
- public inheritance
class Child : public Parent { };
- protected inheritance
class Child : protected Parent{ };
- private inheritance
class Child : private Parent{ };
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 53
Ā© 2006 Pearson Education.
All Rights Reserved
Base Class Access vs.
Member Access Specification
ā€¢ Base class access not same as
member access specification:
ā€“ Base class access: determine access for
inherited members
ā€“ Member access specification: determine
access for members defined in the class
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 54
Ā© 2006 Pearson Education.
All Rights Reserved
Member Access Specification
ā€¢ Specified using the keywords
private, protected, public
class MyClass
{
private: int a;
protected: int b; void fun();
public: void fun2();
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 55
Ā© 2006 Pearson Education.
All Rights Reserved
Base Class Access Specification
class Child : public Parent
{
protected:
int a;
public:
Child();
};
member access
base access
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 56
Ā© 2006 Pearson Education.
All Rights Reserved
Base Class Access Specifiers
1) public ā€“ object of derived class can be
treated as object of base class (not vice-
versa)
2) protected ā€“ more restrictive than public,
but allows derived classes to know some of
the details of parents
3) private ā€“ prevents objects of derived class
from being treated as objects of base class.
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 57
Ā© 2006 Pearson Education.
All Rights Reserved
Effect of Base Access
private: x
protected: y
public: z
private: x
protected: y
public: z
private: x
protected: y
public: z
Base class members
x inaccessible
private: y
private: z
x inaccessible
protected: y
protected: z
x inaccessible
protected: y
public: z
How base class members
appear in derived class
private
base class
protected
base class
public
base class
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 58
Ā© 2006 Pearson Education.
All Rights Reserved
11.12 Constructors,Destructors
and Inheritance
ā€¢ By inheriting every member of the base
class, a derived class object contains a
base class object
ā€¢ The derived class constructor can
specify which base class constructor
should be used to initialize the base
class object
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 59
Ā© 2006 Pearson Education.
All Rights Reserved
Order of Execution
ā€¢ When an object of a derived class is
created, the base classā€™s constructor is
executed first, followed by the derived
classā€™s constructor
ā€¢ When an object of a derived class is
destroyed, its destructor is called first,
then that of the base class
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 60
Ā© 2006 Pearson Education.
All Rights Reserved
Order of Execution
// Student ā€“ base class
// UnderGrad ā€“ derived class
// Both have constructors, destructors
int main()
{
UnderGrad u1;
...
return 0;
}// end main
Execute Student
constructor, then
execute
UnderGrad
constructor
Execute UnderGrad
destructor, then
execute Student
destructor
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 61
Ā© 2006 Pearson Education.
All Rights Reserved
Passing Arguments to
Base Class Constructor
ā€¢ Allows selection between multiple base
class constructors
ā€¢ Specify arguments to base constructor on
derived constructor heading
ā€¢ Can also be done with inline constructors
ā€¢ Must be done if base class has no default
constructor
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 62
Ā© 2006 Pearson Education.
All Rights Reserved
Passing Arguments to
Base Class Constructor
class Parent {
int x, y;
public: Parent(int,int);
};
class Child : public Parent {
int z
public:
Child(int a): Parent(a,a*a)
{z = a;}
};
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 63
Ā© 2006 Pearson Education.
All Rights Reserved
11.13 Overriding Base Class
Functions
ā€¢ Overriding: function in a derived class that
has the same name and parameter list as a
function in the base class
ā€¢ Typically used to replace a function in base
class with different actions in derived class
ā€¢ Not the same as overloading ā€“ with
overloading, the parameter lists must be
different
Chapter 11 Starting Out with C++: Early Objects 5/e
slide 64
Ā© 2006 Pearson Education.
All Rights Reserved
Access to Overridden
Function
ā€¢ When a function is overridden, all objects of
derived class use the overriding function.
ā€¢ If necessary to access the overridden
version of the function, it can be done using
the scope resolution operator with the name
of the base class and the name of the
function:
Student::getName();
Starting Out with C++: Early Objects 5/e Ā© 2006 Pearson Education.
All Rights Reserved
Starting Out with C++: Early Objects
5th Edition
Chapter 11
More About Classes and
Object-Oriented Programming

More Related Content

Similar to Chapter11.ppt

object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
Ā 
6_VirtualFunctions_AbstractClasses.pdf
6_VirtualFunctions_AbstractClasses.pdf6_VirtualFunctions_AbstractClasses.pdf
6_VirtualFunctions_AbstractClasses.pdfRamiDiab8
Ā 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
Ā 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptxSouravKrishnaBaul
Ā 
C++ Chapter 11 OOP - Part 3
C++ Chapter 11 OOP - Part 3C++ Chapter 11 OOP - Part 3
C++ Chapter 11 OOP - Part 3DanWooster1
Ā 
C++ basic
C++ basicC++ basic
C++ basicTITTanmoy
Ā 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdfstudy material
Ā 
C++ Chapter 11 OOP - Part 2
C++ Chapter 11 OOP - Part 2C++ Chapter 11 OOP - Part 2
C++ Chapter 11 OOP - Part 2DanWooster1
Ā 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers GuideDaisyWatson5
Ā 
Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4Matt
Ā 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lineslokeshG38
Ā 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...bhargavi804095
Ā 
Constructors.16
Constructors.16Constructors.16
Constructors.16myrajendra
Ā 
Java For Automation
Java   For AutomationJava   For Automation
Java For AutomationAbhijeet Dubey
Ā 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfesuEthopi
Ā 

Similar to Chapter11.ppt (20)

object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
Ā 
6_VirtualFunctions_AbstractClasses.pdf
6_VirtualFunctions_AbstractClasses.pdf6_VirtualFunctions_AbstractClasses.pdf
6_VirtualFunctions_AbstractClasses.pdf
Ā 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
Ā 
Introductions to Constructors.pptx
Introductions to Constructors.pptxIntroductions to Constructors.pptx
Introductions to Constructors.pptx
Ā 
C++ Chapter 11 OOP - Part 3
C++ Chapter 11 OOP - Part 3C++ Chapter 11 OOP - Part 3
C++ Chapter 11 OOP - Part 3
Ā 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
Ā 
C++ basic
C++ basicC++ basic
C++ basic
Ā 
Lec4
Lec4Lec4
Lec4
Ā 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
Ā 
C++ Chapter 11 OOP - Part 2
C++ Chapter 11 OOP - Part 2C++ Chapter 11 OOP - Part 2
C++ Chapter 11 OOP - Part 2
Ā 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
Ā 
EEE 3rd year oops cat 3 ans
EEE 3rd year  oops cat 3  ansEEE 3rd year  oops cat 3  ans
EEE 3rd year oops cat 3 ans
Ā 
Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4
Ā 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lines
Ā 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
Ā 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
Ā 
Constructors.16
Constructors.16Constructors.16
Constructors.16
Ā 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Ā 
C++ language
C++ languageC++ language
C++ language
Ā 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
Ā 

Recently uploaded

Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
Ā 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
Ā 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
Ā 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
Ā 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
Ā 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
Ā 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
Ā 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
Ā 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
Ā 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
Ā 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
Ā 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
Ā 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
Ā 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
Ā 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
Ā 
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
Ā 
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...9953056974 Low Rate Call Girls In Saket, Delhi NCR
Ā 

Recently uploaded (20)

Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
Ā 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
Ā 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
Ā 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
Ā 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
Ā 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
Ā 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
Ā 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
Ā 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Ā 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
Ā 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
Ā 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
Ā 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
Ā 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
Ā 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
Ā 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
Ā 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
Ā 
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Serviceyoung call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
Ā 
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)
Call Us ā‰½ 8377877756 ā‰¼ Call Girls In Shastri Nagar (Delhi)
Ā 
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
šŸ”9953056974šŸ”!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
Ā 

Chapter11.ppt

  • 1. Starting Out with C++: Early Objects 5/e Ā© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5th Edition Chapter 11 More About Classes and Object-Oriented Programming
  • 2. Chapter 11 Starting Out with C++: Early Objects 5/e slide 2 Ā© 2006 Pearson Education. All Rights Reserved Topics 11.1 The this Pointer and Constant Member Functions 11.2 Static Members 11.3 Friends of Classes 11.4 Memberwise Assignment 11.5 Copy Constructors 11.6 Operator Overloading 11.7 Type Conversion Operators
  • 3. Chapter 11 Starting Out with C++: Early Objects 5/e slide 3 Ā© 2006 Pearson Education. All Rights Reserved Topics (continued) 11.8 Convert Constructors 11.9 Object Composition 11.10 Inheritance 11.11 Protected Members and Class Access 11.12 Constructors, Destructors, and Inheritance 11.13 Overriding Base Class Functions
  • 4. Chapter 11 Starting Out with C++: Early Objects 5/e slide 4 Ā© 2006 Pearson Education. All Rights Reserved 11.1 The this Pointer and Constant Member Functions ā€¢ this pointer: - Implicit parameter passed to a member function - points to the object calling the function ā€¢ const member function: - does not modify its calling object
  • 5. Chapter 11 Starting Out with C++: Early Objects 5/e slide 5 Ā© 2006 Pearson Education. All Rights Reserved Using the this Pointer ā€¢ Can be used to access members that may be hidden by parameters with same name: class SomeClass { private: int num; public: void setNum(int num) { this->num = num; } };
  • 6. Chapter 11 Starting Out with C++: Early Objects 5/e slide 6 Ā© 2006 Pearson Education. All Rights Reserved Constant Member Functions ā€¢ Declared with keyword const ā€¢ When const follows the parameter list, int getX()const the function is prevented from modifying the object. ā€¢ When const appears in the parameter list, int setNum (const int num) the function is prevented from modifying the parameter. The parameter is read-only.
  • 7. Chapter 11 Starting Out with C++: Early Objects 5/e slide 7 Ā© 2006 Pearson Education. All Rights Reserved 11.2 Static Members ā€¢ Static variables: - Shared by all objects of the class ā€¢ Static member functions: - Can be used to access static member variables - Can be called before any objects are created
  • 8. Chapter 11 Starting Out with C++: Early Objects 5/e slide 8 Ā© 2006 Pearson Education. All Rights Reserved Static Member Variables 1) Must be declared in class with keyword static: class IntVal { public: intVal(int val = 0) { value = val; valCount++ } int getVal(); void setVal(int); private: int value; static int valCount; };
  • 9. Chapter 11 Starting Out with C++: Early Objects 5/e slide 9 Ā© 2006 Pearson Education. All Rights Reserved Static Member Variables 2) Must be defined outside of the class: class IntVal { //In-class declaration static int valCount; //Other members not shown }; //Definition outside of class int IntVal::valCount = 0;
  • 10. Chapter 11 Starting Out with C++: Early Objects 5/e slide 10 Ā© 2006 Pearson Education. All Rights Reserved Static Member Variables 3) Can be accessed or modified by any object of the class: Modifications by one object are visible to all objects of the class: IntVal val1, val2; valCount val1 val2 2
  • 11. Chapter 11 Starting Out with C++: Early Objects 5/e slide 11 Ā© 2006 Pearson Education. All Rights Reserved Static Member Functions 1)Declared with static before return type: class IntVal { public: static int getValCount() { return valCount; } private: int value; static int valCount; };
  • 12. Chapter 11 Starting Out with C++: Early Objects 5/e slide 12 Ā© 2006 Pearson Education. All Rights Reserved Static Member Functions 2) Can be called independently of class objects, through the class name: cout << IntVal::getValCount(); 3) Can be called before any objects of the class have been created 4) Used mostly to manipulate static member variables of the class
  • 13. Chapter 11 Starting Out with C++: Early Objects 5/e slide 13 Ā© 2006 Pearson Education. All Rights Reserved 11.3 Friends of Classes ā€¢ Friend function: a function that is not a member of a class, but has access to private members of the class ā€¢ A friend function can be a stand-alone function or a member function of another class ā€¢ It is declared a friend of a class with the friend keyword in the function prototype
  • 14. Chapter 11 Starting Out with C++: Early Objects 5/e slide 14 Ā© 2006 Pearson Education. All Rights Reserved Friend Function Declarations 1)Friend function may be a stand-alone function: class aClass { private: int x; friend void fSet(aClass &c, int a); }; void fSet(aClass &c, int a) { c.x = a; }
  • 15. Chapter 11 Starting Out with C++: Early Objects 5/e slide 15 Ā© 2006 Pearson Education. All Rights Reserved Friend Function Declarations 2) Friend function may be a member of another class: class aClass { private: int x; friend void OtherClass::fSet (aClass &c, int a); }; class OtherClass { public: void fSet(aClass &c, int a) { c.x = a; } };
  • 16. Chapter 11 Starting Out with C++: Early Objects 5/e slide 16 Ā© 2006 Pearson Education. All Rights Reserved Friend Class Declaration 3) An entire class can be declared a friend of a class: class aClass {private: int x; friend class frClass; }; class frClass {public: void fSet(aClass &c,int a){c.x = a;} int fGet(aClass c){return c.x;} };
  • 17. Chapter 11 Starting Out with C++: Early Objects 5/e slide 17 Ā© 2006 Pearson Education. All Rights Reserved Friend Class Declaration ā€¢ If frClass is a friend of aClass, then all member functions of frClass have unrestricted access to all members of aClass, including the private members. ā€¢ In general, restrict the property of Friendship to only those functions that must have access to the private members of a class.
  • 18. Chapter 11 Starting Out with C++: Early Objects 5/e slide 18 Ā© 2006 Pearson Education. All Rights Reserved 11.4 Memberwise Assignment ā€¢ Can use = to assign one object to another, or to initialize an object with an objectā€™s data ā€¢ Examples (assuming class V): V v1, v2; .// statements that assign .// values to members of v1 v2 = v1; V v3 = v2;
  • 19. Chapter 11 Starting Out with C++: Early Objects 5/e slide 19 Ā© 2006 Pearson Education. All Rights Reserved 11.5 Copy Constructors ā€¢ Special constructor used when a newly created object is initialized to the data of another object of same class ā€¢ Default copy constructor copies field-to- field ā€¢ Default copy constructor works fine in many cases
  • 20. Chapter 11 Starting Out with C++: Early Objects 5/e slide 20 Ā© 2006 Pearson Education. All Rights Reserved Copy Constructors Problems occur when objects contain pointers to dynamic storage: class CpClass {private: int *p; public: CpClass(int v=0) { p = new int; *p = v;} ~CpClass(){delete p;} };
  • 21. Chapter 11 Starting Out with C++: Early Objects 5/e slide 21 Ā© 2006 Pearson Education. All Rights Reserved Default Constructor Causes Sharing of Storage CpClass c1(5); if (true) { CpClass c2; c2 = c1; } // c1 is corrupted // when c2 goes // out of scope c1.p c2.p 5
  • 22. Chapter 11 Starting Out with C++: Early Objects 5/e slide 22 Ā© 2006 Pearson Education. All Rights Reserved Problems of Sharing Dynamic Storage ā€¢ Destructor of one object deletes memory still in use by other objects ā€¢ Modification of memory by one object affects other objects sharing that memory
  • 23. Chapter 11 Starting Out with C++: Early Objects 5/e slide 23 Ā© 2006 Pearson Education. All Rights Reserved Programmer-Defined Copy Constructors ā€¢ A copy constructor is one that takes a reference parameter to another object of the same class ā€¢ The copy constructor uses the data in the object passed as parameter to initialize the object being created ā€¢ To avoid potential for data corruption, reference parameter should be const
  • 24. Chapter 11 Starting Out with C++: Early Objects 5/e slide 24 Ā© 2006 Pearson Education. All Rights Reserved Programmer-Defined Copy Constructors ā€¢ The copy constructor avoids problems caused by memory sharing ā€¢ Can allocate separate memory to hold new objectā€™s dynamic member data ā€¢ Can make new objectā€™s pointer point to this memory ā€¢ Copies the data, not the pointer, from the original object to the new object
  • 25. Chapter 11 Starting Out with C++: Early Objects 5/e slide 25 Ā© 2006 Pearson Education. All Rights Reserved Copy Constructor Example class CpClass { int *p; public: CpClass(const CpClass &obj) { p = new int; *p = *obj.p; } CpClass(int v=0) { p = new int; *p = v; } ~CpClass(){delete p;} };
  • 26. Chapter 11 Starting Out with C++: Early Objects 5/e slide 26 Ā© 2006 Pearson Education. All Rights Reserved 11.6 Operator Overloading ā€¢ Operators such as =, +, and others can be redefined for use with objects of a class ā€¢ The name of the function for the overloaded operator is operator followed by the operator symbol, e.g., operator+ is the overloaded + operator, and operator= is the overloaded = operator
  • 27. Chapter 11 Starting Out with C++: Early Objects 5/e slide 27 Ā© 2006 Pearson Education. All Rights Reserved Operator Overloading ā€¢ Operators can be overloaded as - instance member functions, or as - friend functions ā€¢ Overloaded operator must have the same number of parameters as the standard version. For example, operator= must have two parameters, since the = operator takes two parameters.
  • 28. Chapter 11 Starting Out with C++: Early Objects 5/e slide 28 Ā© 2006 Pearson Education. All Rights Reserved Overloading Operators as Instance Members ā€¢ A binary operator overloaded as an instance member needs only one parameter, which represents the operand on the right: class OpClass { int x; public: OpClass operator+(OpClass right); };
  • 29. Chapter 11 Starting Out with C++: Early Objects 5/e slide 29 Ā© 2006 Pearson Education. All Rights Reserved Overloading Operators as Instance Members ā€¢ The left operand of the overloaded binary operator is the calling object ā€¢ The implicit left parameter is accessed through the this pointer OpClass OpClass::operator+(OpClass r) { OpClass sum; sum.x = this->x + r.x; return sum; }
  • 30. Chapter 11 Starting Out with C++: Early Objects 5/e slide 30 Ā© 2006 Pearson Education. All Rights Reserved Invoking an Overloaded Operator ā€¢ Operator can be invoked as a member function: OpClass a, b, s; s = a.operator+(b); ā€¢ It can also be invoked in the more conventional manner: OpClass a, b, s; s = a + b;
  • 31. Chapter 11 Starting Out with C++: Early Objects 5/e slide 31 Ā© 2006 Pearson Education. All Rights Reserved Overloading Assignment ā€¢ Overloading assignment operator solves problems with object assignment when object contains pointer to dynamic memory. ā€¢ Assignment operator is most naturally overloaded as an instance member function ā€¢ Needs to return a value of the assigned object to allow cascaded assignments such as a = b = c;
  • 32. Chapter 11 Starting Out with C++: Early Objects 5/e slide 32 Ā© 2006 Pearson Education. All Rights Reserved Overloading Assignment ā€¢ Assignment overloaded as a member function: class CpClass { int *p; public: CpClass(int v=0) { p = new int; *p = v; ~CpClass(){delete p;} CpClass operator=(CpClass); };
  • 33. Chapter 11 Starting Out with C++: Early Objects 5/e slide 33 Ā© 2006 Pearson Education. All Rights Reserved Overloading Assignment ā€¢ Implementation returns a value: CpClass CpClass::operator=(CpClass r) { *p = *r.p; return *this; }; ā€¢ Invoking the assignment operator: CpClass a, x(45); a.operator=(x); a = x;
  • 34. Chapter 11 Starting Out with C++: Early Objects 5/e slide 34 Ā© 2006 Pearson Education. All Rights Reserved Notes on Overloaded Operators ā€¢ Can change the entire meaning of an operator ā€¢ Most operators can be overloaded ā€¢ Cannot change the number of operands of the operator ā€¢ Cannot overload the following operators: ?: . .* sizeof
  • 35. Chapter 11 Starting Out with C++: Early Objects 5/e slide 35 Ā© 2006 Pearson Education. All Rights Reserved Overloading Types of Operators ā€¢ ++, -- operators overloaded differently for prefix vs. postfix notation ā€¢ Overloaded relational operators should return a bool value ā€¢ Overloaded stream operators >>, << must return istream, ostream objects and take istream, ostream objects as parameters
  • 36. Chapter 11 Starting Out with C++: Early Objects 5/e slide 36 Ā© 2006 Pearson Education. All Rights Reserved Overloaded [] Operator ā€¢ Can be used to create classes that behave like arrays, providing bounds- checking on subscripts ā€¢ Overloaded [] returns a reference to object, not an object itself
  • 37. Chapter 11 Starting Out with C++: Early Objects 5/e slide 37 Ā© 2006 Pearson Education. All Rights Reserved 11.7 Type Conversion Operators ā€¢ Conversion Operators are member functions that tell the compiler how to convert an object of the class type to a value of another type ā€¢ The conversion information provided by the conversion operators is automatically used by the compiler in assignments, initializations, and parameter passing
  • 38. Chapter 11 Starting Out with C++: Early Objects 5/e slide 38 Ā© 2006 Pearson Education. All Rights Reserved Syntax of Conversion Operators ā€¢ Conversion operator must be a member function of the class you are converting from ā€¢ The name of the operator is the name of the type you are converting to ā€¢ The operator does not specify a return type
  • 39. Chapter 11 Starting Out with C++: Early Objects 5/e slide 39 Ā© 2006 Pearson Education. All Rights Reserved Conversion Operator Example ā€¢ To convert from a class IntVal to an integer: class IntVal { int x; public: IntVal(int a = 0){x = a;} operator int(){return x;} }; ā€¢ Automatic conversion during assignment: IntVal obj(15); int i; i = obj; cout << i; // prints 15
  • 40. Chapter 11 Starting Out with C++: Early Objects 5/e slide 40 Ā© 2006 Pearson Education. All Rights Reserved 11.8 Convert Constructors ā€¢ Convert constructors are constructors with a single parameter of a type other than the class class CCClass { int x; public: CCClass() //default CCClass(int a, int b); CCClass(int a); //convert CCClass(string s); //convert };
  • 41. Chapter 11 Starting Out with C++: Early Objects 5/e slide 41 Ā© 2006 Pearson Education. All Rights Reserved Example of a Convert Constructor ā€¢ The C++ string class has a convert constructor that converts from C-strings: class string { public: string(char *); //convert ā€¦ };
  • 42. Chapter 11 Starting Out with C++: Early Objects 5/e slide 42 Ā© 2006 Pearson Education. All Rights Reserved Uses of Convert Constructors ā€¢ Automatically invoked by the compiler to create an object from the value passed as parameter: string s("hello"); //convert C-string CCClass obj(24); //convert int ā€¢ Compiler allows convert constructor to be invoked with assignment-like notation: string s = "hello"; //convert C-string CCClass obj = 24; //convert int
  • 43. Chapter 11 Starting Out with C++: Early Objects 5/e slide 43 Ā© 2006 Pearson Education. All Rights Reserved Uses of Convert Constructors ā€¢ Convert constructors allow functions that take the class type as parameter to take parameters of other types: void myFun(string s); // needs string // object myFun("hello"); // accepts C-string void myFun(CCClass c); myFun(34); // accepts int
  • 44. Chapter 11 Starting Out with C++: Early Objects 5/e slide 44 Ā© 2006 Pearson Education. All Rights Reserved 11.9 Object Composition ā€¢ Object composition: A data member of a class may itself be an object of another class ā€¢ Supports the modeling of ā€˜has aā€™ relationship between classes ā€“ enclosing class ā€˜has a(n)ā€™ instance of the enclosed class ā€¢ Same notation as for structures within structures
  • 45. Chapter 11 Starting Out with C++: Early Objects 5/e slide 45 Ā© 2006 Pearson Education. All Rights Reserved Object Composition class StudentInfo { private: string firstName, LastName; string address, city, state, zip; ... }; class Student { private: StudentInfo personalData; ... };
  • 46. Chapter 11 Starting Out with C++: Early Objects 5/e slide 46 Ā© 2006 Pearson Education. All Rights Reserved 11.10 Inheritance ā€¢ Inheritance is a way of creating a new class by starting with an existing class and adding new members ā€¢ The new class can replace or extend the functionality of the existing class ā€¢ Inheritance models the 'is a' relationship between classes
  • 47. Chapter 11 Starting Out with C++: Early Objects 5/e slide 47 Ā© 2006 Pearson Education. All Rights Reserved Inheritance - Terminology ā€¢ The existing class is called the base class ā€“ Alternates: parent class, superclass ā€¢ The new class is called the derived class ā€“ Alternates: child class, subclass
  • 48. Chapter 11 Starting Out with C++: Early Objects 5/e slide 48 Ā© 2006 Pearson Education. All Rights Reserved Inheritance Syntax and Notation // Existing class class Base { }; // Derived class class Derived : Base { }; Inheritance Class Diagram Base Class Derived Class
  • 49. Chapter 11 Starting Out with C++: Early Objects 5/e slide 49 Ā© 2006 Pearson Education. All Rights Reserved Inheritance of Members class Parent { int a; void bf(); }; class Child : Parent { int c; void df(); }; ā€¢ Objects of Parent have members int a; void bf(); ā€¢ Objects of Child have members int a; void bf(); int c; void df();
  • 50. Chapter 11 Starting Out with C++: Early Objects 5/e slide 50 Ā© 2006 Pearson Education. All Rights Reserved 11.11 Protected Members and Class Access ā€¢ protected member access specification: A class member labeled protected is accessible to member functions of derived classes as well as to member functions of the same class ā€¢ Like private, except accessible to members functions of derived classes
  • 51. Chapter 11 Starting Out with C++: Early Objects 5/e slide 51 Ā© 2006 Pearson Education. All Rights Reserved Base Class Access Specification ā€¢ Base class access specification: determines how private, protected, and public members of base class can be accessed by derived classes
  • 52. Chapter 11 Starting Out with C++: Early Objects 5/e slide 52 Ā© 2006 Pearson Education. All Rights Reserved Base Class Access ā€¢ C++ supports three inheritance modes, also called base class access modes: - public inheritance class Child : public Parent { }; - protected inheritance class Child : protected Parent{ }; - private inheritance class Child : private Parent{ };
  • 53. Chapter 11 Starting Out with C++: Early Objects 5/e slide 53 Ā© 2006 Pearson Education. All Rights Reserved Base Class Access vs. Member Access Specification ā€¢ Base class access not same as member access specification: ā€“ Base class access: determine access for inherited members ā€“ Member access specification: determine access for members defined in the class
  • 54. Chapter 11 Starting Out with C++: Early Objects 5/e slide 54 Ā© 2006 Pearson Education. All Rights Reserved Member Access Specification ā€¢ Specified using the keywords private, protected, public class MyClass { private: int a; protected: int b; void fun(); public: void fun2(); };
  • 55. Chapter 11 Starting Out with C++: Early Objects 5/e slide 55 Ā© 2006 Pearson Education. All Rights Reserved Base Class Access Specification class Child : public Parent { protected: int a; public: Child(); }; member access base access
  • 56. Chapter 11 Starting Out with C++: Early Objects 5/e slide 56 Ā© 2006 Pearson Education. All Rights Reserved Base Class Access Specifiers 1) public ā€“ object of derived class can be treated as object of base class (not vice- versa) 2) protected ā€“ more restrictive than public, but allows derived classes to know some of the details of parents 3) private ā€“ prevents objects of derived class from being treated as objects of base class.
  • 57. Chapter 11 Starting Out with C++: Early Objects 5/e slide 57 Ā© 2006 Pearson Education. All Rights Reserved Effect of Base Access private: x protected: y public: z private: x protected: y public: z private: x protected: y public: z Base class members x inaccessible private: y private: z x inaccessible protected: y protected: z x inaccessible protected: y public: z How base class members appear in derived class private base class protected base class public base class
  • 58. Chapter 11 Starting Out with C++: Early Objects 5/e slide 58 Ā© 2006 Pearson Education. All Rights Reserved 11.12 Constructors,Destructors and Inheritance ā€¢ By inheriting every member of the base class, a derived class object contains a base class object ā€¢ The derived class constructor can specify which base class constructor should be used to initialize the base class object
  • 59. Chapter 11 Starting Out with C++: Early Objects 5/e slide 59 Ā© 2006 Pearson Education. All Rights Reserved Order of Execution ā€¢ When an object of a derived class is created, the base classā€™s constructor is executed first, followed by the derived classā€™s constructor ā€¢ When an object of a derived class is destroyed, its destructor is called first, then that of the base class
  • 60. Chapter 11 Starting Out with C++: Early Objects 5/e slide 60 Ā© 2006 Pearson Education. All Rights Reserved Order of Execution // Student ā€“ base class // UnderGrad ā€“ derived class // Both have constructors, destructors int main() { UnderGrad u1; ... return 0; }// end main Execute Student constructor, then execute UnderGrad constructor Execute UnderGrad destructor, then execute Student destructor
  • 61. Chapter 11 Starting Out with C++: Early Objects 5/e slide 61 Ā© 2006 Pearson Education. All Rights Reserved Passing Arguments to Base Class Constructor ā€¢ Allows selection between multiple base class constructors ā€¢ Specify arguments to base constructor on derived constructor heading ā€¢ Can also be done with inline constructors ā€¢ Must be done if base class has no default constructor
  • 62. Chapter 11 Starting Out with C++: Early Objects 5/e slide 62 Ā© 2006 Pearson Education. All Rights Reserved Passing Arguments to Base Class Constructor class Parent { int x, y; public: Parent(int,int); }; class Child : public Parent { int z public: Child(int a): Parent(a,a*a) {z = a;} };
  • 63. Chapter 11 Starting Out with C++: Early Objects 5/e slide 63 Ā© 2006 Pearson Education. All Rights Reserved 11.13 Overriding Base Class Functions ā€¢ Overriding: function in a derived class that has the same name and parameter list as a function in the base class ā€¢ Typically used to replace a function in base class with different actions in derived class ā€¢ Not the same as overloading ā€“ with overloading, the parameter lists must be different
  • 64. Chapter 11 Starting Out with C++: Early Objects 5/e slide 64 Ā© 2006 Pearson Education. All Rights Reserved Access to Overridden Function ā€¢ When a function is overridden, all objects of derived class use the overriding function. ā€¢ If necessary to access the overridden version of the function, it can be done using the scope resolution operator with the name of the base class and the name of the function: Student::getName();
  • 65. Starting Out with C++: Early Objects 5/e Ā© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5th Edition Chapter 11 More About Classes and Object-Oriented Programming