46
C++ for Java Programmers 1 C++ for Java Programmers Chapter 5 Class Definitions

C++ for Java Programmers1 Chapter 5 Class Definitions

Embed Size (px)

Citation preview

Page 1: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 1

C++ for Java Programmers

Chapter 5Class Definitions

Page 2: C++ for Java Programmers1 Chapter 5 Class Definitions

ClassesSimilarities & Minor Differences

Java No semicolon. Modifiers to each data

field or method individually.

extends to indicate Inheritance from a parent class.

Class contains member function implementation

C++ End with a semicolon. Divided into major sections

by private, protected, and public.

class A : B, C, Dto indicate inheritance

All classes are public. Member function

implementation can be external to class

C++ for Java Programmers 2

Page 3: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 3

Example

class box { // Java public box (int v) { val = v; }public int value() { return val; }private int val;

}

class box { // C++public:

box (int v) { val = v; }int value() { return val; }

private:int val;

};

Page 4: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 4

Separation of Class & Implementation

In C++, method bodies are typically not placed in the class definition. Usually prototypes only

External method body must use fully qualified namevoid Link::addBefore(int value, List* theList){ …}

Page 5: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 5

Separation of Class & Implementation

Methods defined in class are called inline definitions

Use inline definitions only for methods that are short.

An optimizing compiler may choose to expand an inline method directly, without the cost of a function call

Page 6: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 6

Interface & Implementation Files

Interface file: extension .h is used in the interface file name.

Implementations will often be in a different file from the class definition.

In C++, a class need not be defined in a file with the same name.

Page 7: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 7

Example of Interface

# include <libClass.h># include "myClass.h"# include "/users/…/…/tom/myClass.h"

Angle bracket indicate “system” interface files. Quotation marks are used for immediate

interface files.

Page 8: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 8

The inline Directive

Can be used to indicate that the function can be expanded inline at a point of call, exactly as if the method had been written in a class description.

If the method body is sufficiently short, it can be marked as inline.

Virtual methods should not be declared as inline, as compiler is not able to produce inline code even if requested by the user.

Page 9: C++ for Java Programmers1 Chapter 5 Class Definitions

Virtual Functions

class Animal{ public: virtual void eat() { cout << "I eat like a generic Animal.”; } }; class Wolf : public Animal { public: void eat() { cout << "I eat like a wolf!”; } }; class Fish : public Animal { public: void eat() { cout << "I eat like a fish!”; } };class GoldFish : public Fish { public: void eat() { cout << "I eat like a goldfish!“; } };

C++ for Java Programmers 9

Page 10: C++ for Java Programmers1 Chapter 5 Class Definitions

Virtual Functions

Animal* anAnimal[4];

anAnimal[0] = new Animal(); anAnimal[1] = new Wolf(); anAnimal[2] = new Fish(); anAnimal[3] = new GoldFish(); for (int i = 0; i < 5; i++){ anAnimal[i]->eat(); // what happens when

delete anAnimal[i]; // i == 4 ??}

C++ for Java Programmers 10

Page 11: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 11

Prototypes

Function type signature must be known before a function can be invoked.

Function type signature describes the argument and return types of a function.

Must happen before first time a function is used (note, different than in Java)

Page 12: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 12

Examples of Prototypes

int max (int, int);

int min (int a, int b); // argument names are optional

complex abs (complex &); // can use user defined types

bool operator < (distance &, distance &);

// prototype for operator

Page 13: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 13

External Declarations

The extern modifier to a declaration indicates that a global variable is defined in another file but will be used in the current file.

The declaration informs the linker that the value being named is used in two or more files but that it should nevertheless refer to only one object.

Page 14: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 14

Example of extern

extern int size;

extern char buffer[ ]; // array limits don't have to be given

extern ObjectType anObject;

// declare strcmp is written in C, not C++

extern "C" int strcmp (const char *, const char *);

Page 15: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 15

Forward References

Both function and class names must be defined before they can be used.

A forward declaration asserts that a particular name represents a class but gives no further information.

It permits pointers to be declared to the class but not to invoke methods defined by the class or the creation of instances of the class.

Page 16: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 16

Forward Reference

A list

Link Link Link Link

Page 17: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 17

Example of Forward References

class Link; // forward declaration

class List

{public:...private:

Link * firstLink; // permitted, since class Link is declared

void push_front (int val);

};

Page 18: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 18

Example of Forward References

class Link { // now provide the full link implementationpublic:

// constructor defined in-lineLink (int v, Link * f, Link * b) {

value = v;forwardLink = f;backwardLink = b;

} // data fields are publicint value;Link * forwardLink;Link * backwardLink;

// prototype, definition given elsewhere// requires knowledge of class Listvoid addBefore (int val, List * theList);

};

