SlideShare uma empresa Scribd logo
1 de 15
CSE 332: C++ classes
Free Ebooks Download
Mba Ebooks
By Edhole
Mba ebooks
Free ebooks download
http://ebooks.edhole.com
CSE 332: C++ classes
Review of Types in C++
• Two main kinds of types in C++
– native and user-defined
• User-defined types
– Classes, structs, unions, enumerations declared by code
– includes those provided by C++ libraries, like bad_alloc
• Native types
– Types “built in” to the C++ language itself: int, long, float, …
• Type definitions
– A typedef creates new type names for other types
– We’ll use this idea a lot when we talk about templates
http://ebooks.edhole.com
CSE 332: C++ classes
Overview of C++ Polymorphism
Poly (= many) + morphism (= forms)
• Inheritance creates sub-types
• Only applies to user-defined classes
(and structs)
• A publicly derived class is-a subtype
of its base class
– Object b has only one type
• Instance of Base only
– Object d has two types
• Instance of both Base, Derived
class Base {
public:
Base (int i);
Base (const Base & b);
virtual ~Base ();
void operator= (const Base & b);
void i (int i); int i () const;
private:
int i_;
};
class Derived : public Base {
public:
Derived (int i, int j, int k);
Derived (const Derived & d);
virtual ~Derived ();
void operator= (const Derived & d);
void j (int j); int j () const;
void k (int k); int k () const;
private:
int j_; int k_;
};
int main (int, char *[]) {
Base b (1);
Derived d(2, 3, 4);
}
http://ebooks.edhole.com
CSE 332: C++ classes
Aliasing and Substitution with Inheritance
• Aliasing with inheritance
– Pointer dptr can only point to d
• Can’t do dptr = b; dptr->j ();
– Pointer bptr can point to b or d
• But can only call Base functions
• Can’t say bptr->j ();
• Liskov Substitution Principle
– if S is a subtype of T, then can use an
S where a T is needed
• But not the other way around
• bptr = &d; ok, but not dptr = &b;
class Base {
public:
Base (int i);
Base (const Base & b);
virtual ~Base ();
void operator= (const Base & b);
void i (int i); int i () const;
private:
int i_;
};
class Derived : public Base {
public:
Derived (int i, int j, int k);
Derived (const Derived & d);
virtual ~Derived ();
void operator= (const Derived & d);
void j (int j); int j () const;
void k (int k); int k () const;
private:
int j_; int k_;
};
int main (int, char *[]) {
Base b (1);
Derived d(2, 3, 4);
Base *bptr = d;
Derived *dptr = d;
}
http://ebooks.edhole.com
CSE 332: C++ classes
Static vs. Dynamic Types
• Pointers have static types
– References have them too…
– Type with which it was declared
– Most general type it can alias
• Base is more general than Derived
– Static type of bptr is Base*
– Static type of dptr is Derived*
• What’s pointed to / referenced has a
dynamic type
– Type of object currently aliased
• Dynamic type of *bptr can be either
Base or Derived
• Dynamic type of *dptr is Derived
– Expands if classes inherit from Derived
– May change if pointer reassigned
– May change if reference parameter is
passed a different object
class Base {
public:
Base (int i);
Base (const Base & b);
virtual ~Base ();
void operator= (const Base & b);
void i (int i); int i () const;
private:
int i_;
};
class Derived : public Base {
public:
Derived (int i, int j, int k);
Derived (const Derived & d);
virtual ~Derived ();
void operator= (const Derived & d);
void j (int j); int j () const;
void k (int k); int k () const;
private:
int j_; int k_;
};
int main (int, char *[]) {
Base b (1);
Derived d(2, 3, 4);
Base * bptr = d;
Derived * dptr = d;
}
http://ebooks.edhole.com
CSE 332: C++ classes
Declaring Virtual Member Functions
class A {
public:
virtual foo () {cout<<"A";}
};
class B : public A {
public:
// overrides A::foo definition
virtual foo() {cout<<"B";}
};
int main (int, char *[]) {
A *aptr = new B;
// prints "B" : would print
// "A" instead if non-virtual
aptr->foo ();
delete aptr;
return 0;
};
• Enables polymorphism using
pointers and references in C++
• Class declares a member function
to be virtual
• Derived class overrides the base
class’s definition of the function
– Good style to say it’s virtual at re-
declaration, but it’s virtual anyway
– Overriding only happens when
signatures are the same
– Otherwise it just Overloads the
function or operator name with a
different signature
• Ensures function definition is
resolved by dynamic type
– E.g., that destructors farther down the
hierarchy get called
• Non-virtual functions are resolved
by static type
http://ebooks.edhole.com
CSE 332: C++ classes
Calling Virtual Member Functions
class A {
public:
void x() {cout<<"A:x";};
virtual void y() {cout<<"A:y";};
};
class B : public A {
public:
void x() {cout<<"B:x";};
virtual void y() {cout<<"B:y";};
};
int main () {
B b;
A *ap = &b; B *bp = &b;
b.x (); // prints "B:x"
b.y (); // prints "B:y"
bp->x (); // prints "B:x"
bp->y (); // prints "B:y"
ap->x (); // prints "A:x"
ap->y (); // prints "B:y"
return 0;
};
• Only matter with pointer or reference
– Calls on object itself resolved statically
– E.g., b.y();
• Look first at pointer/reference type
– If non-virtual, resolve statically
• E.g., ap->x();
– If virtual, resolve dynamically
• E.g., ap->y();
• Note that virtual keyword need not be
repeated in derived classes
– But it’s good style to do so
• Caller can force static resolution of a
virtual function via scope operator
– E.g., ap->A::y(); prints “A:y”
– E.g., ap->B::y(); prints “B:y”
– But should use RTTI to be type safe
http://ebooks.edhole.com
CSE 332: C++ classes
Virtual Destructors and the Class Slicing Problem
class A {
public:
A () {cout<<" A";}
virtual ~A () {cout<<" ~A";}
};
class B : public A {
public:
B () :A() {cout<<" B";}
virtual ~B() {cout<<" ~B";}
};
int main (int, char *[]) {
// prints "A B"
A *ap = new B;
// prints "~B ~A" : would only
// print "~A" if non-virtual
delete ap;
return 0;
};
• Derived class destructor called
before base class destructor
• But, need to watch out for static
versus dynamic type differences
• Making destructor virtual
– ensures chain of destructor calls starts
at dynamic type and moves up
– Otherwise would start at static type
(would “slice off” calls to destructors of
more derived classes)
• “Class slicing problem” can also
occur with pass/catch by value
– Only static type gets copied
– Another reason to always catch/pass by
reference (using const if needed)
http://ebooks.edhole.com
CSE 332: C++ classes
Declaring Pure Virtual Functions
class A {
public:
virtual void x() = 0;
virtual void y() = 0;
};
class B : public A {
public:
virtual void x();
virtual void y() = 0;
};
class C : public B {
public:
virtual void y();
};
int main () {
A * ap = new C;
ap->x ();
ap->y ();
delete ap;
return 0;
};
• A is an Abstract Base Class
– Similar to an interface in Java
– Declares pure virtual functions (=0)
• Derived classes override those pure virtual member
functions
– B overrides x(), C overrides y()
– Good style (but optional) to re-declare pure virtual
functions that are not yet overridden
• Can’t instantiate class with declared or inherited
pure virtual functions
– A and B are abstract, but C is concrete
– Can create instances of C, but not B or A
• Can still have a pointer to an abstract class type
– Very useful for polymorphism
http://ebooks.edhole.com
CSE 332: C++ classes
Tips on Using Polymorphism
• Push common code/variables up into base classes
• Use public inheritance for polymorphism
– Use private/protected inheritance for encapsulation
• Polymorphism depends on dynamic typing
– Use a base-class pointer or reference if you want polymorphism
– Use virtual member functions for dynamic overriding
• Use abstract base classes to declare interfaces
• Even though you don’t have to, re-label each virtual (and
pure virtual) function in derived classes
http://ebooks.edhole.com
CSE 332: C++ classes
Type Casting in C++• Casting up the inheritance type hierarchy, size conversion
– Converts between related types
– Note that static_cast does not examine the dynamic type
– Widens the static type to be more general, farther from dynamic type
B* p = static_cast<B*>(d); // d is D *
char c = static_cast<char>(i); // -128 <= i <= 127
• Casting down the inheritance type hierarchy
– Narrows the static type to be less general, closer to dynamic type
D* p = dynamic_cast<D*>(b); // b is B *
• Casting away const protections
– Tells compiler: trust me, I know it’s ok to modify this variable
T* p = const_cast<T*>(q); // q is const T *
• Reinterpretation of what is being pointed to
– Tells compiler: trust me, I really really know what I’m doing
T* p = reinterpret_cast<T*>(v); // v is void*
http://ebooks.edhole.com
CSE 332: C++ classes
Run-Time Type Information (RTTI)• Using dynamic_cast<> operator template
– Examples
dynamic_cast<T*>(p)
dynamic_cast<T&>(r)
– If p points to (sub-)type T then address is returned, else 0
– If r references (sub-)type T then a reference to T is returned
• otherwise an exception is thrown
• Using typeid() operator and type_info class
– Only use when appropriate (see Prata 5th
ed. pp. 847-848)
– Need to include <typeinfo> header file to use them
– returns type information (including a name string)
• if polymorphic then the dynamic type is returned
• otherwise the static type is returned.
http://ebooks.edhole.com
CSE 332: C++ classes
Basic Ideas of Multiple inheritance
• Override resolution is not applied across class scope
boundaries
• So if two different base classes define a function
with the same signature, you have an ambiguity
(compiler cannot figure it out)
– Can be explicit, Base1::fn() or Base2::fn()
– Can use a using-clause:
using Base1::fn(); or using Base2::fn();
• What about replicating the base classes?
– Eliminates ambiguities related to which base is being
referenced (but may duplicate code)
– If you do this you should write an overriding function
in the derived class
• Making Base0 a virtual base class
– Base1 and Base2 say : virtual public Base0
– Only one copy of base object is constructed
– Initialization of virtual base class is responsibility of
the most derived object
– Only time you’d initialize above immediate parent
Base3::Base3 (int i)
: Base0 (i), Base2(i), Base3(i) {}
Base0
void fn();
Base1
Base2
Base3
http://ebooks.edhole.com
CSE 332: C++ classes
For Next Time• Topic: C++ memory models and memory
management idioms
– auto_ptr
– singleton
– guard
– reference counting
– copy-on-write
• Assigned Readings
– pages 393-420
– pages 873-877
http://ebooks.edhole.com
CSE 332: C++ classes
Free Ebooks Download
Mba Ebooks
By Edhole
Mba ebooks
Free ebooks download
http://ebooks.edhole.com

