the c++ class class - clemson university · pdf file2.1.c++ class vs c++ struct only one di...

42
What is a class? Classes and objects Class Constructors Overloaded Operators Interface vs . . . Naming Conventions Makefiles Sample Problems Template Classes JJ II J I Slide 1 of 42 Go Back Full Screen Quit The C++ Class January 19, 2012 Brian A. Malloy

Upload: lamtruc

Post on 28-Mar-2018

220 views

Category:

Documents


1 download

TRANSCRIPT

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 1 of 42

Go Back

Full Screen

Quit

The C++ Class

January 19, 2012

Brian A. Malloy

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 2 of 42

Go Back

Full Screen

Quit

1. What is a class?

• Unit of encapsulation:

– Public operations

– Private implementation

• Abstraction:

– string: abstracts char* of C

– student

– sprite

• C++ Classes: easy to write, difficult to getright!

• I’ll provide lots of examples and gotchas

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 3 of 42

Go Back

Full Screen

Quit

2. Classes and objects

• C++ objects can be stored on the stack:

class A{};

int main() {

// a & b are allocated on stack;

// storage is automatic

A a, b;

};

• Or on the heap:

int main() {

A *a = new A; // Programmer allocated this, so

A *b = new B; // programmer has to deallocate

};

• Compiler does stack; programmer does heap!

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 4 of 42

Go Back

Full Screen

Quit

2.1. C++ class vs C++ struct

• Only one difference: the default protection

• Default protection for a class is private

• Default protection for a struct is public

• Data attributes should never be public, sothe “Bad class” below should make its dataattributes private!

Bad class Good Classclass Student { class Student {

public: string name;

string name; float gpa;

float gpa; };

};

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 5 of 42

Go Back

Full Screen

Quit

3. Class Constructors

• A well designed class takes care of itself.This includes:

– Allocating storage for its data attributes

– Making sure each attribute is initial-ized

– When the class is destroyed any heap-based storage should be reallocated.

• These actions are coded in the constructorsand destructor for the class

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 6 of 42

Go Back

Full Screen

Quit

Three types of constructors:

• Default

• Conversion

• Copy

class Student {

public:

Student(); // default constructor (no args)

Student(char * n); // conversion constructor

Student(const Student&); // copy constructor

};

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 7 of 42

Go Back

Full Screen

Quit

What constructors are used:1 #include <iostream>

2 class String {

3 public:

4 String() { cout << "default "; }

5 String(const char * const n) { cout<<"convert "; }

6 String(const String&) { cout << "copy "; }

7 ~String() { cout << "destructor "; }

8 private:

9 char * name;

10 };

11 int main() {

12 String a("cat"), b = a;

13 String * ptr = new String("dog");

14 cout << endl;

15 }

************ output ****************

convert copy convert

destructor destructor

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 8 of 42

Go Back

Full Screen

Quit

3.1. Prefer initialization to assignment

• This is Item # 12 in Effective C++

• Initialization is more efficient for data at-tributes that are objects; I’ll demonstratethis in later slides.

• To initialize data attributes, we don’t useassignment, but rather we prefer a differentnotation, explained on the next page.

• There are times when initialization mustbe used:

– const and reference parameters.

– When passing values from a derivedclass to a base class.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 9 of 42

Go Back

Full Screen

Quit

Initialization vs Assignment

Class Student initializes data attribute gpa by us-ing initialization on line 3: gpa(g). You might beaccustomed to assignment, illustrated for Teacheron Line 9. However, the Student is correct!

1 class Student {

2 public:

3 Student(float g) : gpa(g) {}

4 private:

5 float gpa;

6 };

7 class Teacher {

8 public:

9 Teacher(int a) { age = a; }

10 private:

11 int age;

12 };

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 10 of 42

Go Back

Full Screen

Quit

Comparing the cost of init v assign

The examples on the following pages compare the use ofassignment and initialization.

Class Test1, on the next page, uses assignment to initializestr. The output is: default convert assign.The default constructor is used because construction ofobjects proceeds in two phases:

1. Initialization of data members

2. Execution of the body of the constructor

Since there is no initialization argument for str, the de-

fault constructor is used to initialize it. Then, the con-

version constructor is used to convert parameter s to a

