1 of 12

Classes

CSE 232 - Dr. Josh Nahum

2 of 12

Reading:

Section 2.3

3 of 12

Table of contents

00

02

01

enum & union

Return Type

Constructors

4 of 12

00

enum & union

5 of 12

—Me

“enums and unions are powerful types, but not essential enough to be taught in CSE 232.”

6 of 12

01

Return Type

7 of 12

Alternative Return Types

Danger! Functions should not return references or pointers to variables that are local to the function. These local variables will fall out of scope and be deleted when the function call ends.

Most function return ordinary types (non-const copies of objects).

Functions can return pointers, references and const objects, if needed.

8 of 12

Live Coding Example

9 of 12

02

Constructors

10 of 12

Constructors

Constructors never have a return type

Body

Constructor

No Return Type

Optionally a list can be provided to initialize data members

The body of the constructor can to other initialization work (if any)

Member initializer list

A constructor is a member function with the same name as the class

11 of 12

Default Constructor

Could also be written like this with a member initialization list:

class Vector {

public:

Vector() :elem{nullptr}, sz{0} {}

// ...

};

A default constructor is a constructor that can be called with no arguments.

Example:

class Vector {

public:

Vector() {

elem = nullptr;

sz = 0;

}

// ...

};

12 of 12

Attribution

Dr. Joshua Nahum

www.nahum.us

EB 3504

Please ask questions via Piazza

© Michigan State University - CSE 232 - Introduction to Programming II

CREDITS: This presentation template was created by Slidesgo, and includes icons by Flaticon, and infographics & images by Freepik