c++ classes how to create and use them

97
C++ Classes How to Create and Use Them

Upload: erna

Post on 19-Jan-2016

50 views

Category:

Documents


2 download

DESCRIPTION

C++ Classes How to Create and Use Them. Overview. Terminology File Topology Designing Classes Functions in Classes (methods) Constructor Accessors/Modifiers Miscellaneous The Driver and Object instantiation. Terminology. Now in OO land (Object-Oriented) – Real C++ programming! - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C++ Classes How to Create and Use Them

C++ Classes

How to Create and Use Them

Page 2: C++ Classes How to Create and Use Them

2

Overview

• Terminology• File Topology• Designing Classes• Functions in Classes (methods)

Constructor Accessors/Modifiers Miscellaneous

• The Driver and Object instantiation

Page 3: C++ Classes How to Create and Use Them

3

Terminology

• Now in OO land (Object-Oriented) – Real C++ programming!• A class is just a combination of data and functions• It creates a new data type!• A class is a generic description• Create several instances of this class (objects)• Each instance has their own variables (they don’t share)• Functions are now called methods or behaviors (and rarely member

functions)

Page 4: C++ Classes How to Create and Use Them

4

File Topology(separate files for everything)

Descriptionof a cat

Descriptionof a dog

Descriptionof a person

Cat.cpp Dog.cpp

Person.cpp

Driver.cpp

This is where we createinstances of dog and catsand then tell them whatto do. It’s the controlling

algorithm

Page 5: C++ Classes How to Create and Use Them

5

A couple of rules

Classes usually begin with an upper-case letterThe name of the file that you put the class in should be called the <class name>.cpp

Especially if it’s a public class (later)

Example: If we are creating a dog, we should name the class

Dog and put it into a file named Dog.cpp Remember, C++ is case-sensitive!

Page 6: C++ Classes How to Create and Use Them

6

The Smallest Class

Has template:class <class name> {};

Example: you’re told to create class X

Solution:class X {};

Remember, this should go in a separate file named X.cpp (not x.cpp)

Page 7: C++ Classes How to Create and Use Them

7

A “real life” example

The CDog Attributes (characteristics)

rabid or not rabid (bool)weight (int or float)name (char [ ])

Behaviorsgrowleat

Page 8: C++ Classes How to Create and Use Them

8

Step 1: The Skeleton

class CDog {// attributes will go here – name, weight, rabid// behaviors will go here – growl, eat

};

Page 9: C++ Classes How to Create and Use Them

9

Step 2: The attributes(we’ll discuss public later)

class CDog { public:

boolean rabid;int weight;char name[255];

// Behaviors go here};

Page 10: C++ Classes How to Create and Use Them

10

Step 3: The Constructor

This is a special function Used to give initial values to ALL attributes Is activated when someone creates a new instance

of the class

The name of this function MUST be the same name as the class

Page 11: C++ Classes How to Create and Use Them

11

Step 3: Designing the Constructor

Constructors will vary, depending on designAsk questions:

Are all CDogs born either rabid or non-rabid?(yes – they are all born non-rabid)

Are all CDogs born with the same weight?(no – they are born with different weights)

Are all CDogs born with the same name?(no – they all have different names)

If ever “no”, then you need information passed in as parameters.

Page 12: C++ Classes How to Create and Use Them

12

Step 3: The Constructor

class CDog {

public:

boolean rabidOrNot;

int weight;

char name [255];

// Constructor

CDog::CDog (int x, String y) {

rabid = false;

weight = x;

strcpy (name, y);

}

// Behaviors go here

};

Notice that every

CDog we createwill be born

non-rabid. Theweight and

name will depend on

thevalues of theparameters

Page 13: C++ Classes How to Create and Use Them

13

The Driver

We’re talking about a whole new file!

The Driver contains main()

It’s the controlling algorithm

Steps: Type in the skeleton Create a couple of instances of classes Start telling them what to do

Page 14: C++ Classes How to Create and Use Them

14

Step 1: Type in the Skeleton

#include <iostream.h>

void main ( ) {// Create your instances here!

}

Page 15: C++ Classes How to Create and Use Them

15

Step 2: Declare A CDog Pointer

#include <iostream.h>

void main ( ) {CDog* c1;

}

// null means “dead” null

c1

Page 16: C++ Classes How to Create and Use Them

16

The new operator

new Brings instances “to life” Calls the class’ constructor Opens up enough space in memory to fit an instance of

that class

Format:<class>* <var_name>;<var_name> = new <class> (<parameters>);

Page 17: C++ Classes How to Create and Use Them

17

Step 3: Bring c1 to Life

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);

}