string and, finally, assignment is used to assign s to str.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 11 of 42

Go Back

Full Screen

Quit

The cost of assignment1 class string {

2 char *buf;

3 public:

4 string() { cout << "default "; }

5 string(const char *b) { cout << "convert "; }

6 string& operator=(const string&) {

7 cout << "assign ";

8 return *this;

9 }

10 };

11 class Test1 {

12 string str;

13 public:

14 Test1(const char* s) { str = s; }

15 };

16 int main() {

17 Test1 t1("cat"); //output: default convert assign

18 }

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 12 of 42

Go Back

Full Screen

Quit

The cost of initialization1 class string {

2 char *buf;

3 public:

4 string() { cout << "default "; }

5 string(const char *b) { cout << "convert ";}

6 string& operator=(const string&) {

7 cout << "assign ";

8 return *this;

9 }

10 };

11 class Test2 {

12 string str;

13 public:

14 Test2(const char* s) : str(s) { }

15 };

16 int main() {

17 Test2 t2("dog"); //output: convert

18 }

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 13 of 42

Go Back

Full Screen

Quit

Inheritance

You must use the initialization notation to passparameters to a base class. For example, on line9 below, we are passing age to the base classPerson.

1 class Person {

2 public:

3 Person(int a) : age(a) {}

4 private:

5 int age;

6 };

7 class Student : public Person {

8 public:

9 Student(int age, float g) : Person(age), gpa(g) {}

10 private:

11 float gpa;

12 };

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 14 of 42

Go Back

Full Screen

Quit

Init performed in order of declare

Class data attributes are initialized in the orderthat they are declared in the class. For example,in class Student below, iq is declared first, andthen age, on lines 5 and 6. This means that iqwill be initialized before age on line 3, which isprobably an error.

1 class Student {

2 public:

3 Student(int a) : age(a), iq(age+100) {}

4 private:

5 int iq;

6 int age;

7 };

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 15 of 42

Go Back

Full Screen

Quit

3.2. Principle of Least Privilege

