60
Sahar Mosleh California State University San Marcos Page 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Embed Size (px)

Citation preview

Page 1: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 1

Simple C++

Classes

The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Page 2: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 2

Data

- We’ve seen how to represent single simple pieces of data (simple C++ data types) and simple collections of data (C++ arrays)

- But data - especially “real- world” data - is often more complex than that

- One data item may be best described by several simple data types

– that is, it's heterogeneous - made of many different types of data - rather than homogeneous - made of one type

Page 3: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 3

Simple C++ Classes

- Classes are data types which keep related data items together

- The data items are called members (or fields)

- The members are identified by names

- Each member can be any C++ type (including another class or array)

- The number of members, their names, and their types are defined at compile time

Page 4: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 4

Example of Class Definition

class Person {

public:string name;int age;long SSN; // social security number

};

– the keyword class starts a class definition for the new data type Person– public means all the fields are available for access everywhere (much more on this later)– name, age, SSN are members

Page 5: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 5

Using Classes

- Our previous declaration defines a new type– it doesn’t allocate memory for objects of that type

- We use the class name as the type name:

Person one_person;

- This declaration would create a variable of type Person

Page 6: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 6

Objects

- Variables which are defined to be of some class are often called objects.

- an object of some class is often referred to as an instance of that class

- one_person is an object of type Person, or an instance of the class Person

- you will hear a lot more about objects and "object oriented programming" in the future

Page 7: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 7

Accessing Members

- We can access a specific member using the . (dot or period) operator

Person one_person;one_person.name = “Jim”;one_person.age = 31;one_person.SSN = 653324123;cout << “name is: ” << one_person.name << endl;cout << “His age is: ” << one_person.age << endl;

This would print out:name is JimHis age is 31

- We are using “.” as a member selector- We need to do this whenever we want to do something with part of an object rather than with the object as a whole

Page 8: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 8

A Real-World Example

- classes are very useful for describing real- world entities

- Many things in the real world cannot be described by a single piece of information

- For example, say we want to keep track of a record and CD collection

Page 9: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 9

A Real- World Example

- A class for defining an item in the collection can be done as: class Album {

public:string artist_name;string title;string format;

};

- Notice: upper and lower case for the class names, lower case for the member names

- this is a common style but by no means the only one

Page 10: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 10

- Easily visualized as a fill-in-the blank template

- The template is the class, we get a new set of blanks to fill in for every instance of that class

- We can work with this object as a single data item now. For example, we usually have >1 album, so...

What this Looks like

Albumartist_name : Kevin_Millertitle: The_Beautiful_Worldformat: CD

Page 11: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 11

Using Our Class

- We can create a list for our collection

Album collection[100];

- To add items to our list we'll need an object of type album Album new_entry;

- Note the difference betweencollection[0].artist_name andnew_entry.artist_name[0]

Page 12: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 12

Input and Output

- It’s not possible to input and output classes directly

- even if it were, it’s not a very good idea

- The way classes are stored in memory is system-dependant

- We can’t guarantee what would happen if we could do input or output (I/O) on them

- We have to input or output one member at a time

Page 13: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 13

Input and Output

- For example, to read in an item for the collection:

Album new_entry;char format;cin >> new_entry.artist_name;cin >> new_entry.title;cin >> new_entry.format;

Page 14: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 14

Input and Output

- We can add the new entry to our list as follows:

collection[0] = new_entry;

- Output is done one member at a time

cout << collection[0].artist_name << “ ” << collection[0].title << “ ”

<< collection[0].format << endl;

cout << endl;

Page 15: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 15

What we’ve got now

- We are able to describe complex real- world entities by defining our own data types

- There's a lot more to classes than this, and we'll get the other stuff in a bit

- Like other data structures, classes evolve

- We may decide to add information and expand what a class stores

- The data members of a class can be any type we'd like. They can be simple data type (int, char, float) or complex data type such as arrays or even other classes.

Page 16: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 16

Extending our Class

- let’s say we want to add information about each song on each album.

- We want to store the song titles, and their lengths (in minutes and seconds)

- These are logical units that we want to keep together. The title of the song is obviously nicely suited to a string, but if we want minutes and seconds separate, that's two values that have a connection

