C++, Visual C++, and Managed C++: What s the Difference?

Similar documents
Creating Test Harnesses and Starter Applications

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

One advantage that SONAR has over any other music-sequencing product I ve worked

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

Python Programming: An Introduction to Computer Science

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Appendix D. Controller Implementation

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago

n Explore virtualization concepts n Become familiar with cloud concepts

CS 11 C track: lecture 1

n We have discussed classes in previous lectures n Here, we discuss design of classes n Library design considerations

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

MOTIF XF Extension Owner s Manual

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

CMPT 125 Assignment 2 Solutions

IMP: Superposer Integrated Morphometrics Package Superposition Tool

Python Programming: An Introduction to Computer Science

. Written in factored form it is easy to see that the roots are 2, 2, i,

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5.

1 Enterprise Modeler

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

COP4020 Programming Languages. Compilers and Interpreters Prof. Robert van Engelen

The Magma Database file formats

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

Baan Tools User Management

From last week. Lecture 5. Outline. Principles of programming languages

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Elementary Educational Computer

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

n Learn how resiliency strategies reduce risk n Discover automation strategies to reduce risk

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

BEA Tuxedo. Using the BEA Tuxedo System on Windows NT

Guide to Applying Online

Web OS Switch Software

JavaFX. JavaFX 2.2 Installation Guide Release 2.2 E August 2012 Installation instructions by operating system for JavaFX 2.

Workflow model GM AR. Gumpy. Dynagump. At a very high level, this is what gump does. We ll be looking at each of the items described here seperately.

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

BAAN IVc/BaanERP. Conversion Guide Oracle7 to Oracle8

Ones Assignment Method for Solving Traveling Salesman Problem

Chapter 4 Threads. Operating Systems: Internals and Design Principles. Ninth Edition By William Stallings

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Overview Chapter 12 A display model

Definitions. Error. A wrong decision made during software development

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

BEA Tuxedo. Creating CORBA Server Applications

Lecture 28: Data Link Layer

The VSS CCD photometry spreadsheet

Weston Anniversary Fund

Transitioning to BGP

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

3.1 Overview of MySQL Programs. These programs are discussed further in Chapter 4, Database Administration. Client programs that access the server:

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

SD vs. SD + One of the most important uses of sample statistics is to estimate the corresponding population parameters.

Architectural styles for software systems The client-server style

BEA WebLogic Server. Installing and Setting up WebLogic Server 5.1

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Operating System Concepts. Operating System Concepts

Chapter 3 Classification of FFT Processor Algorithms

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design

SCI Reflective Memory

Ch 9.3 Geometric Sequences and Series Lessons

BEA WebLogic Process Integrator

Threads and Concurrency in Java: Part 1

Τεχνολογία Λογισμικού

Threads and Concurrency in Java: Part 1

Term Project Report. This component works to detect gesture from the patient as a sign of emergency message and send it to the emergency manager.

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

System and Software Architecture Description (SSAD)

How do we evaluate algorithms?

Data Warehousing. Paper

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

In this chapter, you learn the concepts and terminology of databases and

Panel for Adobe Premiere Pro CC Partner Solution

Lecture 1: Introduction and Strassen s Algorithm

Oracle Server. What s New in this Release? Release Notes

Global Support Guide. Verizon WIreless. For the BlackBerry 8830 World Edition Smartphone and the Motorola Z6c

Bayesian approach to reliability modelling for a probability of failure on demand parameter

Computers and Scientific Thinking

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

BEA Tuxedo. Creating CORBA Client Applications

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

Data diverse software fault tolerance techniques

Transcription:

02 6000 ch01 11/18/03 8:52 AM Page 7 C++, Visual C++, ad Maaged C++: What s the Differece? Differeces Betwee Visual C++ ad C++ C++ is a laguage, ad Visual C++ is a product. The laguage itself was developed i the early 80s, ad C++ compilers have bee for sale sice about 1985. Visual C++ made its debut i 1993, ad has had may major releases sice that time. I the late 90s a stadard was developed for the C++ laguage, ad the latest release of Visual C++ (i Visual Studio.NET 2003) icludes a top-otch C++ compiler that is 98% compliat to that stadard, the most compliat versio ever. 1 IN THIS CHAPTER. Differeces Betwee Visual C++ ad C++. Maaged ad Umaaged Code. Maaged ad Umaaged Data. Properties. I Brief The Visual C++ Suite of Tools Of course, Visual C++ is much more tha just a compiler. I additio to a compiler, Visual C++ icludes Two very powerful C++-oly class libraries (MFC ad ATL). A implemetatio of the Stadard Template Library, STL, part of stadard C++. A debugger that icludes a variety of productivityboostig features to help you uderstad what your applicatio is doig, ad why.

