Download presentation
Presentation is loading. Please wait.
1
C++ for Java Programmers
Chapter 5 Class Definitions C++ for Java Programmers
2
Classes Similarities & Minor Differences
Java C++ No semicolon. Modifiers to each data field or method individually. extends to indicate Inheritance from a parent class. Class contains member function implementation End with a semicolon. Divided into major sections by private, protected, and public. class A : B, C, D to indicate inheritance All classes are public. Member function implementation can be external to class C++ for Java Programmers
3
C++ for Java Programmers
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; }; 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 name void Link::addBefore(int value, List* theList) { … } 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 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. C++ for Java Programmers
7
C++ for Java Programmers
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. C++ for Java Programmers
8
C++ for Java Programmers
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. C++ for Java Programmers
9
C++ for Java Programmers
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
10
C++ for Java Programmers
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
11
C++ for Java Programmers
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) 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 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. C++ for Java Programmers
14
C++ for Java Programmers
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 *); C++ for Java Programmers
15
C++ for Java Programmers
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. C++ for Java Programmers
16
C++ for Java Programmers
Forward Reference A list Link Link Link Link 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); }; C++ for Java Programmers
18
Example of Forward References
class Link { // now provide the full link implementation public: // constructor defined in-line Link (int v, Link * f, Link * b) { value = v; forwardLink = f; backwardLink = b; } // data fields are public int value; Link * forwardLink; Link * backwardLink; // prototype, definition given elsewhere // requires knowledge of class List void addBefore (int val, List * theList); }; 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); } 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. 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 C++ for Java Programmers
22
Example of Constructors
class 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 constructor box two (7); // ordinary constructor box three (two); // copy constructor box four = merge_boxes(one, two) // copy constructor C++ for Java Programmers
23
C++ for Java Programmers
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. 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 } }; C++ for Java Programmers
25
Example of Initializers
class A { // class with initialization error public: 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; C++ for Java Programmers
26
Example of Initializers
class bigBox extends box { // Java code public bigBox (int x, double d) { super(x); // initialize parent dvalue = d; // initialize self } private double dvalue; // private data field } class bigBox : public box { // C++ code public: bigBox (int x, double d) : box(x), //init base class dvalue(d) //init derived class {} private: double dvalue; }; C++ for Java Programmers
27
Example of Initializers
class order { // Warning - Initializations done // in order of method declaration // Not in order of initializer public: order (int i) : one(i), two(one) { } int test() { return two; } private: int two; // initialized first int one; // initialized second }; 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. C++ for Java Programmers
29
Initialization in Java
class A { // Java classes illustrating initialization public 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"); } C++ for Java Programmers
30
C++ for Java Programmers
Output of Java in A constructor in A init in B init in B constructor C++ for Java Programmers
31
C++ for Java Programmers
Initialization in C++ class A { // C++ classes illustrating initialization public: 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"); } C++ for Java Programmers
32
C++ for Java Programmers
Output of C++ in A constructor in A init in B constructor C++ for Java Programmers
33
Combining Constructors
In C++, you cannot invoke one constructor form within another. class box { // error -- does not work as expected public: box (int i) : x(i) { } box (int i, int j) : y(j) { box::box(i); } int x, y; }; 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 } }; C++ for Java Programmers
35
Example of Constructors
// C++ class with factored constructors class 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 } }; 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. C++ for Java Programmers
37
C++ for Java Programmers
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. C++ for Java Programmers
38
C++ for Java Programmers
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 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. 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 C++ for Java Programmers
41
C++ for Java Programmers
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 class int box::zeroCount = 0; C++ for Java Programmers
42
Example of static constants
class coloredBox : public box { public: // define the range of color values static 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; }; 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? 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? 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? 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? C++ for Java Programmers
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.