new calls the CDog’s constructorCDog::CDog (int x, char y[ ]) {

rabid = false;weight = x;strcpy (name, y);

}

null

c1

Page 18: C++ Classes How to Create and Use Them

18

Opens Space

new calls the CDog’s constructorCDog::CDog (int x, char y[ ]) {

rabid = false;weight = x; strcpy (name, y);

}

null

c1

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);

}

Page 19: C++ Classes How to Create and Use Them

19

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);

}

Data Passing

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

null

c1

// This is over in CDog.cpp

Page 20: C++ Classes How to Create and Use Them

20

Data Passing

null

c1

rabid:false

weight:14

name:”bob”

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

// This is over in CDog.cpp

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);

}

Page 21: C++ Classes How to Create and Use Them

21

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);

}

Declare a 2nd CDog

null

c1

rabid:false

weight:14

name:”bob”

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

// This is over in CDog.cpp

Page 22: C++ Classes How to Create and Use Them

22

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);

}

Opens Space

null

c1

rabid:false

weight:14

name:”bob”

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

// This is over in CDog.cppc2

Page 23: C++ Classes How to Create and Use Them

23

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);

}

Data Passing

null

c1

rabid:false

weight:14

name:”bob”

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

// This is over in CDog.cpp

c2

Page 24: C++ Classes How to Create and Use Them

24

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);

}

Copy Values to Memory

null

c1

rabid:false

weight:14

name:”bob”

CDog::CDog (int x, char y[ ]) {rabid = false;weight = x; strcpy (name, y);

}

// This is over in CDog.cpp

c2rabid:false

weight:7

name:”Ethel”

Page 25: C++ Classes How to Create and Use Them

25

Back to CDog

class CDog {

public:

boolean rabidOrNot;

int weight;

char name [255];

// Constructor

CDog::CDog (int x, char y[ ]) {

rabid = false;

weight = x;

strcpy (name, y);

}

// Behaviors we still need to eat and growl

};

Page 26: C++ Classes How to Create and Use Them

26

Miscellaneous Methods

Follow the pattern

void CDog::eat ( ) {cout << name << “ is now eating” << endl;weight++;

}

void CDog::growl ( ) {cout << “Grrrr” << endl;

}

Page 27: C++ Classes How to Create and Use Them

27

Add Methodsclass CDog {

public:boolean rabidOrNot;int weight;char name [255];// ConstructorCDog::CDog (int x, char y[ ]) {

rabid = false;weight = x;strcpy (name, y);

}void CDog::eat ( ) {

cout << name << “ is now eating” << endl;weight++;

}

void CDog::growl ( ) {cout << “Grrrr” << endl;

}};

Page 28: C++ Classes How to Create and Use Them

28

The “.” and “->” operators

“Dot” operator used for non-pointers to:Get to an instances attributesGet to an instances methodsBasically get inside the instance

Format:<instance>.<attribute or method>

Arrow operator used for pointers

Format:<instance> -> <attribute or method>

Page 29: C++ Classes How to Create and Use Them

29

Using the “.” and “->” Operators

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);c2.bark( );c1->growl( );

}

Page 30: C++ Classes How to Create and Use Them

30

Accessors and Modifiers

AccessorsA method that returns the value of an attributeWill have non-void return typeHas return statement inside

ModifiersA method that changes the value of an attributeChange is based off of a parameter valueHas a void return type

Have one accessor and one modifier per attribute

Page 31: C++ Classes How to Create and Use Them

31

Accessors and Modifiers

Accessor for the rabid attributebool CDog::getRabid ( ) {

return rabid;}