02 6000 ch01 11/18/03 8:52 AM Page 8 8 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? A itegrated developmet eviromet that eables you to edit, compile, ad debug your code all from the same applicatio. A suite of wizards ad desigers that geerates code for commo applicatio types, or simplifies codig by usig dialog boxes like the properties widow to automatically modify your code. The.NET Framework SDK, which icludes aother set of class libraries (the.net Base Class Libraries, ASP.NET, ADO.NET, ad Widows Forms) alog with commad-lie compilers ad utilities for.net developmet. Visual C++ is available i several editios, all at differet prices. The umbrella product, Visual Studio, comes with Visual C++ as well as Visual Basic, Visual C#.NET, ad other tools. Visual Studio comes i Professioal, Eterprise Developer, ad Eterprise Architect versios, each of which cotais the three maistream laguages (C++, VB, ad C#). Visual C++.NET Stadard Editio comes with oly Visual C++ o VB or C# compilers. I additio, there is a Academic editio ad evaluatio versios are occasioally available. I M A VISUAL C++ PROGRAMMER SO WHAT? For years, if someoe told you I m a Visual C++ programmer, it meat that perso kew C++, had leared the MFC class library (ad perhaps also the ATL template library), was familiar with the cocepts uderlyig Widows programmig ad the Widows API, ad kew how to use Visual C++ to write MFC ad ATL applicatios for Widows, or for class libraries ad compoets. Those skills do t always traslate well to the.net way of buildig applicatios ad libraries. A Visual C++.NET programmer buildig maaged applicatios has more i commo with a Visual Basic.NET programmer or a C# programmer tha a Visual C++ 6 programmer. To use Visual C++.NET to build applicatios for the.net Framework, you eed to uderstad the cocepts behid.net, ad lear a itegrated developmet eviromet that s quite differet from Visual C++ 6. That s what this book is here to help you lear. This book assumes you re workig with the Professioal Editio. If a demostrated feature is from the Eterprise or Eterprise Architect editio, that detail is metioed. The first release of Visual C++ that could produce maaged code ad target the.net Commo Laguage Rutime was amed Visual C++.NET, ad was part of Visual Studio.NET, released i the sprig of 2002. Sice the, the ew release of those products icludes the moiker 2003; for example, Visual C++.NET 2003. The older product has bee reamed Visual C++.NET 2002, part of Visual Studio.NET 2002. The chages betwee the 2002 ad 2003 versios are relatively mior i most of the.net laguages, but they re quite dramatic i Visual C++. This book covers the 2003 product. The architectural cocepts of.net ad the descriptio of the class libraries icluded i the.net Framework are applicable if you re usig the 2002 product, but the meu choices, wizards, code geerators, ad the like are quite differet i the 2003 release.

02 6000 ch01 11/18/03 8:52 AM Page 9 9 Differeces Betwee Visual C++ ad C++ The Maaged Extesios to C++ It s log bee a covetio amog C++ compiler developers that ay idetifier that starts with a uderscore belogs to the compiler. Do t start your variable or fuctio ames with a uderscore, ad you ll ever accidetally overwrite somethig the compiler was usig. A similar covetio is to use double uderscores at the start of idetifiers ad keywords that are compiler-specific (implemeted by oe compiler vedor but ot by others). This remids developers who use these features that the work they are doig would ot compile or ru properly if it were built with a differet compiler. Although all compilers have a hadful of compiler-specific keywords, these extesios have t really bee importat to developers i the past. Millios of lies of code have bee writte that did t kowigly use compiler-specific code. (The qualifier kowigly applies because compilers vary dramatically i their stadards compliace, ad code that compiles ad works uder oe compiler might behave quite differetly uder aother.) Developers have chose C++ developmet tools based o criteria like the stregth of the class library, or the ease of use of the itegrated editor, ot the collectio of extesio keywords offered by the compiler itself. With the itroductio of Visual C++.NET i 2002, that situatio chaged. Cotiuig i Visual C++.NET 2003, developers use a series of extesio keywords (kow as the Maaged Extesios to C++) to geerate code that targets the.net Framework, also called maaged code. Oe of the requiremets for the team developig Visual C++.NET was that existig code must compile ad ru without error whether the code ow ra i the framework or ot. Therefore, the developmet team could ot chage the meaig or behavior of ay existig keywords. The escape hatch of compiler-specific extesios eabled the team to meet this requiremet. I a prited book, it ca be hard to spot the double uderscores. Ca you see the differece betwee gc ad _gc? Could you see it if they did t appear side by side? There are a lot more leadig double uderscores i this book s sample code tha leadig sigle uderscores, so if you re ot sure, it s probably a double uderscore. If you leared C++ with a compiler other tha Visual C++, you might be cocered that you have aother laguage to lear you do t. The keywords, sytax, brace brackets, semicolos, ad other delights of C++ are exactly the same i Visual C++. What s differet are the libraries, wizards, ad itegrated developmet eviromet that combie to make you a more productive programmer o matter what kid of applicatio you re creatig. Applicatios That Ru Directly Uder Widows Whe you develop a applicatio usig Visual C++.NET 2002 or 2003, it will be either a maaged or umaaged applicatio. I either case, it will be built to ru o a Widows machie.