- Ideal to use another class for this, Like so

Page 17: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 17

A Time Class

class Length { public:

int minutes;int seconds;

};

- The time is associated with a song, and so is the title - so a song will be yet another object

Page 18: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 18

A Song Class

class Song { public:

string song_title;Length song_length;

};

- Remember, class members can be any type, including another class

- For each song we can now store the Song_title and the song_length

- Now lets add this to our original Album definition.

Page 19: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 19

Our New Album Class

class Album { public:

string artist_ name;string title;string format;Song songs[10];

};

- That’s everything - an album now also contains an array with all the song information on it

Page 20: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 20

Using Our New Album Class

- We can set artist_ name, title, and format the same way as before

- To add a song, we create an object of type Song, fill it in, and place it into the array of song.

Song new_song;new_song.song_title = “Nature”;new_song.song_length.minutes = 2;new_song.song_length.seconds = 7;collection[0].songs[0] = new_song;

Page 21: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 21

Using Our New Album Class

- Notice how we referred to the members of Length in our Song

- Let’s take a look at how objects of our class are stored in memory now…

Page 22: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 22

PreviousAlbum...

NextAlbum...

Our Collection Array

Kevin_Miller

The_Beautiful_World

CDformat

title

Artist_name

songs[0]

Song_title

Song_length

Nature

Minutes: 2

Second: 7

Song_title

Song_length

….

Minutes: .

Second: .

songs[1]

Collection[n-1] Collection[n] Collection[n+1]

Page 23: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 23

Data Abstraction

- Complex data structures like this one allow us to specify relationships in our data

- We could have made one class for a song, including title, length in minutes, and length in seconds as members

- However, by making the length a separate class, we have indicated there is a closer relationship between minutes and seconds than between title and minutes

Page 24: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 24

Data Abstraction, cont’d

- We can use classes to separate what our data represents from how it is implemented

- this is called data abstraction

- This property allows us to build libraries of data types that we can re-use in other programs

Page 25: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 25

Changing Our Implementations

- Data abstraction also allows us to change our implementation while minimizing changes to our code

- For example, we could change our Length to: class Length {

public:float time;

};

- Where time represents the number of minutes (the decimal part is the number of seconds)

Page 26: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 26

The Benefit

- If we had isolated our use of Length to specific functions (like PrintLength(), InputLength(), etc.), we would only have to change those functions!!!

- By making our object more modular, we have a much more flexible approach!

- Changes (and bugs!) are isolated to easily identifiable portions of your code!

Page 27: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 27

The Problem

- In the definition we just gave there’s no way to enforce this isolation

- We can access the members of Length anywhere it’s define

- That is, I could write a nice function to take a length and print it, but some other function could take a song X (or even a whole album) and just output x.minutes and x.seconds

- or even use them in ways we didn't intend (like changing the length of a song…)

Page 28: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 28

Encapsulation and

Class Design

The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Page 29: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 29

Objects So Far

- So far objects just look like the method we showed for combining heterogeneous data together

- It looked like an array, but we access components by name rather than position

- But there's much more to them than that

- The use of true object-oriented programming is best seen from examining the nature of physical objects

- Suppose you had a factory and wanted to make a remote-controlled car

Page 30: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 30

Extending our Concept of Objects

- Think about what you'd specify in the design of the car

- Lots of data, like length, width, colour…

- also subcomponent objects: engine, etc...

- So an obvious application to the objects we've used so far

- But you'd also need other things– what the car's supposed to do if we turn the control left– or when we step on the break …

Page 31: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 31

Operations and Objects

- These are operations, not data, but the car's behaviors are just as much a part of the car when we think about building one

- Objects let us include operations as members as well!

- Object-oriented programming involves defining the data components of an object, and also the operations we perform on the object, and bundling them together into a single package

Page 32: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 32

Classes and Instances

- This analogy also makes the relationship between classes and instances clearer

- We define a Car class to encompass all the choices we've made in our car design

- It serves as a general model for the factory

- Then we crank out many instances of the Car class (and here, hopefully sell them for big bucks)

- This analogy will also explain many other aspects of Object-Oriented Programming that we will see later

Page 33: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 33

Operations and Objects