Page 19: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 19

Example of Forward References

inline void List::push_front (int val)

{if (firstElement == 0) // adding to empty list

firstElement = new Link(val, 0, 0);else // else add before first element

firstElement->addBefore(val, this);

}

Page 20: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 20

Constructors and Initialization

Constructors tie together the tasks of creation and initialization.

Ensuring that no value is created without being initialized and no value is initialized more than once.

Page 21: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 21

Default & Copy Constructors

All class definitions should include both a default and a copy constructor.

The default constructor takes no arguments. Used to initialize object data fields with default

values when no other arguments are specified. A copy constructor takes an instance of the same

class as a constant reference argument. (Clone constructor)

Used internally when functions return Class values, or are passed Class parameters by value

Page 22: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 22

Example of Constructorsclass box { public: box () // default constructor

{ val = 1; } // give data field some default value

box (int x) // ordinary constructor{ val = x; }

box (const box & a) // copy constructor{ val = a.val; } // clone argument value

private:int box_val;

};box one; // default constructorbox two (7); // ordinary constructorbox three (two); // copy constructorbox four = merge_boxes(one, two) // copy constructor

Page 23: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 23

Initializers

In Java, if a data member is initialized with a value that is independent of the constructor arguments, simply written as an initial assignment at the point of declaration, otherwise, an explicit assignment statement.

C++ does not allow the initialization of data members at the point of declaration.

All data members must be initialized in a constructor. Performed either in an explicit assignment or in an

initializer.

Page 24: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 24

Example of Initialization

class Link {public:

Link(int v, Link * f, Link * b) : value(v), forwardLink(f), backwardLink(b) { }

Link(int v, Link * f, Link * b) // without initializers

{ value = v;

forwardLink = f;

backwardLink = b

}

};

Page 25: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 25

Example of Initializers

class A { // class with initialization errorpublic:

void A (box & aBox) : boxOne(aBox) // copy constructor{ boxTwo = aBox; } // default constructor, then assign

private:box boxOne;box boxTwo;

};class B { // a better way,

public:void B (box & aBox) : boxOne(aBox), boxTwo(aBox) { }

private:box & boxOne;const box boxTwo;

};

Page 26: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 26

Example of Initializers

class bigBox extends box { // Java codepublic bigBox (int x, double d) {

super(x); // initialize parentdvalue = d; // initialize self

}private double dvalue; // private data field

}

class bigBox : public box { // C++ codepublic: bigBox (int x, double d)

: box(x), //init base classdvalue(d) //init derived

class{}

private: double dvalue; };

Page 27: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 27

Example of Initializers

class order { // Warning - Initializations done

// in order of method declaration

// Not in order of initializerpublic:

order (int i) : one(i), two(one) { }int test() { return two; }

private:int two; // initialized first int one; // initialized second

};

Page 28: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 28

Order of Initialization

In C++, the initialization of parent classes occurs before the initialization of child class.

Methods that are invoked are matched only to functions in the parent class, even if these methods have been declared as virtual.

Page 29: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 29

Initialization in Java