02 6000 ch01 11/18/03 8:52 AM Page 10 10 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? A umaaged applicatio rus directly uder Widows. Eve a cosole applicatio, which rus i a commad prompt, rus uder Widows. The compiled executable from Visual C++ caot be executed o a o-widows machie, although the code itself might be portable. The source code for a cosole applicatio ca be moved to a o-widows machie ad recompiled with a compiler for that machie. That source code would ru, assumig it did t use ay Microsoft-specific libraries such as MFC or ATL, did ot attempt to load ay DLLs or use ay COM compoets, ad avoided compiler-specific extesios. Of course, ay kid of Widows applicatio other tha a cosole applicatio is utterly oportable. A maaged applicatio rus i the.net rutime. As of mid-2003, o versios of the.net rutime are geerally available for platforms other tha Widows. A demostratio/academic research versio of a subset of the.net Framework called Rotor rus o at least oe flavor of UNIX (FreeBSD) ad the Mac. It does t iclude ASP.NET or Web Services, Widows Forms, ADO.NET, or aythig Widows-specific such as Registry access. The licese agreemet prohibits its use for commercial purposes. Aother project for implemetig the.net Framework o a o-widows platform is Moo, which targets Liux ad other UNIX flavors. The work is partially complete ad a completio date has ot bee aouced. Because Visual C++ is itself a Widows applicatio, it s a good bet that you ll be usig it to create Widows applicatios. That s the assumptio throughout this book. Maaged ad Umaaged Code A compiler that emits umaaged code compiles your source to machie code, which the just rus uder Widows. A compiler that emits maaged code does ot compile your source to machie code, but rather to Itermediate Laguage (IL). Maaged code rus i the Commo Laguage Rutime, ot directly o Widows. Whe you build a maaged applicatio, your code is compiled to IL i a file called a assembly, alog with metadata that describes the classes, methods, ad attributes (such as security requiremets) of the code you ve created. This assembly is the oe-stop-shoppig uit of deploymet i the.net world. You copy it to aother server to deploy the assembly there ad ofte that copyig is the oly step required i the deploymet. Maaged code rus i the Commo Laguage Rutime. The rutime offers a wide variety of services to your ruig code. I the usual course of evets, it first loads ad verifies the assembly to make sure the IL is OK. The, just i time, as methods are called, the rutime arrages for them to be compiled to machie code suitable for the machie the assembly is ruig o, ad caches this machie code to be used the ext time the method is called. (This is called Just I Time, or JIT compilig, or ofte just jittig.) As the assembly rus, the rutime cotiues to provide services such as security, memory maagemet, threadig, ad the like. The applicatio is maaged by the rutime. By cotrast, umaaged code rus uder Widows as it always has.