Modifier for the rabid attributevoid CDog::setRabid (bool myBoolean) {

rabid = myBoolean;}

Put these inside of the CDog class

Page 32: C++ Classes How to Create and Use Them

32

Using accessors and modifiers

#include <iostream.h>

void main ( ) {CDog* c1;c1 = new CDog (14, “Bob”);CDog c2 (7, “Ethel”);c1->setRabid (1);// prints 1 for truecout << c1->getRabid( ) << endl;

}

Page 33: C++ Classes How to Create and Use Them

33

Make a Separate Header File(for the generic description)

class CDog {public:

int weight;bool rabid;char name [ ];CDog (int x, char y[ ]);bool getRabid ( );void setRabid (bool x);char [ ] getName ( );void setName (char z[ ]);int getWeight ( );void setWeight (int x);void bark( );void growl( );

};

Page 34: C++ Classes How to Create and Use Them

34

Our Final CDog.cpp

#include <iostream.h> #include <CDog.h>

// ConstructorCDog::CDog (int x, char y[ ]) {

rabid = false;weight = x;strcpy(name, y);

}void CDog::eat ( ) {

cout << name << “ is eating”;}void CDog::growl ( ) {

cout << “Grrrr”;}

bool CDog::getRabid ( ) { return rabid;}void CDog::setRabid (bool x) { rabid = x;}int CDog::getWeight ( ) { return weight;}void CDog::setWeight (int y) { weight = y;}char[ ] CDog::getName ( ) { return name;}void setName (char z[ ]) { name = z;}

Cdog.hCdog.cpp

Page 35: C++ Classes How to Create and Use Them

35

Summary of Class Concepts

A class is a generic description which may have many instances

When creating classes1. Sketch the skeleton2. Fill in the attributes3. Make the constructor4. Make the accessors/modifiers/miscellaneous

Classes go in separate files

The “.” and “->” operators tell the instances which method to run

Page 36: C++ Classes How to Create and Use Them

Inheritance and Objects

Page 37: C++ Classes How to Create and Use Them

37

Inheritance

• Inheritance allows one class to take on the properties of another

• Superclass-subclass relationship• Sometimes called parent-child relationship• Use the : <class name> to express this relationship• Subclass will “inherit” certain attributes and methods• Benefit: good design, reuse of code

Page 38: C++ Classes How to Create and Use Them

38

Class Hierarchy

Mammal

Land-Mammal

int weight

int numLegs

Dogboolean rabid

Chihuahua

giveBirth( )

SheepDog

Question: how manyattributes does Doghave?

Page 39: C++ Classes How to Create and Use Them

39

Things to Note

• Land-Mammal is a superclass to Dog, but a subclass to Mammal

• Dog has three attributes

weight, numLegs and rabid Two from inheritance, one it declared itself

Page 40: C++ Classes How to Create and Use Them

40

An Example(CDog.h – just review)

#include <iostream.h>#include <string.h>

class CDog {public:

int weight;char name [255];bool rabid;CDog(int x);void growl( );

};

Page 41: C++ Classes How to Create and Use Them

41

CDog.cpp(still review)

#include "CDog.h"

CDog::CDog(int x) {

weight = x;

rabid = false;

strcpy (name, "bob");

cout << "A CDog was made" << endl;

}

void CDog::growl( ) {

cout << “Grrrr" << endl;

}

Page 42: C++ Classes How to Create and Use Them

42

Poodle: The evil subclass

• Since a poodle is a type of CDog, how can we make class Poodle without re-writing a lot of code?

• Does a poodle necessarily growl the same way a CDog growls?

Page 43: C++ Classes How to Create and Use Them

43

Class Poodle(both header and cpp file)

#include "CDog.h“

class CPoodle:public CDog {public:

CPoodle(int x);};

CPoodle::CPoodle(int x) : CDog (x){cout << "A poodle was made" << endl;

}

Here’s where we inheritfrom CDog

Page 44: C++ Classes How to Create and Use Them

44

What’s going on here?

CPoodle::CPoodle(int x) : CDog (x){cout << "A poodle was made" << endl;

}

