140 likes | 232 Views
Classes, Arrays & Pointers. Compiler & Linker expectations. file1.cpp. file2.cpp. filen.cpp. …. Compiler. Compiler. Compiler. file1.o. file2.o. filen.o. …. Linker. C++ compiler does not care about filenames. application (executable). Classes.
E N D
Compiler & Linker expectations file1.cpp file2.cpp filen.cpp …. Compiler Compiler Compiler file1.o file2.o filen.o …. Linker C++ compiler does not care about filenames. application (executable)
Classes • High level concepts are same as Java – details are bit different. • Example: Complex Numbers • Unlike Java, • C++ compiler does not care about filenames. • C++ uses 2 files for each class: one header (.h) file for definition, another source file (.cpp) for implementation • Need to use “#include ….h” to use any class.
Concepts: Constructor • Constructor • mostly similar to Java • Exception: default values for formal parameters
Concepts: Operator overloading • Operator overloading: ComplexNumber x, y, z; z = x + y; • In Java?
Concepts: Pass by value or reference • Passing parms by value or reference • User selection • const keyword for reference types • Java? • Method overloading – similar to Java • use different argument types to differentiate
Concepts: Method overloading • Method overloading – similar to Java • use different argument types to differentiate
Concepts: Friend • friend designation - breaks OOP philosophy! • specific functions/methods outside the class can access private data Why?
Concepts: Objects • Objects can be created as local variables just like any basic data types. ComplexNumber num1;
Arrays • Basic data types and classes are treated the same way in C++, unlike Java. ComplexNumber numbers[5];
Array version #2 ComplexNumber *numbers; numbers = new ComplexNumber[5];
Array version #3 (equivalent to Java) ComplexNumber **numbers; numbers = new ComplexNumber*[5]; for( index i = 0 ; i < 5 ; i++) numbers[i] = new ComplexNumber(…);
Pointers • Explicit in C++: ComplexType *cnump; • Pointer arithmetic: (cnump + 5) • “Address of” operator: & • Dereference operator for objects: -> cnump->setComplex(…); • Dynamic memory allocation requires pointers (just like references in Java)
Dynamic memory allocation • No automatic garbage collection in C++ • # of new invocations should match # of delete invocations. • If a class constructor allocates memory (i.e. uses “new …”), it needs a destructor method too – it should use “delete …” to release allocated memory.