02 6000 ch01 11/18/03 8:52 AM Page 11 11 Maaged ad Umaaged Code Compilers that emit umaaged code iclude Visual C++ 6 ad earlier Visual Basic 6 ad earlier Ay C++ compiler for Widows other tha Visual C++.NET Visual C++.NET 2002 ad 2003 Compilers that emit maaged code iclude Visual C#.NET 2002 ad 2003 Visual Basic.NET 2002 ad 2003 Other compilers for Visual Studio that meet the Commo Laguage specificatio Visual C++.NET 2002 ad 2003 Notice aythig uusual about the two lists? Visual C++.NET 2002 ad 2003 are o both of them you have a choice of whether you build a maaged or a umaaged applicatio. Visual C++.NET is the oly laguage provided with Visual Studio.NET that ca emit either maaged or umaaged code ad ca eve combie them withi a sigle applicatio. Advatages of Maaged Code Maaged code is, i may ways, a huge improvemet over umaaged code. The services the rutime offers to ruig code iclude Memory maagemet Security Threadig Exceptios Iteroperability betwee laguages Iteroperability to ad from COM Iteroperability to old-style DLLs Iteroperability, as provided by the rutime, icludes parameter marshallig, type coversios, ad eve traslatig COM HRESULTs ito exceptios. Oe of the astoishig thigs Visual C++.NET ca do is to take old C++ code, writte before the.net Framework was iveted, ad compile it to maaged code. The classes ad objects used i that code will all be umaaged data, but the code will compile to IL ad ru i the

02 6000 ch01 11/18/03 8:52 AM Page 12 12 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? rutime. If this ewly maaged code calls methods ad fuctios of umaaged DLLs or LIBs, o problem! As the C++ Dev Team says, It Just Works ad it does. Whe you build your applicatio as maaged code, you have easy access to all the.net class libraries, to compoets writte i Visual Basic.NET or C#, ad to both maaged ad umaaged C++ code. You ca leverage all this code for maximum productivity, ad ejoy all the latest fuctioality provided i the libraries. Advatages of Umaaged Code Umaaged code does t ru i the rutime, it just rus uder Widows. That meas the computers o which your applicatio are istalled do t eed the.net Framework. Durig the first few years of.net, you wo t be able to cout o every Widows machie havig the framework. Startig with Widows Server 2003, every ew release of Widows will iclude the framework, ad it s also available as a Widows Update, so everyoe who keeps up to date will have it. But there s a large segmet of the populatio who ever istall Widows Updates or upgrade their operatig systems. Code aimed at those users should be umaaged code, or should be shipped o a CD with a istall program that istalls the framework automatically. What if the code you re writig is a library of sorts, desiged to be called from older umaaged code as well as ew maaged code? You could write it as a.net object ad wrap it so it s exposed as a COM compoet. That would allow your umaaged code to access it easily, but at a slight performace cost. Alteratively, you could write it as a umaaged COM compoet or a umaaged DLL, ad let the ew maaged code pay the small performace cost for accessig it. Your decisio will probably be based o which of the applicatios that eed to use your code are more performace sesitive. For example, if oe applicatio is used by hudreds of cliets throughout the day, whereas the other is used by oe admiistrator a few times a week, impose the performace pealty o the admiistrator s applicatio ad esure the users have the fastest experiece possible. That meas writig your library as maaged if the user applicatio is maaged, or umaaged if the user applicatio is umaaged. Either way, iteroperability will be possible; it s just a matter of decidig who pays the performace pealty. Performace Cosideratios Which is faster, maaged or umaaged code? The aswer is a resoudig it depeds. I the simplest case code that does t call out to ay other code umaaged is usually faster. You ca test this yourself by writig a simple umaaged cosole applicatio, ad the writig the same mai() as a maaged cosole applicatio. Which versio rus faster depeds o exactly what the code does. The rutime has more checks ad balaces, which

02 6000 ch01 11/18/03 8:52 AM Page 13 13 Maaged ad Umaaged Code ca impose some performace pealties, ad whe you compile to IL you caot take advatage of certai compiler switches that produced optimized machie code (for example, to take advatage of a particular CPU chip), so you would expect the maaged code to always be slower. But oce i a while, it s quicker! Here s a example a etire applicatio i umaaged C++: // LegacyArithmetic.cpp : Defies the etry poit for the cosole applicatio. // #iclude stdafx.h #iclude <iostream> usig amespace std; #iclude <atltime.h> class ArithmeticClass public: double Add( double um1, double um2); double ArithmeticClass::Add(double um1, double um2) retur um1+ um2; } it _tmai(void) ArithmeticClass arith; double aswer ; CTime start = CTime::GetCurretTime(); for (log i=0;i<10000000;i++) aswer = arith.add(1.1,2.3); } CTime stop = CTime::GetCurretTime(); CTimeSpa spa = stop - start; cout << It took << spa.gettotalsecods() << secods << edl; retur 0;