class A { // Java classes illustrating initializationpublic A () {

System.out.println("in A constructor");init();

}public void init () {

System.out.println ("in A init"); }

}class B extends A {

public B () { System.out.println ("in B constructor");

}public void init () {

super.init();System.out.println ("in B init");

}}

Page 30: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 30

Output of Java

in A constructor

in A init

in B init

in B constructor

Page 31: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 31

Initialization in C++

class A { // C++ classes illustrating initializationpublic:

A () { printf("in A constructor\n"); init(); }

virtual void init () { printf("in A init\n"); }

};class B : public A {

public:B () {

printf("in B constructor\n"); }virtual void init () {

A::init(); printf("in B init\n");

}};

Page 32: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 32

Output of C++

in A constructor

in A init

in B constructor

Page 33: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 33

Combining Constructors

In C++, you cannot invoke one constructor form within another.

class box { // error -- does not work as expectedpublic:

box (int i) : x(i) { }box (int i, int j) : y(j) { box::box(i); }

int x, y;

};

Page 34: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 34

Example of Constructors

// C++ class with default arguments in constructor

class newClass {public:

newclass (int i, int j = 7) {

// do object initialization...

}

};

Page 35: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 35

Example of Constructors

// C++ class with factored constructorsclass newClass {

public:newClass (int i) {

initialize(i); // do common initialization}newClass (int i, int j) {

initialize(i);... // then do further initialization

}private:

void initialize (int i) {... // common initialization actions}

};

Page 36: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 36

The Orthodox Canonical Class Form

A default constructor: used internally to initialize objects and data members when no other value is available.

A copy constructor: used in the implementation of call-by-value parameters.

An assignment operator: used to assign one value to another.

A destructor: Invoked when an object is deleted.

Page 37: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 37

Visibility Modifiers

In C++, the modifiers designate a section of a class definition rather than being applied item by item as in Java.

The modifiers cannot be applied to entire classes.

A subclass is permitted to change the visibility of attributes inherited from a parent class.

Page 38: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 38

Example of Modifiers

class parent {public:

virtual void test () { printf("in parent test\n"); }};class child : public parent {

private:void test () { printf("in parent test\n"); }

};

parent * p = new child;p->test();

child * c = (parent *) p;c->test(); // compile error, cannot invoke private method

Page 39: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 39

Inner Classes vs. Nested Classes

An inner class in Java is linked to a specific instance of surrounding class, and is permitted access to data fields and methods in this object.

A nested class in C++ is simply a naming device; it restricts the visibility of features associated with the inner class, but otherwise the two are not related.

Page 40: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 40

static Initialization

C++ does not use the message-passing syntax of invoking static functions.

d = Math.sqrt (d); // Java -- invoke static function sqrt

Date::setDefault(12,7,42); // C++ -- use qualified name

Page 41: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 41

Example of static

class box {public:

box (int v) : value(v) { boxCount++; if (v == 0)

zeroCount++; }

private:static int boxCount = 0;static int zeroCount;

};

// global initialization is separate from classint box::zeroCount = 0;

Page 42: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 42

Example of static constants

class coloredBox : public box {public:

// define the range of color valuesstatic const int Red = 1;static const int Yellow = 2;static const int Blue = 3;

coloredBox (int v, int c) : box(v), ourColor(c) { }

private:int ourColor;

};

Page 43: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 43

Test your understanding What are some superficial

similarities between class definitions in Java and C++? What are some differences?

What does it mean to say that C++ separates class definition and implementation?

Page 44: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 44

Test your understanding What does it mean to say a

method is inline? How does (may) the compiler treat

an inline method differently? What are two different ways to

create an inline method?

Page 45: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 45

Test your understanding What is a function prototype?

When is it necessary to provide one?

What does the extern modifier on a declaration mean?

Page 46: C++ for Java Programmers1 Chapter 5 Class Definitions

C++ for Java Programmers 46

Test your understanding What two tasks are tied together

by a constructor? What is a default constructor? What is a copy constructor?