- Recall our problem with our length class - there was nothing restricting us from referring to the internal components of a length object from anywhere

- Thus big problem occurs if we ever changed length!

- We can simply define the legal operations for an object of type length, and make them part of length itself!

- Then they're in one spot, and we only have to ever make changes in one place

- Let's see what this looks like...

Page 34: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 34

Adding Functions

- we'll add routines to read and print a length

- For example:

class Length {

int minutes;int seconds;public:

void input();void print();

};

Page 35: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 35

Adding Functions

- This definition specifies a new class Length

- Similar to our earlier Length class, except the functions that operate on Length are included in our definition

- They look just like normal function headers - the odd part is the bodies are separate (we'll define them in a few minutes)

- The class contains Data members and function members

- Function members are also called methods

Page 36: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 36

Instantiation

- Remember that a class definition only creates a new type

– we need to declare objects/variables of that class: Length the_length;

– the_length is an instance of the class Length- also called an object of class (or type) Length

– Our declaration of the_length reserves space for the data members and

– We still need to define the methods

Page 37: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 37

Implementation

- We do this the same way as any other function, with a little extra syntax

void Length::input( ) void Length::print( ) { { cin >> minutes >> seconds; cout << minutes << “:” << seconds; } }

- These go outside the definition of the length class - it makes sense to keep them close though!

- “Length::” specifies that the function we’re defining isn't global, but belongs to the Length class. Could have a global input/print too!

Page 38: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 38

- Notice that within Length, we refer to the variables without dot notation

- i.e., we say minutes instead of the_ length.minutes

- This should make sense - remember why we use the dot notation

- normally we'd use the the_length prefix to specify the object whose minutes member we want

- but when this is executing we're INSIDE that object - there's only one minutes member we could possibly be referring to!

Page 39: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 39

- We’ve already seen class methods, although we haven’t been calling them that

- Calling a method:

the_length.print(cout);

- In other words, we call a method in the same way that we specify any other member, using “.”

Page 40: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 40

Scope

- Our print() method, has one line of code in it:

cout << minutes << “:” << seconds;

- When we call

the_length.print( );

minutes and seconds in the method refer to the_length’s minutes and seconds members

All this boils down to:- The scope of class members extends to the class’ methods

Page 41: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 41

Inside the Method

- If we declare another object of type Length, it will have different minutes and seconds members - for example:

Length the_length1, the_length2;

the_length1.input( );the_length2.input( );the_length1.print( );the_length2.print( );

Page 42: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 42

Back to the idea of protection

- Remember we brought up the idea of embedding functions in objects as a means of ensuring that code we write doesn't depend on the physical implementation of our class

- Instead of having several functions from all over referring to the internal data members of length, and having to change all those when we change the internals of length…

- We declare what we need INSIDE length and allow other objects to use those functions

Page 43: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 43

Back to the idea of protection

- That way NOBODY but the length object itself knows OR CARES about what's stored internally

- In this case, they just know that they can call input or print and get what they need!

- Everything else is INDEPENDENT of length

- BUT - there's still nothing FORCING us to use this… YET!

Page 44: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 44

Information Hiding

- This general concept is called Information Hiding and is one of the major benefits of using Object-Oriented methodologies

- C++ provides very nice mechanisms for enforcing the ideas we've just covered. In fact we've even seen a sign of them.

- The word "public:" has been put in every class we've made so far

- Classes allow us to select what parts to hide

Page 45: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 45

Information Hiding

- Members of the class following the “public:” specification can be accessed anywhere- So for example, we want our input and print functions to be public in our Length class - we WANT other's to be able to use them!

- Any other members are considered private– We can also explicitly declare members as private using the “private:” specification

- Private members can be accessed in member functions (methods)

- So anything we put before the "public:" can only be seen/ changed inside the class!

Page 46: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 46

Private: Specification

class Length {public:

void input( );void print( );

private:int minutes;int seconds;

};

- So, in our example, we can make “minutes” and “second” as private members so that only the two public members (input and print methods) can access them.

Page 47: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 47

- In general, Any function or data member can be public or private

- By specifying members as either public or private, we can decide what parts of our class are visible to the rest of our program, and which are hidden

- Thus, as long as the public stuff looks the same, we can change our private members at will!

- For example, if we wanted to change the way we store minutes and seconds to a float (whole number is minutes, fractional part is seconds), we can do that

- And ANY OTHER PART of our program will be completely unaffected, because they couldn't possibly be using those

members

Page 48: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 48

Changing the Implementation

class Length {public:

void input( );void print( );

private:float time;

};

- Now we could change our input() and print() methods appropriately

- Notice: functions using (calling) input and print don't have to change!

Page 49: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 49

The Interface

- Our Length class can only be accessed through the input() and print() methods

- These methods make up the interface to our class- The part the user of the object gets to see

and work with

- Anything public is part of the interface

Page 50: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 50

Designing Classes

- Programming classes is a little different from what we’ve been doing so far

- The programs that you’ve designed already (like the assignments) solved problems by dividing them into smaller tasks

- Each task was implemented as a function Rather than dividing things into tasks, we start by looking at the data we are working with.

- In object-oriented programming and design, we design our classes by dividing up the data by logical relationships

Page 51: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 51

Designing Classes

- Then we need to decide what we need to do with our data- This helps us create our interface

- For example, it was decided (beforehand) that our Length class was going to be used in our list of music albums

- We would be reading in the list of albums (from a file or the keyboard), and writing them out

- So the only two methods that we need are input() and print()

Page 52: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 52

Encapsulation

- We can make that easier by separating the implementation of our class from where it’s declared

– this is called encapsulation

- In practice, usually do this by placing our implementation in a separate source code file

- We would create a file called length.cpp containing our two function declarations

Page 53: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 53

The Interface

- In order to use our class in a program, we need to have the class definition specified somewhere

- We would put it in a header file: length.h

- Now we’ve (mostly) split things up according to our design:

– length.cpp contains our implementation– length.h contains our interface (the specification file)– our main program uses the Length class

<See: Example 1>

Page 54: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 54

Constructors

- A constructor is a function that gets called each time an instance of a class is created

- Defining a constructor ensures that when we create an instance, it has some sort of (meaningful) initial value

- A constructor is a method (member function) which has the same name as the class itself class Length {

public:Length();...

};- Notice the syntax: no return type is specified!

Page 55: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 55

Default Constructors

- This particular constructor takes no parameters, and gets called when we instantiate our class like this:

Length the_length;

- We call this the default constructor- it doesn't do much!

- The implementation might look like this:

Length::Length() {

minutes = 0; // a gain, inside the object, so no '. '!

seconds = 0; }

Page 56: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 56

Constructors, cont’d

- We can also have a constructor that takes one or more parameters:

class Length {public:

Length (int, int);// Our default constructor can be specified// as well - c++ knows which one to use by// the number & types of parameters// supplied when calling it!

Length();…

};

Page 57: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 57

Constructors, cont’d

- This constructor gets called when we instantiate our class with parameters: Length the_ length( 1, 43);

- Our implementation might be:

Length:: Length( int mins, int secs) {

// Initialize our class to the given number of// minutes and seconds

minutes = mins;seconds = secs;

}

Page 58: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 58

Constructors, cont’d

- There’s an odd interaction between default constructors and ones which take parameters

- A default constructor exists even if you don’t explicitly write one (it just doesn’t do anything)

- But if you specify a constructor that takes parameters, and no default constructor,

then the class has no default constructor

Page 59: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 59

- Let’s say Length has no constructors at all: Length the_ length; // Calls the default constructor

- This works:- we haven’t written a default constructor, but one still exists (the one that does nothing)

- Let’s add a constructor that takes parameters, like Length:: Length( int, int) Length len1(1, 43); // OK, calls Length( int, int)

Length len2; // Error! No default constructor!

- This is important because we cannot use a constructor with parameters when we make an array of class instances

- Arrays require a default constructor (or no constructors at all)

Page 60: Sahar Mosleh California State University San MarcosPage 1 Simple C++ Classes The contents of this lecture prepared by the instructors at the University

Sahar Mosleh California State University San Marcos Page 60

Destructors

- The opposite of constructors

- Destructors are functions that get called when our variable is destroyed (e.g. goes out of scope)

- They look like this:class Length { public: ~Length(); // Destructor ...};

- We don’t have much of a use for these – yet