02 6000 ch01 11/18/03 8:52 AM Page 14 14 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? Here s the same applicatio as maaged C++: // This is the mai project file for VC++ applicatio project // geerated usig a Applicatio Wizard. #iclude stdafx.h #iclude <tchar.h> usig amespace System; class ArithmeticClass public: double Add( double um1, double um2); double ArithmeticClass::Add(double um1, double um2) retur um1+ um2; } // This is the etry poit for this applicatio it _tmai(void) double aswer; ArithmeticClass arith; DateTime start = DateTime::get_Now(); for (log i=0;i<10000000;i++) aswer = arith.add(4.7,3.2); } DateTime stop = DateTime::get_Now(); TimeSpa spa = stop - start; Cosole::Write( It took ); Cosole::Write(spa.TotalSecods); Cosole::WriteLie( secods ); retur 0; These applicatios are preseted i their etirety primarily to demostrate a way of determiig how log code takes to ru, ad partly to show how may times you ll have to repeat a loop to get a measurable time differece. Uless you re writig some computatioally expesive code, you might ever see a differece betwee maaged ad umaaged C++. However, just as a poit of iterest, whe you ru these two applicatios the maaged

02 6000 ch01 11/18/03 8:52 AM Page 15 15 Maaged ad Umaaged Data code rus measurably quicker, every time. The oly differece betwee the two applicatios is that the umaaged applicatio uses CTime (from MFC) to time itself ad the maaged applicatio uses DateTime (from the System amespace) to time itself. If your code calls out to umaaged code, goig through COM Iterop or PIvoke (the oly optios available to VB ad C# programmers) will impose a performace pealty. But callig out to that code usig It Just Works is as fast as a direct call. Bottom lie? Your decisio should t be based o a prejudice about speed. If you ca t cout o havig the framework o the target machie, write your code as umaaged. If your code will be called from both maaged ad umaaged, ad the umaaged callig code is more performace sesitive, write your code as umaaged. Otherwise, write it as maaged. Whe it s complete, if you have a performace issue, cosider compilig portios of it as umaaged ad test to see whether that improves performace. Maaged ad Umaaged Data Whe you are writig a umaaged applicatio, you have oly umaaged data. Whe you write a maaged applicatio i Visual Basic or C#, you will have oly maaged data. But whe you write a maaged C++ applicatio, you cotrol whether your data is maaged or umaaged. There are beefits to maaged data, but to gai those beefits you have to accept some restrictios. Umaaged Data This term is just a way to describe the way data has always bee hadled i C++ programmig. You ca ivet a class: class ArithmeticClass public: double Add( double um1, double um2); You ca create a istace of your class o the stack ad use it, like this: ArithmeticClass arith; arith.add(2,2); Or you ca create a istace o the heap, ad use it through a poiter: ArithmeticClass* parith = ew ArithmeticClass(); parith->add(2,2);

02 6000 ch01 11/18/03 8:52 AM Page 16 16 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? Whe the flow of cotrol leaves the block i which the stack variable was declared, the class destructor rus ad the memory becomes available o the stack agai. The heap variable must be explicitly cleared away: delete parith; Ad this, of course, is the rub. Memory maagemet is your job i classic C++. What you create with ew you must clea up with delete. If you forget, you ca suffer a memory leak. What s more, whe you use a umaaged poiter, you ca make all kids of mistakes that overwrite other memory or otherwise corrupt your applicatio. Whe your data is umaaged, it s up to you to maage it. That ca be a lot of work, ad if you mess up, you might create a subtle bug that s hard to fid. Garbage-Collected Classes If you create a class as a garbage-collected class, the rutime will maage the memory for you. I exchage, you give up the capability to create a istace o the stack, ad you have to follow some rules whe desigig your class. You set garbage collectio class-by-class, ot object-by-object. Whe you defie the class, iclude the gc keyword, like this: gc class Sample private: double umber; public: Sample( double um): umber(um) Havig defied your class i this way, you caot create istaces o the stack ay more. If you do, this compiler error results: error C3149: Sample : illegal use of maaged type Sample ; did you forget a *? Istead, you ca oly allocate istaces of a garbage-collected o the heap, with ew. For example Sample* s = ew Sample(3.2);

02 6000 ch01 11/18/03 8:52 AM Page 17 17 Maaged ad Umaaged Data Whe you re fiished with this istace, just igore it. Whe the poiter goes out of scope, the istace will be eligible for cleaup by the garbage collector. If you do try to delete this istace, you ll get a compiler error: error C3841: illegal delete expressio: maaged type Sample does ot have a destructor defied Just leave the poiter aloe ad let the rutime maage your memory. It will be cleaed up evetually. DETERMINISTIC DESTRUCTION SHOP TALK Oe of the hallmarks of a garbage-collected rutime is that you do t kow whe a object i memory will be cleaed up. If the applicatio uses a lot of memory ad is costatly allocatig more, aythig that s eligible to be cleaed up will be destructed quickly. I a applicatio that does t use much memory ad rus for a log log time, it might be hours or days before a object is cleaed up. C++ programmers are used to puttig clea-up code i the destructor. They kow whe the destructor will ru: whe the object goes out of scope or whe they use the delete operator o the poiter. This is called determiistic destructio, because programmers kow whe the destructor will ru. But whe you use maaged data, you have o idea whe the destructor will execute, which is called idetermiistic destructio. I this case, havig clea-up code is a bad idea. For example, if the destructor closes a file, it will sit ope util the destructor rus ad that might be a really log time. I spet quite a few ights up late with frieds arguig about determiistic destructio. Fially, I came to a opiio. If a maaged class holds oly memory thigs you would ormally clea up with delete do t write a destructor ad do t worry about destructio, determiistic or otherwise. If the class holds a o-memory resource (a ope file, a database coectio, a resource lock of some kid, or aythig else that is t memory ad therefore is t garbage collected), do t use a destructor either implemet the Dispose patter. The heart of this patter is a method called Dispose that cleas up the o-memory resource (closes a file, for example). Code that creates istaces of your class should call the Dispose method whe it s through with the istace. You ca write a destructor as a sort of backup pla i case cliet code forgets to dispose your object. Makig your class a garbage-collected class is ot always as simple as addig the gc keyword to the defiitio. There are some restrictios about the way you ca defie your class if you wat it to be garbage-collected, ad some restrictios o the way you use it, too.

02 6000 ch01 11/18/03 8:52 AM Page 18 18 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? Iheritace Restrictios Whe you write a umaaged class, you ca iherit from ay kid of base class at all, or o base class if you prefer. Garbage-collected classes do t have quite the same freedom. Specifically, a garbage-collected class caot iherit from a umaaged class. Cosider this pair of classes: class A protected: it a; gc class Sample: public A public: Sample(it x) : a(x) } This looks like perfectly good C++. Ad it would be, if it were t for that gc extesio keyword i the defiitio of Sample. If you type this code ad try to compile it, you ll be told error C3253: A : a maaged class caot derive from a umaaged class To fix the problem, make the base class maaged if possible, or leave the derived class umaaged. Sigle Iheritace Not oly must garbage-collected classes iherit oly from other garbage-collected classes, but they also ca t use multiple iheritace. Cosider this variat o the Sample class show earlier: gc class A protected: it a; gc class B protected: it b;