Mais conteúdo relacionado

Mais de Edhole.com

Chartered accountant in dwarka
Chartered accountant in dwarkaChartered accountant in dwarka
Chartered accountant in dwarkaEdhole.com
 
Ca firm in dwarka
Ca firm in dwarkaCa firm in dwarka
Ca firm in dwarkaEdhole.com
 
Website development company surat
Website development company suratWebsite development company surat
Website development company suratEdhole.com
 
Website designing company in surat
Website designing company in suratWebsite designing company in surat
Website designing company in suratEdhole.com
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in indiaEdhole.com
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhiEdhole.com
 
Website designing company in mumbai
Website designing company in mumbaiWebsite designing company in mumbai
Website designing company in mumbaiEdhole.com
 
Website development company surat
Website development company suratWebsite development company surat
Website development company suratEdhole.com
 
Website desinging company in surat
Website desinging company in suratWebsite desinging company in surat
Website desinging company in suratEdhole.com
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in indiaEdhole.com
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhiEdhole.com
 
Video lectures for mba
Video lectures for mbaVideo lectures for mba
Video lectures for mbaEdhole.com
 
Video lecture for b.tech
Video lecture for b.techVideo lecture for b.tech
Video lecture for b.techEdhole.com
 
Video lecture for bca
Video lecture for bcaVideo lecture for bca
Video lecture for bcaEdhole.com
 
