HP C/aC++ for PA-RISC Software manual Explicit Keyword

Page 141

class Base1 {

//Not a polymorphic type.

//additional class details omitted

};

 

class Base2 {

 

virtual void f();

// Make Base2 polymorphic.

//additional class details

//omitted

};

void Base2::f()

{

// Define Base2 function.

}

class Derived : public virtual Base1, public virtual Base2 { // additional class details omitted

};

int main()

{

Base1 *bp1; Base2 *bp2; Derived *dp;

bp1 = new Derived; bp2 = new Derived;

// dp = (Derived *) bp1;

//Problem: compile time error

//Can’t cast from virtual base.

// dp = (Derived *) bp2;

//Problem: compile time error

//Can’t cast from virtual base.

//dp = dynamic_cast<Derived *> bp1;

//Problem: compile time error

//Can’t cast from

//non-polymorphic type.

dp = dynamic_cast<Derived *> bp2;

// OK

}

 

explicit Keyword

explicit Keyword

The explicit keyword is used for declaring constructor functions within class declarations. When these functions are declared explicit, they cannot be used for implicit conversions.

Usage

While constructors taking one argument are often useful in the design of a class, they can allow inadvertent conversion in expressions. This can introduce subtle bugs. The explicit keyword allows a class designer to prohibit such implicit conversions. It is often used in the production of class libraries.

Example