02 6000 ch01 11/18/03 8:52 AM Page 19 19 Maaged ad Umaaged Data gc class Sample: public A, public B public: Sample(it x, it y) : a(x), b(y) } Compilig these classes produces this error: error C2890: Sample : maaged class ca oly have oe o-iterface superclass You ca, if you wat, iherit from as may maaged iterfaces as you eed to, but you ca t use traditioal multiple iheritace. Most C++ programmers do t use multiple iheritace. If you re such a programmer, it s o great loss to give it up. If you have workig code that uses multiple iheritace, it s best to leave it as umaaged ad access it from ew maaged code. You ll see how to do that later i this book. Additioal Restrictios o Garbage-Collected Classes Garbage-collected classes have some other restrictios: You caot use the fried keyword to give aother class access to the private members of a maaged class. No member variable of the class ca be a istace of a umaaged class (uless all the member fuctios of the umaaged class are static). You caot override operator & or operator ew. You caot implemet a copy costructor. At first glace, these might seem restrictive. But remember that the reaso you usually write a copy costructor is that your destructor does somethig destructive, such as freeig memory. A garbage-collected class probably has o destructor at all, ad therefore has o eed for a specialized copy costructor. Value Classes May programmers feel ucomfortable whe they are told they caot create istaces of a garbage-collected class o the stack. There are a umber of advatages, i classic C++, to creatig a object o the stack: The object is destructed for you whe it goes out of scope. The overhead of allocatig o the stack is slightly less tha allocatig o the heap. The heap ca get fragmeted (ad therefore you will have a performace hit) if you allocate ad free a lot of short-lived objects.