Mba top schools in india
Mba top schools in indiaMba top schools in india
Mba top schools in indiaEdhole.com
 
B.tech top schools in india
B.tech top schools in indiaB.tech top schools in india
B.tech top schools in indiaEdhole.com
 
Top schools in india
Top schools in indiaTop schools in india
Top schools in indiaEdhole.com
 
Mba admissions in india
Mba admissions in indiaMba admissions in india
Mba admissions in indiaEdhole.com
 

Mais de Edhole.com (20)

Ca in patna
Ca in patnaCa in patna
Ca in patna
 
Chartered accountant in dwarka
Chartered accountant in dwarkaChartered accountant in dwarka
Chartered accountant in dwarka
 
Ca firm in dwarka
Ca firm in dwarkaCa firm in dwarka
Ca firm in dwarka
 
Ca in dwarka
Ca in dwarkaCa in dwarka
Ca in dwarka
 
Website development company surat
Website development company suratWebsite development company surat
Website development company surat
 
Website designing company in surat
Website designing company in suratWebsite designing company in surat
Website designing company in surat
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in india
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhi
 
Website designing company in mumbai
Website designing company in mumbaiWebsite designing company in mumbai
Website designing company in mumbai
 
Website development company surat
Website development company suratWebsite development company surat
Website development company surat
 