Normal ConstructorStuff

The super class’s constructoris always called*; in this case, we call the constructor which takes an int.

*Note: if you don’t explicitly call the super constructor, it looks fora no-arguments constructor in the super class (which we don’t have)

Page 45: C++ Classes How to Create and Use Them

45

What just happened?

• We created a poodle that has all the attributes and all the methods that a CDog has

Problem:CPoodle* myPoodle = new CPoodle (3);myPoodle->growl ( ); // prints GRRRR

Poodles don’t go GRRRR, they “yip”

Page 46: C++ Classes How to Create and Use Them

46

Overriding methods

• When you override a method, you give new functionality to the class

• In this case, we need to override the growl method for the poodle

• Simply redefine the method

Page 47: C++ Classes How to Create and Use Them

47

A Better Poodle(if there is such a thing)

#include "CDog.h"

class CPoodle:public CDog {public:

CPoodle(int x);void growl();

};

CPoodle::CPoodle(int x) : CDog (x){cout << "A poodle was made" << endl;

}

void CPoodle::growl( ) {cout << "Yip!" << endl;

}

Now when we tell the poodle to growl, it will print “Yip”

Page 48: C++ Classes How to Create and Use Them

48

Access Keywords: public, private(and protected)

• We can restrict access to attributes and methods inside a class using public and private

public – means “everyone can see it”

private – means “only that class can see it”

Page 49: C++ Classes How to Create and Use Them

49

Bad Example(won’t compile)

class X {private:

int myInt;// Constructor…

}