02 6000 ch01 11/18/03 8:52 AM Page 20 20 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? I maaged C++ (i other words, C++ with Maaged Extesios), the garbage collector takes care of destructig the object for you. It ca also defragmet the heap. The garbage collector itroduces overhead of its ow, of course, ad the allocatio cost differece betwee the stack ad the heap remais. So, for certai kids of objects, it might be a better choice to use a value class rather tha a garbage-collected class. The fudametal types, such as it, are referred to as value types, because they are allocated o the stack. You ca defie a simple class of yours to be a value class. You ca also do the same for a struct. If your class maily exists to hold a few small member variables, ad does t have a complicated lifetime, it s a good cadidate for a value class. Here is Sample oce agai as a value class: value class Sample public: it a; it b; Sample(it x, it y) : a(x),b(y) } To create ad use a istace of Sample, you must allocate it o the stack, ot the heap: Sample s(2,4); s.report(); These value classes are still maaged, but they re ot garbage-collected. The restrictios o value classes are You caot use the fried keyword to give aother class access to the private members of a maaged class. No member variable of the class ca be a istace of a umaaged class (uless all the member fuctios of the umaaged class are static). You caot implemet a copy costructor. A value class caot iherit from a garbage-collected class, or aother value class, or a umaaged class. It ca iherit from ay umber of maaged iterfaces. A value class caot have virtual methods other tha those it iherits (ad possibly overrides) from System::ValueType. No class ca iherit from a value class. A value class caot be labeled abstract with the abstract keyword.

02 6000 ch01 11/18/03 8:52 AM Page 21 21 Maaged ad Umaaged Data The best cadidates for value classes are small classes whose objects do t exist for log ad are t passed aroud from method to method (thus creatig a lot of refereces to them i differet pieces of code). Aother advatage of value classes is that istaces are essetially ever uiitialized. Whe you allocate a istace of Sample o the stack, you ca pass parameters to the costructor. But if you do ot, the member variables are iitialized to zero for you. This is true eve if you wrote a costructor that takes argumets, ad did t write a costructor that does t take argumets. Look at these two lies of code: STACK AND HEAP If you ve bee readig or hearig about Visual Studio.NET already, you might have heard that structs are value types ad classes are referece types, or that structs are o the stack ad objects are o the heap. Those statemets apply to C#. I C++, you re i charge you ca allocate istaces of value types (classes or structs) o the stack ad istaces of garbage-collected types (classes or structs) o the heap. Sample s2; s2.report(); Whe this code rus, it will report a is 0 ad b is 0 Because the Sample class is maaged, the members are iitialized automatically. Piig ad Boxig The class libraries that come with the.net Framework are terrific they provide fuctioality every applicatio eeds. It s atural to use them from your maaged C++ applicatios. Oe thig you eed to kow: The methods i these classes are expectig poiters to garbagecollected objects, ot the umaaged data your applicatio might be usig. What s more, whe you use older libraries, the methods are expectig istaces or poiters to istaces of umaaged variables, ot istaces of maaged classes or member variables of those maaged istaces. Whe you mix maaged ad umaaged data, you eed to use two ew.net cocepts: boxig ad piig. Boxig a Fudametal Type If you try to pass a piece of umaaged data to a method that is expectig maaged data, the compiler will reject your attempt. Cosider this fragmet of code: it i = 3; System::Cosole::Write( i is ); System::Cosole::WriteLie(i);

02 6000 ch01 11/18/03 8:52 AM Page 22 22 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? Simple as it looks, this code wo t compile. The error message is error C2665: System::Cosole::WriteLie : oe of the 18 overloads ca covert parameter 2 from type it could be void System::Cosole::WriteLie (System::Strig gc *,System::Object gc *) You eed to pass a poiter to a garbage-collected object to the WriteLie method. The way you get a poiter to a garbage-collected object is to use the box extesio, like this: System::Cosole::WriteLie( box(i)); This is referred to as boxig the iteger, ad is a coveiet way to use framework methods eve from a applicatio that has some umaaged data. Piig a Poiter Sometimes your problem is the other way aroud. You have a fuctio, already writte, that expects a poiter of some sort. If this is legacy code, it does t expect a poiter that ca move aroud; it expects a classic poiter to a umaaged object. Eve a poiter to a iteger member variable of a maaged object ca be moved by the garbage collector whe it moves the etire istace of the object. Cosider this simple maaged class, aother variatio o Sample used throughout this chapter: gc class Sample public: it a; it b; Sample(it x, it y) : a(x), b(y) } You might argue about whether it s a good idea for the member variables a ad b to be public, but it makes this code simpler to do so. Cosider this simple fuctio, perhaps oe that was writte i a earlier versio of Visual C++: void Equalize(it* a, it* b) it avg = (*a + *b)/2 ; *a = avg; *b = avg; }