• Use const whenever possible. (Item #3)

• Can reduce debugging: you know that amember function cannot modify any dataif the function is const

• Provides documentation

• Allow a function enough access to data at-tributes to accomplish its task and no more!

• Most beginners take them all out when theyshould probably add more!

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 16 of 42

Go Back

Full Screen

Quit

Least Privilege Discussion

• Class string, on the next page, demonstratescorrect use of const.

• Function get, line 7, is a constant mem-ber function, because “const” appears af-ter the parentheses and before the curlybraces. This means that get cannot modifyany data in class string.

• If get were not a constant function, thenthe use of get, line 13, would be invalidbecause parameter s, line 12, is declaredconst, which means that any use of s mustguarantee that constness is preserved.

• Function get returns a const value; thus,the returned value may not be modified.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 17 of 42

Go Back

Full Screen

Quit

Least Privilege example1 class string {

2 public:

3 string(const char* n) :

4 buf(new char[strlen(n)+1]) {

5 strcpy(buf, n);

6 }

7 const char* get() const { return buf; }

8 private:

9 char * buf;

10 };

11 std::ostream& operator<<(std::ostream& out,

12 const string& s) {

13 return out << s.get();

14 }

15 int main() {

16 const string x("Hello");

17 std::cout << x.get() << std::endl;

18 }

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 18 of 42

Go Back

Full Screen

Quit

3.3. Classes with Pointers: canonical form1. Copy constructor

2. Destructor

3. Overloaded assignment

class string {

public:

string();

string(const string&);

~string();

string operator=(const string&);

private:

char *buf;

};

ostream& operator<<(ostream&, const string&);

Note: the term canonical form was introduced by J. Coplien

in: Advanced C++ Programming Styles and Idioms

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 19 of 42

Go Back

Full Screen

Quit

Why canonical form?

If a class with heap-based memory is not in canon-ical form, it’s likely that a shallow copy of thepointer value will be made. When this happens,a plethora of errors may ensue, including incor-rect data values and double free errors.

Figure 1: Shallow Copy

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 20 of 42

Go Back

Full Screen

Quit

Example: Double Free ErrorThe innocuous looking program below will com-pile, but when executed, gives a double free error!Do you see why?

1 class Problem {

2 public:

3 Problem(int n) : stuff(new int) { (*stuff) = n; }

4 ~Problem() { delete stuff; }

5 private:

6 int * stuff;

7 };

8 int main() {

9 Problem p(17), q(p);

10 }

Figure 2: A class that’s not in canonical form

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 21 of 42

Go Back

Full Screen

Quit

Why do we get a double free error?

Figure 3: Result of no copy constructor

The above figure illustrates the state of the pro-gram in Figure 2 at line 9, after the programmersupplied conversion constructor and the compilersupplied “copy” constructor are used to createobjects p and q. The shallow copy results be-cause the programmer did not write a copy con-structor, so the compiler supplies one.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 22 of 42

Go Back

Full Screen

Quit

Compiler Supplied Functions

If the programmer writes this:

class Empty{};

The compiler writes this:

class Empty {

public:

Empty();

Empty(const Empty &);

~Empty();

Empty& operator=(const Empty &);

Empty * operator&();

const Empty * operator&() const;

};

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 23 of 42

Go Back

Full Screen

Quit

Here’s what they look like:

inline Empty::Empty() {}

inline Empty::~Empty() {}

inline Empty * Empty::operator&() {return this;}

inline const Empty * Empty::operator&() const {

return this;

}

The copy constructor & assignment operator simply

do a member wise copy, i.e., shallow. Note that

the default assignment may induce a memory leak.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 24 of 42

Go Back

Full Screen

Quit

To ensure a deep copy: write a copyconstructor and an assignment operator

for classes with pointers

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 25 of 42

Go Back

Full Screen

Quit

Problem Solved!1 #include <iostream>

2 using std::ostream;

3 class Problem {

4 public:

5 Problem(int n) : stuff(new int(n)) { }

6 Problem(const Problem& p) :

stuff(new int(p.getStuff())) { }

7 ~Problem() { delete stuff; }

8 int getStuff() const { return *stuff; }

9 void setStuff(int n) {

10 delete stuff;

11 stuff = new int(n);

12 }

13 Problem& operator=(const Problem& rhs) {

14 if ( this == &rhs ) return *this;

15 setStuff(rhs.getStuff());

16 return *this;17 }

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 26 of 42

Go Back

Full Screen

Quit

18 private:

19 int * stuff;

20 };

21 ostream& operator<<(ostream& output, const Problem& p) {

22 return output << p.getStuff();

23 }

24 int main() {

25 Problem p(17), q(p);

26 std::cout << p << ’\t’ << q << std::endl;

27 q.setStuff(99);

28 p = q;

29 std::cout << p << ’\t’ << q << std::endl;

30 }

************ output ****************

17 17

99 99

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 27 of 42

Go Back

Full Screen

Quit

Hopefully, you now know what’s wrongwith this class. Also, notice that

setName is horribly wrong!

class Student {

public:

Student(char * n) : name(n) { }

const getName() const { return name; }

void setName(char *n) { name = n; }

private:

char *name;

};

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 28 of 42

Go Back

Full Screen

Quit

4. Overloaded Operators

class string {

public:

string();

string(const string&);

string operator+(const string&);

string operator=(const string&);

char operator[](int index);

private:

char *buf;

};

string operator+(const string&, const string&);

ostream& operator<<(ostream&, const string&);

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 29 of 42

Go Back

Full Screen

Quit

4.1. An overloaded binary operator:

• Can be written in infix form:

a = b;

cout << stu;

• Or can be written in prefix form:

a.operator=(b)

cout.operator<<(stu)

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 30 of 42

Go Back

Full Screen

Quit

4.2. How to overload assignment

Student & operator=(const Student & stu) {

if (this == &stu) return * this;

delete [] name;

name = new char[strlen(stu.name)+1];

strcpy(name, stu.name);

gpa = stu.gpa;

return *this;

}

(1) Why the comparison on the first line?

(2) Could the first line be: if (*this == stu)?

(3) Why return *this? What does it enable?

(4) Why not return stu, rather than *this?

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 31 of 42

Go Back

Full Screen

Quit

4.3. Formula for overloaded assignment:

• Check for equality of lhs & rhs

• delete storage for lhs

• Create new storage for lhs that’s size of rhs

• Copy data from rhs object to lhs

• return a reference to *this

• Be sure to assign to all data members

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 32 of 42

Go Back

Full Screen

Quit

4.4. About overloading operators:

• Almost all operators can be overloaded

• Operators are binary or unary

• Have the same precedence as their compilercounterpart

• Can be members or friends

• The overloaded output operator should notbe a member of a user defined class

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 33 of 42

Go Back

Full Screen

Quit

4.5. Overloading output as friend

class Student {

public:

getName() const { return name; }

getGpa() { return gpa; }

friend ostream&

operator<<(ostream &, const Student &);

private:

char * name;

float gpa;

};

ostream&

operator<<(ostream& out, const Student& s) {

out << s.name << \t << s.gpa;

return out;

}

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 34 of 42

Go Back

Full Screen

Quit

4.6. Overloading output as stand-alone:

class Student {

public:

getName() const { return name; }

getGpa() { return gpa; }

private:

char * name;

float gpa;

};

ostream &

operator<<(ostream& out, const Student& s) {

out << s.getName() << \t << s.getGpa();

return out;

}

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 35 of 42

Go Back

Full Screen

Quit

5. Interface vs Implementation

Interface goes in .h file:class Student {public:

const char* getName() const { return name; }const float getGpa() const { return gpa; }

private:char * name;float gpa;};ostream& operator <<(ostream &, const Student &);

Implementation goes in .cpp file:ostream & operator<<(ostream& out, const Student& s) {

out << s.getName() << s.getGpa();return out;}

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 36 of 42

Go Back

Full Screen

Quit

6. Naming Conventions

Naming conventions are used in computer pro-gramming to:

• Reduce the effort needed to read and understandsource code.

• Provide additional information about an identifier;for example, the naming convention can indicatethat a variable is a class name, or a data memberof a class, or a global constant.

• Promote consistency among development teams.

• Enable the use of refactoring tools to automatesearch and replace.

• To enhance clarity in cases of ambiguity.

• Enhance source code appearance.

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 37 of 42

Go Back

Full Screen

Quit

A C++ naming convention

There are many naming conventions used in pro-gramming languages and an excellent summaryof these can be found on wikipedia:

http://en.wikipedia.org/wiki/Naming_convention_(programming)

The naming convention used by many C++ pro-grammers is:

• global constants: all caps; underscore separates words

• local & global variables: lower case w/ underscore

• Class names: each word begins upper case

• Class member functions: begin lower case, there-after each word begins with upper case

• Data members: same as member functions

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 38 of 42

Go Back

Full Screen

Quit

7. Makefiles

• Consist of definitions,

• Followed by sequences of 2 line commands.

– First line begins with < id >: fol-lowed by dependencies of < id >

– Second line is the rule to make < id >;this line MUST be preceded by a tab

• To use the make file type: make {< id >}

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 39 of 42

Go Back

Full Screen

Quit

7.1. A simple makefile

CXX = clang++

FLAGS = -Wall -Weffc++ -Wextra -pedantic

main: main.o binary.o

$(CXX) $(FLAGS) -o main main.o binary.o

main.o: main.cpp binary.h

$(CXX) $(FLAGS) -c main.cpp

binary.o: binary.cpp binary.h

$(CXX) $(FLAGS) -c binary.cpp

clean:

rm -f main *.o core

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 40 of 42

Go Back

Full Screen

Quit

7.2. Discussion of Makefile

• $(CXX) permits us to easily switch to an-other compiler; e.g. g++

• make clean will clean the directory of largefiles

• -o option creates an executable

• -c option creates .o file

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 41 of 42

Go Back

Full Screen

Quit

8. Sample Problems

• Design a class for Student

• Write a class string, that encapsulates strings

• Write Binary, an abstraction for binary math.

• Write Stack, an abstraction of a stack.

• Design an experiment to see which is faster:your list or standard C++ library list?

• Faster: your string or standard C++ string?

• Faster: char* or standard C++ string?

What is a class?

Classes and objects

Class Constructors

Overloaded Operators

Interface vs . . .

Naming Conventions

Makefiles

Sample Problems

Template Classes

JJ II

J I

Slide 42 of 42

Go Back

Full Screen

Quit

9. Template Classes

• Normal functions accept variables as pa-rameters

• Template classes accept types as parame-ters