Download Inheritance - Algorithms and Abstract Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!
CPSC 223
Algorithms & Data Abstract Structures
Lecture 2:
Inheritance, const, and
basic operator overloading
Today …
• Homework 1 topics
- Inheritance
- Various uses of const
- Basic operator overloading
- operator==
- operator<
- etc.
- The “this” keyword
- Assignment operator and copy constructor
• Readings
- Ch. 8: 8.1– 8.4, 8. CPSC 223, Fall 2010 2 We won’t be able to cover everything today So, the due date for HW 1 is postponed to next Thursday (9/9/10)
What do we mean by “ Inheritance ”?
Inheritance is a relationship where one class derives the
behavior and/or structure of another class
- A major feature of object-oriented programming languages
- Useful for organizing and modularizing code
- Can enable reuse of existing code
- New classes subclass (inherit) from existing classes CPSC 223, Fall 2010 3
Basic Terminology
- A child class directly inherits from a parent class
- A derived class inherits from a base class
- Derived classes inherit data and functions ( members )
- single inheritance (a class directly inherits from one class)
- multiple inheritance (we won’t talk about this … its tricky)
- Inheritance forms a class hierarchy with single inheritance …
- the hierarchy induces a tree structure
- there is always one root class
- a leaf class has no child classes CPSC 223, Fall 2010 4
An Example: C++ Single Inheritance
CPSC 223, Fall 2010 7 // base class class Account { public: Account(); double getBalance(); private: double balance; }; Account // derived class class Checking : public Account { public: Checking(); double getMonthlyFees(); private: double monthlyFees; }; Checking // derived class class Savings : public Account { public: Savings(); double getMonthlyInterest(); private: double monthlyInterest; }; Savings
An Example: C++ Single Inheritance
Subclass objects contain all members of their superclasses
… and can be used wherever the superclass objects can
CPSC 223, Fall 2010 8 Account Checking Savings Account::getBalance() balance = 1000. Savings::getMonthlyInterest() monthyInterest = 1. Savings Account Object Account::getBalance() balance = 2109. Checking::getMonthlyFees() monthyFees = 10. Checking Account Object
Single Inheritance
Not all inherited members may be accessible
- Members functions and variables have their own visibility Members are either public, protected, or private:
- A public member is always visible and accessible
- A protected member is only visible in inherited classes
- A private member is only visible in their defining class CPSC 223, Fall 2010 9
Single Inheritance
In the case of private variables and functions …
- Memory is still allocated in derived classes
- E.g., balance is allocated for each SavingsAccount object
- Can only be accessed from the base class
- Enables information hiding and modularity
- A base class can change without affecting derived classes CPSC 223, Fall 2010 10 Account::getBalance() balance = 1000. Savings::getMonthlyInterest() monthyInterest = 1. Savings Account Object
Examples …
class Sphere { public: int radius; } int main() { Sphere1 s; s.radius = 10; } CPSC 223, Fall 2010 13 Is this statement legal??? YES! The radius member is declared public This means clients can access it
Examples …
class Sphere { public: int radius; } class Ball1 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 14 A child class of Sphere Uses public inheritance ( also a “client” )
Examples …
class Sphere { public: int radius; } class Ball1 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 15 Is this statement legal???
Examples …
class Sphere { public: int radius; } class Ball1 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 16 Is this statement legal??? YES! radius is declared public Here we inherit public access to it Do you see any design issues here?
Examples …
class Sphere { private: int radius; } int main() { Sphere2 s; s.radius = 10; } CPSC 223, Fall 2010 19 Is this statement legal??? NO! The radius member is declared private This means clients cannot access it
Examples …
class Sphere { private: int radius; } class Ball2 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 20 A child class of Sphere
Examples …
class Sphere { private: int radius; } class Ball2 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 21 Is this statement legal???
Examples …
class Sphere { private: int radius; } class Ball2 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } CPSC 223, Fall 2010 22 Is this statement legal??? NO! radius is declared private It is inherited, but not visible What should we do?
Examples …
class Sphere { protected: int radius; } CPSC 223, Fall 2010 25 Opt. 2: Use protected visibility class Ball1 : public Sphere { public: int getSize() { if(radius < 4) return 3; ... } } int main() { Sphere3 s; s.radius = 10; } Is this legal? NO! radius is declared protected only visible in subclasses
Single Inheritance
Using getters and setters for private data
- can be tricky to hide internal data sufficiently
- … and we must not expose internal structures via public methods (see: “good” software design)
- Overall though the preferred approach
Protected members allow derived classes to access base
class members, while still restricting client access
- this could mean making data members protected (simpler)
- or providing only protected member functions for getting and setting private data (sometimes safer, but more work) CPSC 223, Fall 2010 26
Constructors and Inheritance
The constructor of a base class
- is always invoked before a derived class constructor
- we can assume that in the constructor of the derived class the base class members have been initialized
- the constructor of the derived class is called last, after all inherited classes in the hierarchy (in order)
By default
- the base class constructor is implicitly invoked by the derived class constructor
- we can also explicitly call a base class constructor CPSC 223, Fall 2010 27
Constructors and Inheritance
A"er the client says: Account a; What is printed? account constructor A"er the client says: Checking c; What is printed? account constructor checking constructor CPSC 223, Fall 2010 28 // derived class class Checking : public Account { public: Checking(); float getMonthlyFees(); private: float monthlyFees; }; Account::Account() : balance(0) { cout << “account constructor\n”; } // base class class Account { public: Account(); float getBalance(); private: float balance; }; Checking::Checking() : monthlyFees(5) { cout << “checking constructor\n”; }
Constructors and Inheritance
If a base class constructor is not in the initialization list
- The default constructor of the base class is called
- If there is no default constructor for the base class, then we get a compile error Recall : a default constructor has no arguments … or else every argument has a default value CPSC 223, Fall 2010 31
Subtype Polymorphism
- Subclass objects can be used when superclass objects
are expected …
- This is referred to as “ subtype polymorphism ”
- This doesn’t work in the other direction!
- This is an example of code reuse …
- Subclassing is one form of reuse
- Polymorphism is another CPSC 223, Fall 2010 32 Account::getBalance() balance = 1000. Savings::getMonthlyInterest() monthyInterest = 1. Savings Account Object Account::getBalance() balance = 2109. Checking::getMonthlyFees() monthyFees = 10. Checking Account Object Both objects have an “account” part
Subtype Polymorphism
- A simple example: class Bank { public: void addAccount(Account a); ... }; ... Account a; Bank b; b.addAccount(a); Savings s; b.addAccount(s); CPSC 223, Fall 2010 33 s has an Account “part”
Is this OK?
Yes!
Subtype Polymorphism
- A simple example: class Bank { public: void addSavings(Savings s); ... }; ... Savings s; Bank b; b.addSavings(s); Account a; b.addSavings(a); CPSC 223, Fall 2010 34 a doesn’t have a Savings “part”
Is this OK?
No!
The various uses of const
A simple class for managing stock shares …
class Stock { public: Stock(); Stock(string aCompany, int theShares); int getShares(); string getCompany(); void setShares(int newShares); Stock worthMore(Stock s); private: string company; int shares; }; CPSC 223, Fall 2010 37
The various uses of const
Lets say we want to do the following
const Stock s1("GOOG", 1000); s1.setShares(900); // sell shares
- What will happen when we compile? Compile Error! "error: passing 'const Stock' as 'this' argument of 'void Stock::setShares(int)' discards qualifiers"
- Why is the compiler complaining? … Because s1 is a constant, and we are modifying it! CPSC 223, Fall 2010 38 The compiler is our friend! It is saving us from introducing bugs later
The various uses of const
Lets say now we want to do the following
const Stock s1("GOOG", 1000); cout << s1.getShares() << endl; // check shares
- What will happen when we compile? Compile Error! "error: passing 'const Stock' as 'this' argument of 'void Stock::getShares()' discards qualifiers"
- Why is the compiler complaining now? … The compiler can’t tell we aren’t modifying s CPSC 223, Fall 2010 39 The compiler is our friend! But we have to help it…
The various uses of const
We need to tell the compiler getShares() won’t
change the invoking object
int getShares() const;
- Now when we compile const Stock s1("GOOG", 1000); cout << s1.getShares() << endl; // check shares
- All “getters” should be const functions CPSC 223, Fall 2010 40