02 6000 ch01 11/18/03 8:52 AM Page 23 23 Properties Say that you wat to use this Equalize() fuctio o the two member variables of a istace of this Sample class: Sample* s = ew Sample(2,4); Equalize(&(s->a),&(s->b)); This code wo t compile. The error is error C2664: Equalize : caot covert parameter 1 from it gc * to it * Caot covert a maaged type to a umaaged type Although they are both poiters, the poiter to a garbage-collected type caot be coverted to a poiter to a umaaged type. What you ca do is pi the poiter. This creates aother poiter you ca pass to the fuctio, ad esures that the garbage collector will ot move the istace (i this case, s) for the life of the pied poiter. Here s how it s doe: it pi* pa = &(s->a); it pi* pb = &(s->b); Equalize(pa,pb); The two ew poiters, pa ad pb, are poiters to umaaged types, so they ca be passed to Equalize(). They poit to the locatio i memory where the member variables of s are kept, ad the garbage collector will ot move (upi) the istace, s, util pa ad pb go out of scope. You ca upi the istace sooer by deliberately settig pa ad pb to 0, a ull poiter, like this: pa=0; pb=0; Boxig umaaged data ito temporary maaged istaces, ad piig maaged data to obtai a poiter to umaaged data, are both ways to deal with differeces betwee the maaged ad the umaaged world. Whe you remember that you have these extesios available to you, the task of mixig old ad ew programmig techiques ad libraries becomes much simpler. Properties Maaged classes have oe other feature you might wat to use: properties. You have probably writte classes like this: class Employee private: it salary; //dollars

02 6000 ch01 11/18/03 8:52 AM Page 24 24 CHAPTER 1 C++, Visual C++, ad Maaged C++: What s the Differece? // remaiig member variables public: it getsalary() retur salary;} void setsalary(it s) salary = s;} // remaiig public methods Eve with slightly more complicated code for setsalary(), with some kid of error checkig, the basic cocept is the same it s a private variable with public get ad set fuctios. Not every variable is treated like this, of course: A bak balace, for example, should t be settable from outside, but should istead be chaged by various busiess operatios such as deposits ad withdrawals. But may classes follow this get ad set paradigm. The beefit to this, of course, is ecapsulatio. You are free to add error checkig to either the get or the set method after your system is partially built or i a follow-o phase. You ca eve chage the type of the variable ad simply adjust the code to reflect the chage. Ecapsulatio is a great thig, ad o wise programmer will give it up. The dowside is the way your code looks whe you re usig get ad set fuctios. If you have a poiter to a istace of the Employee class, e, ad you wat to give that employee a $5000.00 raise, here s the code: e->setsalary(e->getsalary() + 5000); That works, but it s ot exactly pretty. But i the.net Framework, you ca have your cake ad eat it too. You just have to chage your defiitio of Employee slightly (the chages are show i bold): gc class Employee private: it salary; //dollars // remaiig member variables public: property it get_salary() retur salary;} property void set_salary(it s) salary = s;} // remaiig public methods

02 6000 ch01 11/18/03 8:52 AM Page 25 25 I Brief Now the class has a Salary property. It s directly tied to the salary member variable, but there s o requiremet that it should be, ad i fact the ame of the property caot be exactly the same as the ame of a member variable, which is why i the Employee class, the property ame (which appears after the get_ ad set_ of the fuctio ames) is Salary ad the member variable is salary. To use the property, you write code that treats it like a public member variable: e->salary = 10000; e->salary = e->salary + 5000; You ca use ay of the familiar C++ operators with a property: e->salary += 5000; Yet behid the scees, your get ad set fuctios, with all their attedat error checkig, are beig called. You have all the beefits of ecapsulatio, yet your code is as easy to read as if all your member variables were public. I Brief Visual C++ is a itegrated developmet eviromet that icludes a compiler, editor, debugger, ad other tools. Applicatios writte i stadard C++ will compile i Visual C++. Maaged applicatios writte i Visual C++.NET make extesive use of laguage extesios, which are keywords startig with double uderscores. Developers ca create garbage-collected classes i Visual C++ if the classes meet a list of restrictios, ad save the trouble of maagig memory allocated for those classes. Developers ca create umaaged classes if that is preferable. Maaged classes ca expose properties that make code simpler to read ad to write while retaiig the beefits of ecapsulatio.

02 6000 ch01 11/18/03 8:52 AM Page 26