Website desinging company in surat
Website desinging company in suratWebsite desinging company in surat
Website desinging company in surat
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in india
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhi
 
Video lectures for mba
Video lectures for mbaVideo lectures for mba
Video lectures for mba
 
Video lecture for b.tech
Video lecture for b.techVideo lecture for b.tech
Video lecture for b.tech
 
Video lecture for bca
Video lecture for bcaVideo lecture for bca
Video lecture for bca
 
Mba top schools in india
Mba top schools in indiaMba top schools in india
Mba top schools in india
 
B.tech top schools in india
B.tech top schools in indiaB.tech top schools in india
B.tech top schools in india
 
Top schools in india
Top schools in indiaTop schools in india
Top schools in india
 
Mba admissions in india
Mba admissions in indiaMba admissions in india
Mba admissions in india
 

Último

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Último (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 

Free Ebooks Download ! Edhole

  • 1. CSE 332: C++ classes Free Ebooks Download Mba Ebooks By Edhole Mba ebooks Free ebooks download http://ebooks.edhole.com
  • 2. CSE 332: C++ classes Review of Types in C++ • Two main kinds of types in C++ – native and user-defined • User-defined types – Classes, structs, unions, enumerations declared by code – includes those provided by C++ libraries, like bad_alloc • Native types – Types “built in” to the C++ language itself: int, long, float, … • Type definitions – A typedef creates new type names for other types – We’ll use this idea a lot when we talk about templates http://ebooks.edhole.com
  • 3. CSE 332: C++ classes Overview of C++ Polymorphism Poly (= many) + morphism (= forms) • Inheritance creates sub-types • Only applies to user-defined classes (and structs) • A publicly derived class is-a subtype of its base class – Object b has only one type • Instance of Base only – Object d has two types • Instance of both Base, Derived class Base { public: Base (int i); Base (const Base & b); virtual ~Base (); void operator= (const Base & b); void i (int i); int i () const; private: int i_; }; class Derived : public Base { public: Derived (int i, int j, int k); Derived (const Derived & d); virtual ~Derived (); void operator= (const Derived & d); void j (int j); int j () const; void k (int k); int k () const; private: int j_; int k_; }; int main (int, char *[]) { Base b (1); Derived d(2, 3, 4); } http://ebooks.edhole.com
  • 4. CSE 332: C++ classes Aliasing and Substitution with Inheritance • Aliasing with inheritance – Pointer dptr can only point to d • Can’t do dptr = b; dptr->j (); – Pointer bptr can point to b or d • But can only call Base functions • Can’t say bptr->j (); • Liskov Substitution Principle – if S is a subtype of T, then can use an S where a T is needed • But not the other way around • bptr = &d; ok, but not dptr = &b; class Base { public: Base (int i); Base (const Base & b); virtual ~Base (); void operator= (const Base & b); void i (int i); int i () const; private: int i_; }; class Derived : public Base { public: Derived (int i, int j, int k); Derived (const Derived & d); virtual ~Derived (); void operator= (const Derived & d); void j (int j); int j () const; void k (int k); int k () const; private: int j_; int k_; }; int main (int, char *[]) { Base b (1); Derived d(2, 3, 4); Base *bptr = d; Derived *dptr = d; } http://ebooks.edhole.com
  • 5. CSE 332: C++ classes Static vs. Dynamic Types • Pointers have static types – References have them too… – Type with which it was declared – Most general type it can alias • Base is more general than Derived – Static type of bptr is Base* – Static type of dptr is Derived* • What’s pointed to / referenced has a dynamic type – Type of object currently aliased • Dynamic type of *bptr can be either Base or Derived • Dynamic type of *dptr is Derived – Expands if classes inherit from Derived – May change if pointer reassigned – May change if reference parameter is passed a different object class Base { public: Base (int i); Base (const Base & b); virtual ~Base (); void operator= (const Base & b); void i (int i); int i () const; private: int i_; }; class Derived : public Base { public: Derived (int i, int j, int k); Derived (const Derived & d); virtual ~Derived (); void operator= (const Derived & d); void j (int j); int j () const; void k (int k); int k () const; private: int j_; int k_; }; int main (int, char *[]) { Base b (1); Derived d(2, 3, 4); Base * bptr = d; Derived * dptr = d; } http://ebooks.edhole.com
  • 6. CSE 332: C++ classes Declaring Virtual Member Functions class A { public: virtual foo () {cout<<"A";} }; class B : public A { public: // overrides A::foo definition virtual foo() {cout<<"B";} }; int main (int, char *[]) { A *aptr = new B; // prints "B" : would print // "A" instead if non-virtual aptr->foo (); delete aptr; return 0; }; • Enables polymorphism using pointers and references in C++ • Class declares a member function to be virtual • Derived class overrides the base class’s definition of the function – Good style to say it’s virtual at re- declaration, but it’s virtual anyway – Overriding only happens when signatures are the same – Otherwise it just Overloads the function or operator name with a different signature • Ensures function definition is resolved by dynamic type – E.g., that destructors farther down the hierarchy get called • Non-virtual functions are resolved by static type http://ebooks.edhole.com
  • 7. CSE 332: C++ classes Calling Virtual Member Functions class A { public: void x() {cout<<"A:x";}; virtual void y() {cout<<"A:y";}; }; class B : public A { public: void x() {cout<<"B:x";}; virtual void y() {cout<<"B:y";}; }; int main () { B b; A *ap = &b; B *bp = &b; b.x (); // prints "B:x" b.y (); // prints "B:y" bp->x (); // prints "B:x" bp->y (); // prints "B:y" ap->x (); // prints "A:x" ap->y (); // prints "B:y" return 0; }; • Only matter with pointer or reference – Calls on object itself resolved statically – E.g., b.y(); • Look first at pointer/reference type – If non-virtual, resolve statically • E.g., ap->x(); – If virtual, resolve dynamically • E.g., ap->y(); • Note that virtual keyword need not be repeated in derived classes – But it’s good style to do so • Caller can force static resolution of a virtual function via scope operator – E.g., ap->A::y(); prints “A:y” – E.g., ap->B::y(); prints “B:y” – But should use RTTI to be type safe http://ebooks.edhole.com
  • 8. CSE 332: C++ classes Virtual Destructors and the Class Slicing Problem class A { public: A () {cout<<" A";} virtual ~A () {cout<<" ~A";} }; class B : public A { public: B () :A() {cout<<" B";} virtual ~B() {cout<<" ~B";} }; int main (int, char *[]) { // prints "A B" A *ap = new B; // prints "~B ~A" : would only // print "~A" if non-virtual delete ap; return 0; }; • Derived class destructor called before base class destructor • But, need to watch out for static versus dynamic type differences • Making destructor virtual – ensures chain of destructor calls starts at dynamic type and moves up – Otherwise would start at static type (would “slice off” calls to destructors of more derived classes) • “Class slicing problem” can also occur with pass/catch by value – Only static type gets copied – Another reason to always catch/pass by reference (using const if needed) http://ebooks.edhole.com
  • 9. CSE 332: C++ classes Declaring Pure Virtual Functions class A { public: virtual void x() = 0; virtual void y() = 0; }; class B : public A { public: virtual void x(); virtual void y() = 0; }; class C : public B { public: virtual void y(); }; int main () { A * ap = new C; ap->x (); ap->y (); delete ap; return 0; }; • A is an Abstract Base Class – Similar to an interface in Java – Declares pure virtual functions (=0) • Derived classes override those pure virtual member functions – B overrides x(), C overrides y() – Good style (but optional) to re-declare pure virtual functions that are not yet overridden • Can’t instantiate class with declared or inherited pure virtual functions – A and B are abstract, but C is concrete – Can create instances of C, but not B or A • Can still have a pointer to an abstract class type – Very useful for polymorphism http://ebooks.edhole.com
  • 10. CSE 332: C++ classes Tips on Using Polymorphism • Push common code/variables up into base classes • Use public inheritance for polymorphism – Use private/protected inheritance for encapsulation • Polymorphism depends on dynamic typing – Use a base-class pointer or reference if you want polymorphism – Use virtual member functions for dynamic overriding • Use abstract base classes to declare interfaces • Even though you don’t have to, re-label each virtual (and pure virtual) function in derived classes http://ebooks.edhole.com
  • 11. CSE 332: C++ classes Type Casting in C++• Casting up the inheritance type hierarchy, size conversion – Converts between related types – Note that static_cast does not examine the dynamic type – Widens the static type to be more general, farther from dynamic type B* p = static_cast<B*>(d); // d is D * char c = static_cast<char>(i); // -128 <= i <= 127 • Casting down the inheritance type hierarchy – Narrows the static type to be less general, closer to dynamic type D* p = dynamic_cast<D*>(b); // b is B * • Casting away const protections – Tells compiler: trust me, I know it’s ok to modify this variable T* p = const_cast<T*>(q); // q is const T * • Reinterpretation of what is being pointed to – Tells compiler: trust me, I really really know what I’m doing T* p = reinterpret_cast<T*>(v); // v is void* http://ebooks.edhole.com
  • 12. CSE 332: C++ classes Run-Time Type Information (RTTI)• Using dynamic_cast<> operator template – Examples dynamic_cast<T*>(p) dynamic_cast<T&>(r) – If p points to (sub-)type T then address is returned, else 0 – If r references (sub-)type T then a reference to T is returned • otherwise an exception is thrown • Using typeid() operator and type_info class – Only use when appropriate (see Prata 5th ed. pp. 847-848) – Need to include <typeinfo> header file to use them – returns type information (including a name string) • if polymorphic then the dynamic type is returned • otherwise the static type is returned. http://ebooks.edhole.com
  • 13. CSE 332: C++ classes Basic Ideas of Multiple inheritance • Override resolution is not applied across class scope boundaries • So if two different base classes define a function with the same signature, you have an ambiguity (compiler cannot figure it out) – Can be explicit, Base1::fn() or Base2::fn() – Can use a using-clause: using Base1::fn(); or using Base2::fn(); • What about replicating the base classes? – Eliminates ambiguities related to which base is being referenced (but may duplicate code) – If you do this you should write an overriding function in the derived class • Making Base0 a virtual base class – Base1 and Base2 say : virtual public Base0 – Only one copy of base object is constructed – Initialization of virtual base class is responsibility of the most derived object – Only time you’d initialize above immediate parent Base3::Base3 (int i) : Base0 (i), Base2(i), Base3(i) {} Base0 void fn(); Base1 Base2 Base3 http://ebooks.edhole.com
  • 14. CSE 332: C++ classes For Next Time• Topic: C++ memory models and memory management idioms – auto_ptr – singleton – guard – reference counting – copy-on-write • Assigned Readings – pages 393-420 – pages 873-877 http://ebooks.edhole.com
  • 15. CSE 332: C++ classes Free Ebooks Download Mba Ebooks By Edhole Mba ebooks Free ebooks download http://ebooks.edhole.com