void main ( ) { X* myX = new X ( ); myX->myInt = 42; // Not Allowed!}

Page 50: C++ Classes How to Create and Use Them

50

Working Example

class X {public:

int myInt;// Constructor…

}

void main ( ) { X* myX = new X ( ); myX->myInt = 42; // Allowed!}

Page 51: C++ Classes How to Create and Use Them

51

Why private?

• Security: Keeps other classes from changing attributes at random

• Design: forces other classes to use accessors and modifiers to get to the information

• Encapsulation: the class is complete to itself

Page 52: C++ Classes How to Create and Use Them

52

Memory Trace

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;null

Page 53: C++ Classes How to Create and Use Them

53

Memory Trace(declare the variables; they are dead)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;null

d1 d2

Page 54: C++ Classes How to Create and Use Them

54

Memory Trace(bring d1 to life)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;// Remember, new opens up// space and calls the class// constructor

null

d1 d2

Page 55: C++ Classes How to Create and Use Them

55

Memory Trace(bring d1 to life)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;// Remember, new opens up// space and calls the class// constructor

null

d1 d2

Page 56: C++ Classes How to Create and Use Them

56

Memory Trace(bring d1 to life)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;// Remember, new opens up// space and calls the class// constructor

null

d1 d2

rabid=false

weight=5

name=“bob”

Page 57: C++ Classes How to Create and Use Them

57

Memory Trace(bring d2 to life)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;

// Remember, new opens up// space and calls the class// constructor

null

d1 d2

rabid=false

weight=5

name=“bob”

Page 58: C++ Classes How to Create and Use Them

58

Memory Trace(bring d2 to life)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;// Remember, new opens up// space and calls the class// constructor

null

d1 d2

rabid=false

weight=5

name=“bob”

rabid=false

weight=5

name=“bob”

Page 59: C++ Classes How to Create and Use Them

59

Memory Trace(comparison)

d1 and d2 do NOT occupythe same space in memory,so they are NOT ==

Example:d1 == d2evaluates to false

null

d1 d2

rabid=false

weight=5

name=“bob”

rabid=false

weight=5

name=“bob”

Page 60: C++ Classes How to Create and Use Them

60

Memory Trace(have d1 point to d2)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;null

d1 d2

rabid=false

weight=5

name=“bob”

rabid=false

weight=5

name=“bob”

Page 61: C++ Classes How to Create and Use Them

61

Memory Trace(have j1 point to j2)

Dog *d1, *d2;d1 = new Dog (5, “bob”);d2 = new Dog (5, “bob”);

d1 = d2;null

d1 d2

rabid=false

weight=5

name=“bob”

rabid=false

weight=5

name=“bob”

Page 62: C++ Classes How to Create and Use Them

62

Memory Trace(have j1 point to j2)

Now, d1 and d2 are ==

But no one is pointing to this

Because no one is pointing to it, we can no longer referenceit. We call this piece of memorygarbage. We killed it!

null

d1 d2

rabid=false

weight=5

name=“bob”

rabid=false

weight=5

name=“bob”

Page 63: C++ Classes How to Create and Use Them

63

Freeing up Memory

• Necessary to get rid of unused memory

• Rule: never set to null

• Use the delete ( ) operator

• Takes in a pointer to an object

• Usage (from previous example): delete (d1);

Page 64: C++ Classes How to Create and Use Them

64

Summary of Inheritance

Benefits of inheritance

Allows for reuse of code Good design

Use :<class name> to achieve this

Override methods in subclasses== tests for same object in memory

Page 65: C++ Classes How to Create and Use Them

C++ Classes

Object Oriented Programming

Page 66: C++ Classes How to Create and Use Them

66

Object Oriented Programming

• Programmer thinks about and defines the attributes and behavior of objects.

• Often the objects are modeled after real-world entities.

• Very different approach than function-based programming (like C).

Page 67: C++ Classes How to Create and Use Them

67

Reasons for OOP

AbstractionEncapsulation

Information hidingInheritance

Polymorphism

Software Engineering Issues

Page 68: C++ Classes How to Create and Use Them

68

Class: Object Types

• A C++ class is an object type.

• When you create the definition of a class you are defining the attributes and behavior of a new type.

• Attributes are data members.• Behavior is defined by methods.

Page 69: C++ Classes How to Create and Use Them

69

Creating an object

• Defining a class does not result in creation of an object.

• Declaring a variable of a class type creates an object. You can have many variables of the same type (class). Instantiation

Page 70: C++ Classes How to Create and Use Them

70

Information Hiding

• The interface to a class is the list of public data members and methods.

• The interface defines the behavior of the class to the outside world (to other classes and functions that may access variables of your class type).

• The implementation of your class doesn't matter outside the class – only the interface.

Page 71: C++ Classes How to Create and Use Them

71

Information Hiding (cont.)

• You can change the implementation and nobody cares! (as long as the interface is the same).

• You can use other peoples classes without fear!

• Wars will end, poverty and illness will be vanquished from earth!

Page 72: C++ Classes How to Create and Use Them

72

Inheritance

• It is possible to extend existing classes without seeing them.

• Add whatever new behavior you want.

Example:

You have a class that represents a "student". Create a new class that is a "good student".

Most of the behavior and attributes are the same, but a few are different – specialized.

Page 73: C++ Classes How to Create and Use Them

73

Polymorphism

• The ability of different objects to respond to the same message in different ways.

Example:

Tell an int to print itself: cout << i;Now tell a double: cout << x;

Now tell the Poly: cout << poly;

Page 74: C++ Classes How to Create and Use Them

74

Private vs. Public

• Public data members and methods can be accessed outside the class directly.

• The public stuff is the interface.

• Private members and methods are for internal use only.

• We will also see Protected.

Page 75: C++ Classes How to Create and Use Them

75

Special Member Functions

Constructors: called when a new object is created (instantiated). can be many constructors, each can take different

arguments.

Destructor: called when an object is eliminated only one, has no arguments.

Page 76: C++ Classes How to Create and Use Them

76

Accessing Data Members

Data members are available within each method (as if they were local variables).

Public data members can be accessed by other functions using the member access operator "." (just like struct).

Page 77: C++ Classes How to Create and Use Them

77

Accessing class methods

Within other class methods, a method can be called just like a function.

Outside the class, public methods can be called only when referencing an object of the class.

Page 78: C++ Classes How to Create and Use Them

78

What happens here?

class foo {int i; // # elements in the arrayint a[10]; // array 10 at most// sum the elementsint sum(void) {

int i, x=0;for (i=0;i<i;i++)

x+=a[i];return(x);

}...

which i is it ?

Page 79: C++ Classes How to Create and Use Them

79

Class Scope Operator ::

You can solve the previous problem using the "::" operator classname::membername.

for (i=0;i<foo::i;i++) x+=a[i];

Page 80: C++ Classes How to Create and Use Them

80

Method names and ::

• Sometimes we put just a prototype for a member function within the class definition.

• The actual definition of the method is outside the class.

• You have to use :: to do this.

Page 81: C++ Classes How to Create and Use Them

81

Example

class foo { ...int sum(void);

};

int foo::sum(void) {int sum=0;

for (int i=0;i<foo::i;i++) {sum += a[i];

} return(sum);}

Page 82: C++ Classes How to Create and Use Them

82

Classes and Files

• The relationship between C++ class definitions and files depends on the compiler.

• In general you can put class definitions anywhere! Visual C++ wants one class per file.

• Most people do this:

class definition is in classname.h any methods defined outside of the class definition

are in classname.cpp

Page 83: C++ Classes How to Create and Use Them

83

static methods

• A static method is a class method that can be called without having an object.

• Must use the :: operator to identify the method.

• Method can't access non-static data members! (they don't exist unless we have an object).

Page 84: C++ Classes How to Create and Use Them

84

Static Data Members

It is possible to have a single variable that is shared by all instances of a class (all the objects).

declare the variable as static.

Data members that are static must be declared and initialize outside of the class.

at global or file scope.

Page 85: C++ Classes How to Create and Use Them

85

Static data member example

class foo {

private:

static int cnt;

public:

foo() {

foocount++;

cout << "there are now " << cnt

<< " foo objects << endl;

}

...

Page 86: C++ Classes How to Create and Use Them

86

A Problem

• Class definitions usually in a ".h" file.

• Can be included by many other ".cpp" files, all part of the same program.

• Can't declare and initialize a static data member in the ".h" file.

Page 87: C++ Classes How to Create and Use Them

87

Solution

class foo{

static int cnt;

};

int foo::cnt=1;

foo.hfoo.cpp

#include "foo.h"

...

#include "foo.h"

...

int main() {

...

f1.cpp

f2.cpp

Page 88: C++ Classes How to Create and Use Them

88

Operator Overloading

• We can define what some C++ operators mean when applied to user defined objects.

• vector example (ivec.h) defines operators:

ostream <<istream >>+ -[]=

== < >

Page 89: C++ Classes How to Create and Use Them

89

Operator Overloading Restrictions

You can't:

define a completely new operator redefine the meaning of operators on built-in data types

(like int or double). Change operator precedence or associatively.

Page 90: C++ Classes How to Create and Use Them

90

Inheritance

• You can create a new class that inherits from an existing class.

• You can add new members and methods.

• You can replace methods.

• The new class is a specialization of the existing class.

Page 91: C++ Classes How to Create and Use Them

91

Terminology

• The existing class is called the base class.

• The new class is called the derived class.

• Objects of the derived class are also objects of the base class.

Page 92: C++ Classes How to Create and Use Them

92

Inheritance Example

• Base class is shape, represents the abstract notion of a shape.

• Derived classes: rectangle circle triangle.

• An object that is a circle is also a shape!

Page 93: C++ Classes How to Create and Use Them

93

Protected Class members/methods

• We've already seen private and public.

• Protected means derived classes have access to data members and methods, but otherwise the members/methods are private.

Page 94: C++ Classes How to Create and Use Them

94

Public/Private/Protected Inheritance

• Usually use public inheritance.

• Private and Protected inheritance change what members/methods can be accessed outside of the class.

Page 95: C++ Classes How to Create and Use Them

95

Polymorphism

• You can treat derived class objects as objects of the base class.

• The problem is that when doing this we don't get access to the derived class methods!

Page 96: C++ Classes How to Create and Use Them

96

Virtual Functions

• A virtual function is a method in a base class that can be overridden by a derived class method.

• For example, we would like each object to "know" which print() method to use.

• Declare the base class print method virtual, and this happens!

Page 97: C++ Classes How to Create and Use Them

97

The End