class C { public:

HP aC++ Keywords 141

Image 141
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Standardizing Your Code 138 Using HP aC++ Templates 132Exception Handling 161 Optimizing HP aC++ Programs 156170 Tools and Libraries 175Mixing C++ with Other Languages 188 Distributing Your C++ Products 195 Migrating from HP C++ cfront to HP aC++ 198Strings 194 Arrays Files in Fortran Glossary 223 Index 227 Documentation feedback 221 Diagnostic Messages 222HP secure development lifecycle About This Document Intended AudienceWhat’s in This Document This document uses the following conventions Typographical ConventionsRelated Documents Publishing HistoryHP-UX Release Name and Release Identifier HP-UX 11i ReleasesFollowing is a list of documents available with this release HP Encourages Your CommentsComponents of the Compilation System Getting Started with HP aC++C89 C99 ecom Ctcom Other HP aC++ executable files areCompiling a Simple Program Using the aCC CommandExecuting the Program Debugging ProgramsExamples of the aCC Command Compiler Command Syntax and Environmental VariablesAssembly Language Source Files .s Files Files on the aCC Command Line++ Source File .C file Preprocessed Source Files .i FilesEnvironment Variables Configuration Files .conf FilesObject Files .o Files Library Files .a and .so FilesACCMAXERR Environment Variable ACCFULLPATHNAMES Environment VariableCxxopts Environment Variable Cclibdir Environment VariableACC -L/mnt/proj/lib file.o ACC file.o Ccrootdir Environment VariableCxxmapfile Environment Variable Floating InstallationTmpdir Environment Variable Export CCROOTDIR=/mnt/CXX2.1HP aC++ Setting up Floating InstallationCommand-Line Options ACC -c sub.C prog.C Options to Control Code GenerationACC +DO11.22 +O3 app.C ILP32 Data Model and LP64 Data ModelCompiling in Networked Environments Using +DS to Specify Instruction SchedulingData Alignment and Storage ACC -S prog.CSize and Alignment of HP Compiler Data Types Fshort-enums Debugging Options+expandtypesindiag ACC +u1 app.CDifferences Between -g, -g0, and -g1 Options When to use -g, -g0, and -g1G1 Algorithm +macrodebug+pathtrace +noobjdebug+pathtrace=kind LocalNone Error Handling+pathtrace=globallocal ACC +p file.C+wn +Wargs+Wcontextlimit +We +wperfadvice+Weargs +WvExtensions to the Language Exception Handling+wsecurity +noeh+Onofenvaccess Floating-Point Processing Options+Onocxlimitedrange Fpevaldec FpevalNofpwidetypes +decfp+Onolibmerrno +FPmode+Oprefetchlatency +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs +help Online Help Option+inlinelevel num Inlining OptionsDynamic Library OptionsExec LnameMinshared Linker Options+nostl +Onolibcalls=Usymbol Usymbol+Onodynopt +OnodynoptNative Language Support Option Options for Naming the Output File+ild +ildrelinkCode Optimizing Options Handling Null Pointers OptionsBasic Optimization Level Options ACC -z file.C+O1 +O0+O2 +O3+O4 Additional Optimization Options for Finer ControlACC +O3 prog.C +O4Ipo +nonrv+Onofailsafe +Onoaggressive Advanced +Ooptimization Options+Onolimit +Onoptrstoglobals=list+Onodatalayout +Onocrossregionaddressing+Onodataprefetch +Onofltacc+Onoinitcheck +Ofrequentlycalled+Onoinline +Olit+Ointegeroverflow +Onolooptransform +Olevel+Onoloopunroll +Onoopenmp+Onoparminit +opts+Onoparmsoverlap +Onoprocelim+Orarelycalled +Onosignedpointers+Oshortdata Profile-Based Optimization Options +Otypesafety+Onostoreordering +OunrollfactorInformation Embedding Options Parallel Processing OptionsDisplaying Optimization Information Annotate=structsRequired if -DPOSIXCSOURCEis used Option Matrix for -mt+tls=staticdynamic +Onoautopar+wlock Performance OptionsFast +Ofast+Onotlscallschangetp +Ofaster+nosrcpos +DSmodel+sb Porting Options+ub +uc+wdriver +w64bit+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 +check Runtime Checking Options+check=all +check=noneCompiling with +check=boundspointer +check=boundsarray +check=boundspointerCheck off by any number out-of-bounds access Check off by one out-of-bounds access+check=lock +check=globals+check=malloc +check=thread +check=stackframevariablesnone+check=uninit +check=truncateexplicitimplicitCh = intval & 0xff +check=truncateexplicit +check=truncateimplicitStandards Related Options AarmAarm AC99 AC89Ag++ AgccAOa and -AOe +legacycpp+legacyv5 +stl=rwnone +std=c89c99c++98c++11gccg++gnuWc,-ansiforscope,onoff +tru64Wc,-koeniglookup,onoff +tru64Tx,name Subprocesses of the CompilerMore Examples of -t Tx,nameWx,args Bdefault Symbol Binding OptionsBextern Passing Options to the Linker with -WBhiddendef BhiddenBprotected BprotecteddataTemplate Options +instincludesuffixes Trigraph Processing Suppression OptionVerbose 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 Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas #pragma Versionid string Data Alignment Pragmas#pragma Versionid Software Product, Version 12345.A.01.05 #pragma align NData Alignment Pragmas Template Example Basic ExampleHandling Unaligned Data Implicit Access to Unaligned DataInteraction between pack and unalign pragmas is as follows #pragma unalign Typedef T1 T2Optlevel Pragma Optimization PragmasOptimize Pragma Floattrapson PragmaNoinline Pragma Other Pragmas Diagnostic PragmasBinding Pragma Defaultbinding PragmaEstimatedfrequency Pragma Extern PragmaHidden Pragma Hdrstop PragmaHpdefinedexternal Pragma Hpdefinedinternal PragmaPragma once POP PragmaProtected Pragma Ptrsstronglytyped PragmaStdc Cxlimitedrange Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc FLOATCONSTDECIMAL64 Pragma Stdc Fpcontract PragmaStdc Fenvaccess Pragma Unrollfactor PragmaOMP Atomic Pragma OMP Critical Pragma OMP Barrier PragmaOMP for Pragma OMP Flush PragmaOMP Ordered Pragma OMP Master PragmaOMP Parallel Pragma OMP Parallel for PragmaOMP Sections Pragma OMP Parallel Sections PragmaOMP Single Pragma OMP Task PragmaOpenMP Clauses Copyprivate DefaultShared CopyinAttributes Attribute noreturn Attribute nonexposingAttribute nonexposing Attribute noreturnAttribute format Attribute visibilityAttribute warnunusedresult Overview of the Preprocessor Preprocessing DirectivesSyntax Usage GuidelinesSyntax Source File Inclusion #include, #includenextDescription Assertions #assert, #unassert#define mac very very long\ Replacement string Macro Replacement #define, #undefExamples Macros with ParametersConcatenating Tokens with the ## Operator Specifying String Literals with the # OperatorExample Following illustrates the ## operatorOther Macros Using Macros to Define ConstantsVar1 is #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Predefined Macros Assertions #assert, #unassertConditional Compilation #if, #ifdef, .. #endif HP aC++ predefines the following predicatesCode that compiles if the expression evaluates to zero Using the #if Directive Using the defined OperatorUsing the #ifdef and #ifndef Directives Using the #else DirectiveLine Control #line Example#line 5 myfile Iostream Performance Improvement Pragma This macro enables the following non-standard featuresPragma Directive #pragma and Pragma Operator See page 96 for more information on pragmasTrigraph Sequences Error Directive #errorExamples Line below contains the trigraph sequence ??=??=line 5 myfile When this line is compiled it becomesInvoking Compile-Time Instantiation Using HP aC++ TemplatesScope and Precedence Template ProcessingUsage Explicit InstantiationPerformance Template class TablecharCompile-Time Instantiation Command-Line Option InstantiationFunction Template ACC -c +instcompiletime a.C ACC -c a.CPossible Duplicate Symbols in Shared Libraries Why Use Compile-Time InstantiationPossible Duplicate Symbols in Archive Libraries ScopeClass Templates ++ Template TutorialBuilding an Archive Library with +instauto/+instclose Building an Archive Library with Compile-time InstantiationFunction Templates HP aC++ Keywords Standardizing Your CodeBool Keyword HP aC++ KeywordsDynamiccast Keyword Compile time error message isAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Connections Across Translation Units Namespace and using KeywordsUsing Nx // Where N is a namespace, x is a name in N Using- declarations and using- directivesAn 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 Int before const typeinfo& const Unsupported FunctionalityMemfun1reft Memfunreft Iostream Optimizing HP aC++ Programs Setting Basic Optimization LevelsRequesting Optimization Level 1 OptimizationLevel 3 Optimization Additional Options for Finer ControlLevel 4 Optimization Enabling Aggressive OptimizationsProfile-Based Optimization Removing Compilation Time Limits When OptimizingEnabling Only Conservative Optimizations Limiting the Size of Optimized CodeCollecting Data for Profiling InstrumentationMaintaining Profile Data Files Sample.exe input.file1 Sample.exe input.file2Performing Profile-Based Optimization Pragmas That Control OptimizationACC -o sample.exe +Oprofile=use +O3 sample.C See Optimization Pragmas page 103 for more informationException Handling in C++ Exception HandlingFunction Try Block Examples Basic Exception Handling ExampleUsing Locks Using ThreadsDebugging Exception Handling Performance Considerations Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library Required Command-line OptionsRogue Wave Standard C++ Library 1.2.1 and Tools.h++ LpthreadThis option applies only to kernel threadsUsing -DHPACCTHREADSAFERBTREE Using -DTHREADSAFE with the cfront Compatible libstreamLimitations 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 Environment Variables in OpenMP +Onoopenmp Command Line OptionOpenmp Macro Where, kind is either of of static, dynamic, or guidedExecution Environment Functions Runtime Library Functions in OpenMPExport OMPDYNAMIC=value Setenv Ompdynamic value Export OMPNESTED=value Setenv Ompnested valueOmpgetnumthreads OmpsetnumthreadsOmpgetmaxthreads OmpgetthreadnumOmpsetdynamic Lock FunctionsOmpgetdynamic OmpsetnestedOmpdestroylock and ompdestroynestlock Ompinitlock and ompinitnestlockOmpsetlock and ompsetnestlock Ompunsetlock and ompunsetnestlockOmptestlock and omptestnestlock Functions Timing FunctionsOmpgetwtime OmpgetwtickCreating and Using Libraries HP Specific Features of lex and yaccTools and Libraries Locale directive for lexHP aC++ Libraries Introduction to Using the Standard C++ LibraryStandard C++ Library IntroductionNon-Object-Oriented Design of the Standard C++ Library Differences between Standard C++ Library and Other LibrariesIncompatibilities Between the Library and the Standard Standard C++ Library ReferenceTools.h++ Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cHP aC++ Runtime Support Library IOStream LibraryLinking to C++ Libraries Creating and Using Shared LibrariesLinking with Shared or Archive Libraries Specifying Other LibrariesExample of Creating and Using a Shared Library 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 Side Effects of C++ Shared Libraries Binding TimesRoutines and Options to Manage C++ Shared Libraries Linker Options to Manage Shared LibrariesAllocation Policies for Containers Standard HP-UX Libraries and Header FilesFor a string type For -AA Standard LibraryHP aC++ Executable Files HP aC++ File LocationsHP 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++ HP aC++ Calling HP C Using the extern C Linkage SpecificationSyntax 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 Compiling and Running the Sample Programs To compile the example, run the following commandsCalling HP Fortran 90 from HP aC++ Using Reference Variables to Pass ArgumentsFunction Naming Conventions Example of Reference Variables as ArgumentsStrings Using extern C LinkageArrays Files in FortranApplications that use HP aC++ Shared Libraries Distributing Your C++ ProductsInstalling your Application Linking Your HP aC++ Libraries with Other LanguagesHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files General Guidelines for Migration Migrating from HP C++ cfront to HP aC++Getting Started with Migration CC +p cfrontfile.CNew Command-Line Options Command-Line DifferencesWriting Code for both Compilers Explicit Loading and Unloading of Shared LibrariesDescribes obsolete command-line options for HP aC++ Obsolete Command-Line OptionsPtv Changed Command-Line OptionsMigration Considerations when Using Exception Handling Migration Considerations when DebuggingException Handling is the Default See Debugging Options page 35 for complete informationMemory Allocation Failure and operator new Possible Differences when Exiting a Signal HandlerCalling unexpected Differences in setjmp/longjmp BehaviorThrowing an Object having an Ambiguous Base Class Unreachable catch ClausesStandards Based Libraries Migration Considerations when Using LibrariesFstream3C++ iostream and streambuf specialized to files HP C++ cfront Compatibility LibrariesManip3C++ iostream manipulators Man 3s filebufHP C++ cfront Complex Library Not Supported Migration Considerations Related to PreprocessingHP C++ cfront Task Library Not Supported Replace #include with complexObsolete Preprocessor Options Migration Considerations Related to StandardizationChanges in C++ Semantics Implicit Typing of Character String LiteralsExecution Order of Static Constructors in Shared Libraries Overload Resolution Ambiguity of Subscripting OperatorChanges in C++ Syntax More Frequent Inlining of Inline CodeExplicit int Declaration Struct as Template Type Parameter is Permitted For Statement, New Scoping RulesEquivalent, valid HP aC++ code follows WC,-ansiforscope,onBase Template Class Reference Syntax Change This code compiles without error with HP aC++Tokens after #endif Overload not a KeywordDangling Comma in enum Static Member Definition RequiredDeclaring friend Classes Incorrect Syntax for Calls to operator new Using in Class DefinitionsDuplicate Formal Argument Names Ambiguous Function or Object DeclarationReference Initialization Overloaded Operations ++On HP aC++, the following error is generated Using operator new to Allocate ArraysCompiling this code HP aC++ generates the following error Parentheses in Static Member Initialization ListNon-constant Reference Initialization Qualified-id Required in Static Member Initialization ListVerbose Template Processing Information Migration Considerations when Using TemplatesDigraph 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 Aggressive GlossaryInternational Standard defines only synchronous exceptions See template Glossary Index SymbolsCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb