HP C/aC++ for PA-RISC Software manual Overloaded Operations ++, Reference Initialization

Page 216

b.g();

// Error?

}

The ambiguity in the example code is whether b is declared as:

A function with one argument (named p) returning an object of type B.

An object of type B initialized with a temporary object of type A.

HP C++ compiles this code successfully and assumes b is an object. Compiling the code with HP aC++ generates the following error:

Error: File “objDeclaration.c”, Line 5

Left side of ‘.’ requires a class object; type found was a function ‘B (A)’. Did you try to declare an object with a nested constructor call?

Such a declaration is interpreted as a function declaration B b(A) [File “objDeclaration.c, Line 4].

Modify the code as shown below to successfully compile it with both compilers.

struct A {A(int);};

struct B {B(const A &); void g();};

void

f(int p) {

 

 

 

B

b = A(p);

//

declaration

of object

b.g();

//

method call

 

}

 

 

 

 

Overloaded Operations ++ and --

You must use the overloaded operations ++ and --correctly. These operations require a member function with one argument. If the function has no argument, a warning is issued and a postfic is assumed in HP C++. In HP aC++, the inconsistency between the overloaded function usage and definition is considered an error. To avoid this error, change the class definition so that each overloaded function definition has the correct number of arguments.

Example:

class T { public:

T();

const T& operator++ ();

};

int main () {

Tt;

t++;

}

Compiling the above code with HP C++ generates the following warning:

CC:"pre.C", Line 8: warning: prefix ++/-- used as postfix (anachronism) (935)

Compiling the code with HP aC++ generates an error like the following:

Error 184: File “pre.C”, Line 8

Arithmetic or pointer type expected for operator ‘++’; type found was ‘T’.

To compile the code with HP C++ or HP aC++ use the following class definition:

class T { public:

T();

const T& operator++ (); // prefix old style postfix definition const T& operator++ (int); // postfix

};

Reference Initialization

Illegal reference initialization is no longer allowed. In HP C++, a warning is generated stating that the initializer for a non-constant reference is not an lvalue (anachronism). In HP aC++, an illegal

216 Migrating from HP C++ (cfront) to HP aC++

Image 216
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Pragma Directives and Attributes Initialization and Termination PragmasCopyright Notice and Identification Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Using HP aC++ Templates 132 Standardizing Your Code 138Optimizing HP aC++ Programs 156 Exception Handling 161Tools and Libraries 175 170Mixing C++ with Other Languages 188 Distributing Your C++ Products 195 Migrating from HP C++ cfront to HP aC++ 198Strings 194 Arrays Files in Fortran Documentation feedback 221 Diagnostic Messages 222 Glossary 223 Index 227HP secure development lifecycle About This Document Intended AudienceWhat’s in This Document Typographical Conventions This document uses the following conventionsPublishing History Related DocumentsHP-UX Release Name and Release Identifier HP-UX 11i ReleasesHP Encourages Your Comments Following is a list of documents available with this releaseGetting Started with HP aC++ Components of the Compilation SystemC89 C99 ecom Ctcom Other HP aC++ executable files areUsing the aCC Command Compiling a Simple ProgramExecuting the Program Debugging ProgramsCompiler Command Syntax and Environmental Variables Examples of the aCC CommandFiles on the aCC Command Line Assembly Language Source Files .s Files++ Source File .C file Preprocessed Source Files .i FilesConfiguration Files .conf Files Environment VariablesObject Files .o Files Library Files .a and .so FilesACCFULLPATHNAMES Environment Variable ACCMAXERR Environment VariableCxxopts Environment Variable Cclibdir Environment VariableCcrootdir Environment Variable ACC -L/mnt/proj/lib file.o ACC file.oFloating Installation Cxxmapfile Environment VariableTmpdir Environment Variable Export CCROOTDIR=/mnt/CXX2.1Setting up Floating Installation HP aC++Command-Line Options Options to Control Code Generation ACC -c sub.C prog.CACC +DO11.22 +O3 app.C ILP32 Data Model and LP64 Data ModelUsing +DS to Specify Instruction Scheduling Compiling in Networked EnvironmentsData Alignment and Storage ACC -S prog.CSize and Alignment of HP Compiler Data Types Debugging Options Fshort-enums+expandtypesindiag ACC +u1 app.CWhen to use -g, -g0, and -g1 Differences Between -g, -g0, and -g1 OptionsG1 Algorithm +macrodebug+noobjdebug +pathtrace+pathtrace=kind LocalError Handling None+pathtrace=globallocal ACC +p file.C+wn +Wargs+Wcontextlimit +wperfadvice +We+Weargs +WvException Handling Extensions to the Language+wsecurity +noeh+Onofenvaccess Floating-Point Processing Options+Onocxlimitedrange Fpeval FpevaldecNofpwidetypes +decfp+FPmode +Onolibmerrno+Oprefetchlatency +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs Online Help Option +helpInlining Options +inlinelevel numLibrary Options DynamicExec LnameLinker Options Minshared+nostl +Onolibcalls=Usymbol Usymbol+Onodynopt +OnodynoptOptions for Naming the Output File Native Language Support Option+ild +ildrelinkHandling Null Pointers Options Code Optimizing OptionsBasic Optimization Level Options ACC -z file.C+O0 +O1+O2 +O3Additional Optimization Options for Finer Control +O4ACC +O3 prog.C +O4Ipo +nonrv+Onofailsafe Advanced +Ooptimization Options +Onoaggressive+Onolimit +Onoptrstoglobals=list+Onocrossregionaddressing +Onodatalayout+Onodataprefetch +Onofltacc+Ofrequentlycalled +Onoinitcheck+Onoinline +Olit+Ointegeroverflow +Olevel +Onolooptransform+Onoloopunroll +Onoopenmp+opts +Onoparminit+Onoparmsoverlap +Onoprocelim+Orarelycalled +Onosignedpointers+Oshortdata +Otypesafety Profile-Based Optimization Options+Onostoreordering +OunrollfactorParallel Processing Options Information Embedding OptionsDisplaying Optimization Information Annotate=structsOption Matrix for -mt Required if -DPOSIXCSOURCEis used+Onoautopar +tls=staticdynamicPerformance Options +wlockFast +Ofast+Ofaster +Onotlscallschangetp+nosrcpos +DSmodelPorting Options +sb+ub +uc+w64bit +wdriver+wendian This warning can be suppressed by adding an extra castPreprocessor Options DnameRedirecting Output From This Option Maked +Maked+maked ExamplesProfiling Code Options Uname+profilebucketsize Runtime Checking Options +check+check=all +check=none+check=boundsarray +check=boundspointer Compiling with +check=boundspointerCheck off by one out-of-bounds access Check off by any number out-of-bounds access+check=globals +check=lock+check=malloc +check=stackframevariablesnone +check=thread+check=truncateexplicitimplicit +check=uninitCh = intval & 0xff +check=truncateexplicit +check=truncateimplicitStandards Related Options AarmAarm AC89 AC99Ag++ AgccAOa and -AOe +legacycpp+legacyv5 +std=c89c99c++98c++11gccg++gnu +stl=rwnone+tru64 Wc,-ansiforscope,onoffWc,-koeniglookup,onoff +tru64Subprocesses of the Compiler Tx,nameMore Examples of -t Tx,nameWx,args Symbol Binding Options BdefaultBextern Passing Options to the Linker with -WBhidden BhiddendefBprotected BprotecteddataTemplate Options Trigraph Processing Suppression Option +instincludesuffixesVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r Concatenating Options ACC -V app.CACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Pragma Directives and Attributes Initialization and Termination PragmasCopyright Notice and Identification Pragmas Data Alignment Pragmas #pragma Versionid string#pragma Versionid Software Product, Version 12345.A.01.05 #pragma align NData Alignment Pragmas Basic Example Template ExampleImplicit Access to Unaligned Data Handling Unaligned Data#pragma unalign Typedef T1 T2 Interaction between pack and unalign pragmas is as followsOptimization Pragmas Optlevel PragmaOptimize Pragma Floattrapson PragmaNoinline Pragma Diagnostic Pragmas Other PragmasDefaultbinding Pragma Binding PragmaEstimatedfrequency Pragma Extern PragmaHdrstop Pragma Hidden PragmaHpdefinedexternal Pragma Hpdefinedinternal PragmaPOP Pragma Pragma onceProtected Pragma Ptrsstronglytyped Pragma#pragma Stdc FLOATCONSTDECIMAL64 on OFF Default Stdc Cxlimitedrange PragmaStdc FLOATCONSTDECIMAL64 Pragma Stdc Fpcontract PragmaStdc Fenvaccess Pragma Unrollfactor PragmaOMP Atomic Pragma OMP Barrier Pragma OMP Critical PragmaOMP for Pragma OMP Flush PragmaOMP Master Pragma OMP Ordered PragmaOMP Parallel Pragma OMP Parallel for PragmaOMP Parallel Sections Pragma OMP Sections PragmaOMP Single Pragma OMP Task PragmaOpenMP Clauses Default CopyprivateShared CopyinAttributes Attribute nonexposing Attribute noreturnAttribute nonexposing Attribute noreturnAttribute format Attribute visibilityAttribute warnunusedresult Preprocessing Directives Overview of the PreprocessorSyntax Usage GuidelinesSource File Inclusion #include, #includenext SyntaxDescription Assertions #assert, #unassertMacro Replacement #define, #undef #define mac very very long\ Replacement stringExamples Macros with ParametersSpecifying String Literals with the # Operator Concatenating Tokens with the ## OperatorExample Following illustrates the ## operatorUsing Macros to Define Constants Other MacrosVar1 is #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Assertions #assert, #unassert Predefined MacrosConditional Compilation #if, #ifdef, .. #endif HP aC++ predefines the following predicatesCode that compiles if the expression evaluates to zero Using the defined Operator Using the #if DirectiveUsing the #ifdef and #ifndef Directives Using the #else DirectiveLine Control #line Example#line 5 myfile This macro enables the following non-standard features Iostream Performance Improvement PragmaPragma Directive #pragma and Pragma Operator See page 96 for more information on pragmasError Directive #error Trigraph SequencesExamples Line below contains the trigraph sequence ??=When this line is compiled it becomes ??=line 5 myfileUsing HP aC++ Templates Invoking Compile-Time InstantiationScope and Precedence Template ProcessingExplicit Instantiation UsagePerformance Template class TablecharCommand-Line Option Instantiation Compile-Time InstantiationFunction Template ACC -c +instcompiletime a.C ACC -c a.CWhy Use Compile-Time Instantiation Possible Duplicate Symbols in Shared LibrariesPossible Duplicate Symbols in Archive Libraries Scope++ Template Tutorial Class TemplatesBuilding an Archive Library with +instauto/+instclose Building an Archive Library with Compile-time InstantiationFunction Templates Standardizing Your Code HP aC++ KeywordsBool Keyword HP aC++ KeywordsCompile time error message is Dynamiccast KeywordAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Namespace and using Keywords Connections Across Translation UnitsUsing- declarations and using- directives Using Nx // Where N is a namespace, x is a name in NAn Auxiliary Translation Unit IntPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Wchart Keyword Template KeywordTypename Keyword Overloading new and delete for Arrays Use it as the name of the template C belowDeclare a class as a member of the class template C2 below Example Rangeerror Standard Exception ClassesInvalidargument Exceptions Thrown by the Standard C++ Library Typeinfo ClassFollowing exceptions are thrown by the Standard C++ Library Unsupported Functionality Int before const typeinfo& constMemfun1reft Memfunreft Iostream Setting Basic Optimization Levels Optimizing HP aC++ ProgramsRequesting Optimization Level 1 OptimizationAdditional Options for Finer Control Level 3 OptimizationLevel 4 Optimization Enabling Aggressive OptimizationsRemoving Compilation Time Limits When Optimizing Profile-Based OptimizationEnabling Only Conservative Optimizations Limiting the Size of Optimized CodeInstrumentation Collecting Data for ProfilingMaintaining Profile Data Files Sample.exe input.file1 Sample.exe input.file2Pragmas That Control Optimization Performing Profile-Based OptimizationACC -o sample.exe +Oprofile=use +O3 sample.C See Optimization Pragmas page 103 for more informationException Handling Exception Handling in C++Basic Exception Handling Example Function Try Block ExamplesUsing Threads Using LocksDebugging Exception Handling Performance Considerations Rogue Wave Standard C++ LibraryRequired Command-line Options Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library 1.2.1 and Tools.h++ LpthreadThis option applies only to kernel threadsUsing -DTHREADSAFE with the cfront Compatible libstream Using -DHPACCTHREADSAFERBTREELimitations Cout endlPthreads Posix Threads Exception HandlingACC -mt prog.c Parallel Programming Using OpenMP Function ScopingOpenMP Implementation OpenMP Header File OpenMP LibraryOpenMP APIs are defined in the library libomp +Onoopenmp Command Line Option Environment Variables in OpenMPOpenmp Macro Where, kind is either of of static, dynamic, or guidedRuntime Library Functions in OpenMP Execution Environment FunctionsExport OMPDYNAMIC=value Setenv Ompdynamic value Export OMPNESTED=value Setenv Ompnested valueOmpsetnumthreads OmpgetnumthreadsOmpgetmaxthreads OmpgetthreadnumLock Functions OmpsetdynamicOmpgetdynamic OmpsetnestedOmpinitlock and ompinitnestlock Ompdestroylock and ompdestroynestlockOmpsetlock and ompsetnestlock Ompunsetlock and ompunsetnestlockTiming Functions Omptestlock and omptestnestlock FunctionsOmpgetwtime OmpgetwtickHP Specific Features of lex and yacc Creating and Using LibrariesTools and Libraries Locale directive for lexIntroduction to Using the Standard C++ Library HP aC++ LibrariesStandard C++ Library IntroductionDifferences between Standard C++ Library and Other Libraries Non-Object-Oriented Design of the Standard C++ LibraryStandard C++ Library Reference Incompatibilities Between the Library and the StandardACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.c Tools.h++ LibraryHP aC++ Runtime Support Library IOStream LibraryCreating and Using Shared Libraries Linking to C++ LibrariesLinking with Shared or Archive Libraries Specifying Other LibrariesUsing a Shared Library Example of Creating and Using a Shared LibraryCreating a Shared Library Linking Archive or Shared LibrariesAdvanced Shared Library Features Forcing the Export of Symbols in mainUpdating a Shared Library Binding Times Side Effects of C++ Shared LibrariesRoutines and Options to Manage C++ Shared Libraries Linker Options to Manage Shared LibrariesStandard HP-UX Libraries and Header Files Allocation Policies for ContainersFor -AA Standard Library For a string typeHP aC++ File Locations HP aC++ Executable FilesHP aC++ Runtime Libraries and Header Files Usr/lib/hpux##/libCsup.soUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant Mixing C++ with Other Languages Calling Other LanguagesData Compatibility between C and C++ Using the extern C Linkage Specification HP aC++ Calling HP CSyntax of extern C Examples of extern CDifferences in Argument Passing Conventions Main FunctionExamples HP aC++ Calling HP C HP C Calling HP aC++ Running the ExampleEnter the nameJoann Joann has a balance To compile the example, run the following commands Compiling and Running the Sample ProgramsUsing Reference Variables to Pass Arguments Calling HP Fortran 90 from HP aC++Function Naming Conventions Example of Reference Variables as ArgumentsUsing extern C Linkage StringsArrays Files in FortranDistributing Your C++ Products Applications that use HP aC++ Shared LibrariesInstalling your Application Linking Your HP aC++ Libraries with Other LanguagesHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files Migrating from HP C++ cfront to HP aC++ General Guidelines for MigrationGetting Started with Migration CC +p cfrontfile.CCommand-Line Differences New Command-Line OptionsWriting Code for both Compilers Explicit Loading and Unloading of Shared LibrariesObsolete Command-Line Options Describes obsolete command-line options for HP aC++Changed Command-Line Options PtvMigration Considerations when Debugging Migration Considerations when Using Exception HandlingException Handling is the Default See Debugging Options page 35 for complete informationPossible Differences when Exiting a Signal Handler Memory Allocation Failure and operator newDifferences in setjmp/longjmp Behavior Calling unexpectedUnreachable catch Clauses Throwing an Object having an Ambiguous Base ClassMigration Considerations when Using Libraries Standards Based LibrariesHP C++ cfront Compatibility Libraries Fstream3C++ iostream and streambuf specialized to filesManip3C++ iostream manipulators Man 3s filebufMigration Considerations Related to Preprocessing HP C++ cfront Complex Library Not SupportedHP C++ cfront Task Library Not Supported Replace #include with complexMigration Considerations Related to Standardization Obsolete Preprocessor OptionsChanges in C++ Semantics Implicit Typing of Character String LiteralsOverload Resolution Ambiguity of Subscripting Operator Execution Order of Static Constructors in Shared LibrariesChanges in C++ Syntax More Frequent Inlining of Inline CodeExplicit int Declaration For Statement, New Scoping Rules Struct as Template Type Parameter is PermittedEquivalent, valid HP aC++ code follows WC,-ansiforscope,onThis code compiles without error with HP aC++ Base Template Class Reference Syntax ChangeTokens after #endif Overload not a KeywordDangling Comma in enum Static Member Definition RequiredDeclaring friend Classes Using in Class Definitions Incorrect Syntax for Calls to operator newDuplicate Formal Argument Names Ambiguous Function or Object DeclarationOverloaded Operations ++ Reference InitializationUsing operator new to Allocate Arrays On HP aC++, the following error is generatedCompiling this code HP aC++ generates the following error Parentheses in Static Member Initialization ListQualified-id Required in Static Member Initialization List Non-constant Reference InitializationMigration Considerations when Using Templates Verbose Template Processing InformationDigraph White Space Separators CA aConverting Directed Mode to Explicit Instantiation Common Template Migration Syntax ChangesCfront Implicit Include Convention Documentation feedback Diagnostic Messages AC++ Message CatalogFrequently Encountered Messages Glossary AggressiveInternational Standard defines only synchronous exceptions See template Glossary Symbols IndexCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb