Arrays, Functions, and Return Values

As in C, the declared return type of a function cannot be array (e.g., it cannot look like int[] or char[] or Point[]). Returning (addresses to) arrays from functions that are pointer-typed is allowed. However, this is not recommended in the public interface of a class.

An array is a piece of unprotected memory. A class that encapsulates that memory should not have public member functions that return pointers to it. Doing so opens up the possibility for incorrect use of the memory by client code. A properly designed class completely encapsulates all interactions with any arrays used in the implementation of that class.

Arrays are never passed to functions by valuethe array elements will not be copied. If a function is called with an array in its argument list, for example,

int a[] = {10, 11, 12, 13, 14, 15};
[ ... ]
f(a[]);
[ ... ]

then the array expression is interpreted as a pointer to the first element in the array.

Example 22.5. src/arrays/returningpointers.cpp

#include 

int paramSize;

void bar(int *integers) {
 integers[2]=3; <-- 1
}

int* foo(int arrayparameter[]) {
 using namespace std;
 paramSize = sizeof(arrayparameter);
 bar(arrayparameter); <-- 2
 return arrayparameter; <-- 3
}

int main(int argc, char** argv) {
 int intarray2[40] = {9,9,9,9,9,9,9,2,1};
 char chararray[20] = "Hello World"; <-- 4
 int intarray1[20]; <-- 5
 int* retval; <-- 6

// intarray1 = foo(intarray2); <-- 7

 retval = foo(intarray2);
 assert (retval[2] == 3);
 assert (retval[2] = intarray2[2]);
 assert (retval == intarray2);
 int refSize = getSize(intarray2);
 assert(refSize == paramSize);
 return 0;
}
 

(1)Change the third element in the incoming array.

(2)Pass an array by pointer to a function.

(3)Return an array as a pointer from a function.

(4)special syntax for initializing char array

(5)uninitialized memory

(6)uninitialized pointer

(7)Errorintarray1 is like a // char* const. It cannot be assigned to.


Part I: Introduction to C++ and Qt 4

C++ Introduction

Classes

Introduction to Qt

Lists

Functions

Inheritance and Polymorphism

Part II: Higher-Level Programming

Libraries

Introduction to Design Patterns

QObject

Generics and Containers

Qt GUI Widgets

Concurrency

Validation and Regular Expressions

Parsing XML

Meta Objects, Properties, and Reflective Programming

More Design Patterns

Models and Views

Qt SQL Classes

Part III: C++ Language Reference

Types and Expressions

Scope and Storage Class

Statements and Control Structures

Memory Access

Chapter Summary

Inheritance in Detail

Miscellaneous Topics

Part IV: Programming Assignments

MP3 Jukebox Assignments

Part V: Appendices

MP3 Jukebox Assignments

Bibliography

MP3 Jukebox Assignments



An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net