text:
Rhetoric and Composition/Writing in Business

Writing for business includes multiple types of formats including, but not limited to, cover letters, resumes, memos, e-mails, letters, proposals, business plans, and formal reports. This section will focus on how to be a successful business writer.

Purpose of Business Writing
The main purpose of business writing is to convince. For example, as a professional business writer, you often find yourself explaining the value of a complex idea in order to obtain agreement among readers. Or, you find yourself crafting a document intended to persuade people and rouse them to action.

In other respects, business writing is much like any other form of writing that includes pre-writing or brainstorming, writing and revising. The most important aspects of business writing are clear and concise writing and getting the message across in the best way. As with all writing, it is important to keep the audience in mind when coming up with the best format to get the message across.

Audience
The most important concept to keep in mind when writing for business is who your target audience is. You need to tailor your writing to fit different audiences in different situations. If you address the document's specific target audience in terms it understands, your document will have a better chance of achieving its goal.

Every business document has a purpose. You could be trying to persuade your boss that you are due a raise in one instance, and trying to persuade the HR Department that the company picnic would have more participation if it were held at a lake in another instance. In both instances, the language and way you would approach each is going to differ.

Deadlines
Much, if not all, professional business writing is performed against a deadline. In fact, making a deadline with time to spare is the hallmark of a pro. That act alone inspires a sense of confidence in a business that is often as persuasive as the document itself. So, a good rule of thumb for business writers would be 'better a B+ document that arrives on time than an A that's late.'

Memos and E-mails
Writing memos and e-mails in a business setting is slightly different than writing to a friend or family member. The biggest difference is that in a business setting, the writing must be professional or formal. A big misconception about e-mailing in business is that formality is not important. Grammar and composition are both important aspects. However, should you receive an email of memo which contains compositional and grammatical flaws, it may be rude or unwise to point these out to the author. Memos and e-mails have a similar approach. The purpose of both is to get a certain message across. This section will cover deciding when it is appropriate to use either a memo or e-mail, content, pre-writing techniques, and effectiveness.

Memos
The memo or memorandum has a few types. The memos can be short notes, reports, plans or proposals. The standard memo is most effective when attempting to inform many people within the same organization of upcoming events, changes, thoughts, or ideas.

Most memos will have five basic elements: Note: When writing your subject line, make sure it is called something accurate, unique and specific. Name your memo something informative.
 * The organization's logo or letterhead
 * The "to" line
 * The "from" line
 * The subject line
 * The date line

The first sentence of your memo you should clearly state your purpose. Be concise and direct.

Example: An example from "How to write it? (pp.167)"

To:   All Department Heads From: Joan Alexander Date: May 10, 2007 Subject:Weekly Department Head Meeting, May 30, 2007, 8:00 am. Room 108 Agenda: 1. Vote on the vacation policy. 2. Elect a media spokesperson. 3. Introduce the new vice president of marketing, Mark Halpern.

Example: The purpose of this memo is to request authorization to travel to Minneapolis to visit the Museum of Natural History to learn more about dinosaur fossils.

Use headings throughout your memo to help the reader decide what they want to read and understand the information they are being presented. Headings can also help the reader understand the purpose of the section (i.e. summary).

If your memo has a lot of information or if it is really long, you may consider summarizing the memo. This can help readers understand the body of the memo, allow readers to skip information that is not relevant to them or to remind the reader of the memos main points. A good memo will record the clear main ideas and every important decision.

Keep in mind your audience when writing your memo. You may need to provide background information or explain the events that led to the situation to which the memo is regarding.

E-mails
Emails are fast, cheap, easy to use, and digital. Because of its widespread use, here are some things to keep in mind when writing "business" emails.
 * Use an appropriate level of formality.
 * Keep messages brief. If you are replying to an email, don't repeat information from the email, instead establish a general context of the email.  Also, if sending the email to more than one person, you may want to consider blocking the original author's name for privacy's sake (BCC = Blind Carbon-Copy).
 * Be careful when writing. Because email is often informal, it is easy for them to become sloppy.  Make sure you read your email before sending it.
 * In formal business email, avoid the use of characters to create emotion faces, such as :), Orz, or > <.
 * Use the subject line. All business emails should have a subject so the reader can decide quickly whether or not they need to read the email.
 * Don't use all capital letters or use annoying backgrounds. Keep your emails simple.  Try to stay away from using italics, bolds or underlining.  Even if your email supports these options, others may not.
 * Don't forward a message without the permission of the author.
 * Above all, have something to say. Don't send emails just for fun or just to reply agreeing with the writer (unless this is requested or expected).  In other words, don't send a message just to feel like you are part of the conversation.
 * Remember, if you are writing a memo or email during working hours or on a company computer, the company OWNS this material (and has the fully legal right to inspect it). Avoid overtly personal and/or sensitive content in your email while at work.  If you are concerned about this possibility, look into message encryption.

Cover Letters and Resumes
Writing a resume or a cover letter is basically a sales pitch to a potential employer. You need to acknowledge that they have a need (an empty position), and that you are the perfect fit for them or at least close enough of a fit to bring into their office for an interview.

Cover Letters
The cover letter and resume will form employers’ first impressions of a potential employee. These documents will be the first thing the employer sees, therefore, make every attempt to ensure the documents are without errors (grammatical, spelling, punctuation, etc.). Mistakes in the resume and cover letter are one of the biggest reasons why job seekers fail to secure an interview. If the potential employer finds mistakes, they will have the feeling that the applicant probably will not take the time to be careful with their work when they are on the job.

The cover letter is an opportunity to expand on any specific points in the resume that deserve more attention and can be connected to aspects of the desired position. Remember, there is likely a large pool of people applying for the same position. Use the cover letter effectively to present yourself and distinguish your application from the rest.

Any time a resume is sent in the mail, it must be accompanied by a cover letter. The cover letter is an important factor in getting your resume past the first barrier. The cover letter must be customized for each opportunity. It can also be an opportunity to explain any problems,questions, and things that may not be clear in your resume (such as gaps in employment).

Why is the cover letter so important?

The cover letter:

• is your opportunity to personalize your resume and target your skills to the specific employer;

• connects your past experiences listed on your resume to your potential future position at a new job;

• highlights your strengths, accomplishments, and sparkling personality;

• can be tailored to the needs of the specific company to which you are applying.

Cover Letter Formats

Employer Invited Letter: Use the employer invited letter when an employer has requested a resume. This is often in response to a classified ad or publicized listing. This style focuses on matching your qualifications to the advertised requirements of the position.

Uninvited or Cold Contact Letter: Use the uninvited letter to contact employers who have not advertised or published job openings. The focus is on matching your qualifications to the perceived needs of the employer based on labor market research. This strategy requires that a phone or personal contact with the employer either precede or follow the sending of the resume and cover letter.

Referral Letter: Use the referral letter to contact employers to whom you have been referred. The effective job seeker will receive referrals to many job opportunities through networking and informational interviews. The referral may be to a specific job opening (advertised or unadvertised) or to an employer who may not be hiring. In a referral letter the individual who provided the referral is mentioned in the letter.

Specific points to address in the cover letter.

 * Let the company know why you are contacting them. Your intent may seem obvious, but tell the employer you are interested in a job at their company. Opening a letter without stating you intent may seem awkward. Whenever possible address the cover letter to a specific person by name and title.

 * Let the employer know how you heard about the open position. For example, "I am interested in X position. I heard about/discovered the opening online/in the newspaper/from one of their a current employees. It is likely that the company has more than one open position so make sure to identify the specific position in which you are interested.

 * Include a detailed description of your educational and work experience. Be sure to highlight the areas in your work or educational history that apply directly or closely to your desired position. You can put either paragraph first, but put your strongest information first. If you have a lot of work experience related to the job, then put your work experience first. If your educational experience makes you more strongly qualified, consider putting that information first. Remember, extra-curricular activities can be very valuable, if they are applicable to the position.

 * Use terms from the ad that are clearly relevant to you and your experience. Take a cue from the job ad and emphasize how you are specifically qualified for the position. If the job requires a degree in Management and you have a Master's Degree in Management, emphasize that point. Writing your cover letter specifically for the job for which you are applying, will stand out more than a person who has a generic cover letter. Utilize action words and descriptive statements to convey your qualifications and career objectives.

You may also want to state the best time you can be reached. It is also a good idea to reference your resume, if you haven't already done so.
 * Reemphasize your interest in the position. Include a polite, but also confident request for an interview. Ask that they contact you and be sure to include how you'd like to be contacted (i.e. give your phone number and/or your email address.

 * Remember, be confident! If you don't sound like you think you are qualified for the position, why should a potential employer? Your cover letter needs to persuade the employer that you have skills and abilities that are useful to the company.

Cover Letter Outline

Insert Date Here

Ms. Catherine Smith

Human Resources Director

St. Mary’s Hospital

123 Southview Drive

Minneapolis, MN 55555

Dear Ms. Smith,

First Paragraph: Introduction 1. Explain why you are writing and the position you are applying for

2. Where you learned of the position 3. Who referred you to the job (if someone did)

4. Explain your interest in the employer, company, product/services

Body: Two to four paragraphs

1. Explain why you are qualified for the position

2. Link your cover letter to your resume; expand upon highlights of your resume with specific examples

3. Discuss your most relevant and distinguishing characteristics

Close: One paragraph

1. Indicate that your resume is enclosed/attached

2. Mention your desire for an interview

3. Notify the employer of a day and time you will follow up

4. Express your appreciation for their time and consideration of your application

Cover Letter Example
Other Tips:

The cover letter and resume should be no more than a page.

Be creative, original and professional. Avoid using templates and standardized cover letters from books or websites.

If you are asked to supply additional materials or references, do so promptly.

Double check spelling and triple check any names and titles.

Resumes
Unlike cover letters, resumes are a brief outline used by hiring managers to scan a potential employee. Think of the resume as a "snapshot" of your most relevant work and educational experience. Just like your cover letter, you want to bring out aspects of previous positions that relate to the one you are hoping to obtain.

Resumes need to be brief and descriptive at the same time. How are you going to manage that? You will need to be very selective in your word choice. Each resume usually gets under a one minute chance to make an impression. You should generally be able to get everything that you need to say in one page. Make sure the pertinent information really stands out. If you glance at your resume and can't find what's important right away, someone else will have a hard time finding the information that's important.

Hiring managers expect that your resume be typed or printed, neat, easy to read, clearly outlined. Don't use bright colors of ink or paper. Make sure it looks professional.

There are several elements to a resume:

 * Identification - Include your name, address, e-mail, phone number.

 * Objective - Write a clear goal, avoid generalities. Objectives are not necessary, but they are really helpful when applying for a volunteer position, internship or other positions that are a little more vague than a job opportunity.  If your objective states you want a job, don't include it, but rather specify the particular field of employment.

 * Employment - Include your skills and responsibilities, with what equipment you worked. The most important thing to include here is what you gained from your employment, the results of your experience.  Use an active voice and strong verbs.

 * Education - Include information about your degree and the institution. Again, make sure you talk about the results of your education, not just that your received an education.

 * Interests and Activities - Make sure these are relevant to the job and demonstrate the personal impact you made as part of the group or working on a project. Don't just include random hobbies.

 * References - There are a variety of opinions about whether or not to include references on the resume. Most employers are aware that they can request references from the job applicant at any point throughout the interview and hiring process. The job application itself, also may ask for references and their contact information. It is important to utilize the "white space" on your resume most effectively. You can list your references or write "available upon request". If you choose to list your references on a separate sheet of paper, make sure your name is on all sheets in case the pages get separated. To provide continuity between your cover letter, resume and references list, consider using the same header with your name and contact information on all three documents.

How to get started:

1. Define your objective. What position do you want to be hired for with the resume you will be working on? Resumes should always be customized to reflect the skills related to the desired position. A resume for a human resources position should look different than a resume for a counseling position.

2. Identify and evaluate your audience. Who in the company will most likely be viewing your resume first: a human resources representative, the CEO or the district manager? What skills, qualities and knowledge will your audience look for?

3. Prioritize your selling points. You have considered who your audience is going to be and what they will be looking for, now consider what areas in your work and educational experience best match the desired skills, qualities and knowledge. Brainstorm the key buzz words and action verbs that would best highlight your relevant qualifications.

4. Showcase your successes. Every employer wants a winner on their team. Demonstrate your successes (e.g. college degrees, educational honors, scholarship winnings, job promotions, leadership and community involvement and any other relevant awards/recognition).

5. Choose your resume format and layout. What resume format (chronological, functional or combination) will best showcase your qualifications for the job. How can the layout be designed to best highlight so that the employer will quickly notice your selling points?

6. Create, Critique and Revise. Nothing good is ever written. It is always rewritten. Start the resume writing process as early as possible. Although your resume will always be a work in progress, revising will continually improve the final product. Ask a career advisor, professor, parent or room mates seriously edit your resume. Any typo, spelling and grammatical error or spacing mistake should be improved. Your goal should be to have your resume error free.

7. Ensure the printing looks professional. Typing your resume is an absolute must. Print your resume on a laser printer and use a heavier paper stock.

Questions to help jog your memory about your college activities for your resume:

•Did you win any academic scholarships? What were the winning criteria?

•Were you on the Dean’s list?

•Do you have a high GPA?

•What major (s) and/or minor (s) did you complete?

•Worked while a student to help fund your education?

•Completed an internship?

•Active in student organizations? Held any positions of office/leadership? If so, what were your responsibilities?

•Played sports? Captain? All conference?

•Volunteer/community service?

•Summer employment?

•Student newspaper, radio station, or television station?

•Wrote articles for a publication? Had work published?

•Created a web site?

•Conducted original research?

•Presented papers, served on panels?

•Helped organize a special event or conference?

•Research assistant or teaching assistant?

•Theatre production? Debate team? Choir? Band?

•Individual tutoring?

•Field service/practicum as part of your major?

Using Key Action Verbs

What is an action verb? Action verbs describe achievements or results in a concise and persuasive manner.

The following job description uses a non-action verb:

Was the supervisor of ten employees.

The next job description uses an action verb:

Supervised ten employees.

The job description using the action verb is more concise (three words shorter). Concise writing is easier for the reader to understand and carries more impact and power.

Use action verbs as the first word of each bullet point in your resume to emphasize job descriptions in your resume. Examples:

•Developed and wrote content for the organization’s website

•Created and coordinated special events generating product awareness and increased sales

•Evaluated company’s marketing and public relation campaigns’ impact & implementation.

It is common for students to be too brief in their description of their skills, qualities and traits. Key action words will help you best describe and sell your skills and abilities.

1. First read through the entire list below and write down the action verbs (skills) employers look for in your field or particular position.

2. Next, read through the entire list a second time and write down the action verbs you have used in the experience you are describing on your resume.

3. Look back at your written list and highlight the words that appear on both lists. Incorporate these words into your resume and cover letter.

There are a few different forms of resumes. One gives a chronological breakdown of your work experience while the other shares your skills and prior positions based on function.

Follow up or Thank you letters
After an interview, take that time to write a thank you letter. The follow up letter can do more good for you in less time than most other aspects of the application/interview process. Thank the interviewer for taking time out of their schedule to meet with you. Also, make sure to emphasize your particular qualifications and/or restate your interest in the position. This letter puts your name in front of the interviewer again and also shows that you are truly interested in the position. Plus, if you are basically tied in contention for the job with another person, the thank you letter may tip the scales in your favor.

Mail the thank you letter within a day of your interview. Not only will this help you in remember the details of your interview, it will also help to ensure that your potential interviewer sees your thank you letter before making a final decision about the position.

When to Write Thank You Letters:

A thank you letter should be written after an interview, when someone provides or sends you information at your request, when a contact was particularly helpful to you, or any other contact that you would like to express thanks and develop a good relationship with.

Writing Your Thank You Letter:

The body of your thank you letter is really a “sales” letter. It is an opportunity to restate why you want the job, to reiterate your best qualifications that match the job requirements, and how you will make significant contributions to the establishment. A thank you letter is also the perfect opportunity to discuss anything that your interviewer neglected to ask you or that you neglected to answer as thoroughly as you could have.

Customize Your Thank You Letters:

It’s very important to keep your audience in mind when writing your thank you letter. Typically your thank you letters are typed but research suggests that managers like hand written thank you notes also.

In addition to thanking the person you talked with, thank you letters also reinforce the fact that you want the job.

Follow Up Letter to Recap Important Information:

Remind individuals who attended the meeting of the main events and important dates that were discussed. Remind individuals who attended an important business event of the discussions that were made. This helps keep the work flowing and everyone on the same page. This also promotes further discussion and collaboration.

Follow-up Letter to announce a special Offer:

This type of letter helps improve your relationship with a new customer. Remind the customer that you are willing to help them by stating the advantages that your company can offer. Thank the customer, or announce the special sale or limited time offer. Remind the customer why you are a good business to work with.

Follow-up Letter to Remind Readers of Important Events:

Make sure to include the date, time, location of the event, and any other important information that the reader needs to have in order to attend the event.

Other business letters
Besides writing a letter to express appreciation for an interview, there are several other types of follow up letters. Here are some tips for these types of letters.

 * Letter accepting a job offer - Express appreciation for the offer. Show enthusiasm for the position.  Repeat the major terms of your employment such as start date, job title, or salary.

 * Letter of rejection in response to a job offer - Again, express your appreciation for the offer. If it's appropriate, explain your reason for declining the offer.  Remember, at some point in the future, you may want to work for this company, so be polite with your rejection.

 * Letter acknowledging a rejection - Why bother? This letter maintains good relations with the company.  You might get a phone call later on saying that the first choice candidate wasn't able to take the position.

Proposals, Business Plans and Formal Reports
Proposals, business plans and formal reports can be a critical part of your business career. All of these may deal with important outcomes. The goal of all of these is to persuade the readers into agreeing with your ideas. Often times, you are trying to gain something from the readers, such as money, equipment or help.

Considerations
When starting a proposal, the first thing to consider is what your goals are. If you are asked to write a proposal for someone, make sure you are clear on what their goals and requirements are.

There are four main elements that must be considered with your goals.
 * 1) What are the immediate goals and how do they relate to the long-term goals?
 * 2) What costs or risks are involved with writing the proposal? This includes time and people needed.  Do not forget to explore hidden cost opportunities.
 * 3) What kinds of resources are you going to need? Are those resources readily available?
 * 4) What will come from an unsuccessful proposal? Will it be helpful if only some goals are met?

After considering your goals, there are still many more things to think about. You must take into consideration the readers, your argument, feasibility, and action.

Readers
The more you know about your readers, the more you can tailor your report to appeal to them. If you are lucky, you already know a lot about the reader because they wanted you to write the proposal and have given you specific guidelines. However if you do not know much about your readers, then you better do some research on them. It is important to know what form of research they will be the most receptive to. Surveys may satisfy one reader, while another reader may not find them to be as credible.

 * Argument : An argument can be summed up as what the main issue is and the importance of that issue. You need to prove to your readers the significance of the issue.  You must convince your readers that your issue needs their attention or help.  You need to inform them of the issue, tell them why they should care, what they can do to help, the benefits of their help, and why they should find you credible.

 * Feasibility : In your report, often as part of your argument, you will have to convince the readers of the feasibility of the issue. Included in this would be offering alternative plans, addressing the costs and risks involved, as well as the resources needed.  You should be able to identify why your plan is the best option.

 * Action : You will also need to include a plan of action in your report. Most proposals are asking the readers for something.  You will need to tell the readers exactly what it is that you want them to do.

What is included in a proposal?
Cover, cover letter, table of contents, executive summary, appendix, and graphics.

 * Cover : The cover page should include the title of the proposal, who the proposal is for, who the proposal is by, and the date.

 * Cover letter : The cover letter is used to introduce the formal report. It is often less formal than the report itself.  The letter usually includes an introduction of the topic and how it was authorized, a brief description of the plan, highlights of the report's findings, conclusions, and recommendations.

 * Table of contents : The table of contents is just as it sounds, a table of the proposal's content and page numbers. In the table of contents you should include section headings/topics and the page they can be found on.  Be sure to include leaders (numbers, dots or bullet-points) to link the section with the corresponding page number.

 * Executive summary : The executive summary is a brief overview of the proposal. You should summarize your main points, you should begin with your purpose and follow the order of your proposal.  Make sure to avoid including non essential information.  The executive summary should not be longer than 10 percent of the length of the proposal.  With proposals that are 10 pages or less, it may not be necessary to include an executive summary.

 * Appendix : An appendix is pretty much any supporting material that you either reference in your proposal or may be supporting sources that be relevant to some readers and not others. You may choose to include survey forms, other reports, tables of data, or any related material.  They are named Appendix A, B, C, etc.

 * Graphics : While graphics are not a must, they are greatly appreciated. Graphics help to break up all of the text in order to give the reader's eyes a little break.  You may choose to include a few small charts or graphs in your reports also.  Just be sure that the graphics are relevant to the proposal.

Some tips to consider while writing your proposal...

 * 1) Be clear on your topic.  Do not try to cover too many aspects in one proposal.  Stick to the most important so that you can be clear and concise.
 * 2) Create a phrase that will draw in your readers.  Pick an aspect of your report that should interest you readers and mention it early on to gain their interest.
 * 3) Make sure to include any background information that may be necessary in order to understand the proposal.
 * 4) Give yourself enough time to finish the proposal to the best of your ability.  You do not want to be in a time crunch while writing such an important document.
 * 5) You should not start writing until all of your research has been conducted and you have reached all of your conclusions.
 * 6) All basic writing standards apply... you should revise and edit, be consistent with verb tense, and avoid using "I" or "we" because you want the proposal to be objective and credible.


text:
User:Jayson Virissimo~enwikibooks

Jayson Virissimo's Wikipedia User Page

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: User:Jayson Virissimo~enwikibooks


text:
C++ Programming/Programming Languages/C++/Code/Statements/Variables/Type

Type
So far we explained that internally data is stored in a way the hardware can read as zeros and ones, bits. That data is conceptually divided and labeled in accordance to the number of bits in each set. We must explain that since data can be interpreted in a variety of sets according to established formats as to represent meaningful information. This ultimately required that the programmer is capable of differentiate to the compiler what is needed, this is done by using the different types.

A variable can refer to simple values like integers called a primitive type or to a set of values called a composite type that are made up of primitive types and other composite types. Types consist of a set of valid values and a set of valid operations which can be performed on these values. A variable must declare what type it is before it can be used in order to enforce value and operation safety and to know how much space is needed to store a value.

Major functions that type systems provide are:
 * Safety - types make it impossible to code some operations which cannot be valid in a certain context. This mechanism effectively catches the majority of common mistakes made by programmers. For example, an expression "Hello, Wikipedia"/1 is invalid because a string literal cannot be divided by an integer in the usual sense. As discussed below, strong typing offers more safety, but it does not necessarily guarantee complete safety (see type-safety for more information).
 * Optimization - static type checking might provide useful information to a compiler. For example, if a type says a value is aligned at a multiple of 4, the memory access can be optimized.
 * Documentation - using types in languages also improves documentation of code. For example, the declaration of a variable as being of a specific type documents how the variable is used. In fact, many languages allow programmers to define semantic types derived from primitive types; either composed of elements of one or more primitive types, or simply as aliases for names of primitive types.
 * Abstraction - types allow programmers to think about programs in higher level, not bothering with low-level implementation. For example, programmers can think of strings as values instead of a mere array of bytes.
 * Modularity - types allow programmers to express the interface between two subsystems. This localizes the definitions required for interoperability of the subsystems and prevents inconsistencies when those subsystems communicate.

Standard types
There are five basic primitive types called standard types, specified by particular keywords, that store a single value. These types stand isolated from the complexities of class type variables, even if the syntax of utilization at times brings them all in line, standard types do not share class properties (i.e.: don't have a constructor).

The type of a variable determines what kind of values it can store:

 * bool - a boolean value: true; false
 * int - Integer: -5; 10; 100
 * char - a character in some encoding, often something like ASCII, ISO-8859-1 ("Latin 1") or ISO-8859-15: 'a', '=', 'G', '2'.
 * float - floating-point number: 1.25; -2.35*10^23
 * double - double-precision floating-point number: like float but more decimals

The float and double primitive data types are called 'floating point' types and are used to represent real numbers (numbers with decimal places, like 1.435324 and 853.562). Floating point numbers and floating point arithmetic can be very tricky, due to the nature of how a computer calculates floating point numbers.

Definition vs. declaration
There is an important concept, the distinction between the declaration of a variable and its definition, two separated steps involved in the use of variables. The declaration announces the properties (the type, size, etc.), on the other hand the definition causes storage to be allocated in accordance to the declaration.

Variables as function, classes and other constructs that require declarations may be declared many times, but each may only be defined one time.

This concept will be further explained and with some particulars noted (such as ) as we introduce other components. Here are some examples, some include concepts not yet introduced, but will give you a broader view:

Declaration
C++ is a statically typed language. Hence, any variable cannot be used without specifying its type. This is why the type figures in the declaration. This way the compiler can protect you from trying to store a value of an incompatible type into a variable, e.g. storing a string in an integer variable. Declaring variables before use also allows spelling errors to be easily detected. Consider a variable used in many statements, but misspelled in one of them. Without declarations, the compiler would silently assume that the misspelled variable actually refers to some other variable. With declarations, an "Undeclared Variable" error would be flagged. Another reason for specifying the type of the variable is so the compiler knows how much space in memory must be allocated for this variable.

The simplest variable declarations look like this (the parts in []s are optional):

[specifier(s)] type variable_name [ = initial_value];

To create an integer variable for example, the syntax is

where sum is the name you made up for the variable. This kind of statement is called a declaration. It declares <tt>sum</tt> as a variable of type <tt>int</tt>, so that <tt>sum</tt> can store an integer value. Every variable has to be declared before use and it is common practice to declare variables as close as possible to the moment where they are needed. This is unlike languages, such as C, where all declarations must precede all other statements and expressions.

In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:

you could probably make a good guess at what values would be stored in them. This example also demonstrates the syntax for declaring multiple variables with the same type in the same statement: hour and minute are both integers (int type). Notice how a comma separates the variable names.

Those lines also declare variables, but this time the variables are initialized to some value. What this means is that not only is space allocated for the variables but the space is also filled with the given value. The two lines illustrate two different but equivalent ways to initialize a variable. The assignment operator '=' in a declaration has a subtle distinction in that it assigns an initial value instead of assigning a new value. The distinction becomes important especially when the values we are dealing with are not of simple types like integers but more complex objects like the input and output streams provided by the <tt>iostream</tt> class.

The expression used to initialize a variable need not be constant. So the lines:

can be combined as:

or:

Declare a floating point variable 'f' with an initial value of 1.5:

Floating point constants should always have a '.' (decimal point) somewhere in them. Any number that does not have a decimal point is interpreted as an integer, which then must be converted to a floating point value before it is used.

For example:

will not set a to 2.5 because 5 and 2 are integers and integer arithmetic will apply for the division, cutting off the fractional part. A correct way to do this would be:

You can also declare floating point values using scientific notation. The constant .05 in scientific notation would be $$5 \times 10^{-2}$$. The syntax for this is the base, followed by an e, followed by the exponent. For example, to use .05 as a scientific notation constant:

Below is a program storing two values in integer variables, adding them and displaying the result:

or, if you like to save some space, the same above statement can be written as:

Modifiers
There are several modifiers that can be applied to data types to change the range of numbers they can represent.

const
A variable declared with this specifier cannot be changed (as in read only). Either local or class-level variables (scope) may be declared <tt>const</tt> indicating that you don't intend to change their value after they're initialized. You declare a variable as being constant using the <tt>const</tt> keyword. Global <tt>const</tt> variables have static linkage. If you need to use a global constant across multiple files the best option is to use a special header file that can be included across the project.

declares a positive integer constant, called <tt>DAYS_IN_WEEK</tt>, with the value 7. Because this value cannot be changed, you must give it a value when you declare it. If you later try to assign another value to a constant variable, the compiler will print an error.

The full meaning of <tt>const</tt> is more complicated than this; when working through pointers or references, <tt>const</tt> can be applied to mean that the object pointed (or referred) to will not be changed via that pointer or reference. There may be other names for the object, and it may still be changed using one of those names so long as it was not originally defined as being truly <tt>const</tt>.

It has an advantage for programmers over <tt>#define</tt> command because it is understood by the compiler, not just substituted into the program text by the preprocessor, so any error messages can be much more helpful.

With pointers it can get messy...

If the pointer is a local, having a <tt>const</tt> pointer is useless. The order of T and const can be reversed:

is the same as

volatile
A hint to the compiler that a variable's value can be changed externally; therefore the compiler must avoid aggressive optimization on any code that uses the variable.

Unlike in Java, C++'s <tt>volatile</tt> specifier does not have any meaning in relation to multi-threading. Standard C++ does not include support for multi-threading (though it is a common extension) and so variables needing to be synchronized between threads need a synchronization mechanisms such as mutexes to be employed, keep in mind that <tt>volatile</tt> implies only safety in the presence of implicit or unpredictable actions by the same thread (or by a signal handler in the case of a volatile sigatomic_t object). Accesses to <tt>mutable volatile</tt> variables and fields are viewed as synchronization operations by most compilers and can affect control flow and thus determine whether or not other shared variables are accessed, this implies that in general ordinary memory operations cannot be reordered with respect to a mutable volatile access. This also means that mutable volatile accesses are sequentially consistent. This is not (as yet) part of the standard, it is under discussion and should be avoided until it gets defined.

mutable
This specifier may only be applied to a non-static, non-const member variables. It allows the variable to be modified within const member functions.

mutable is usually used when an object might be logically constant, i.e., no outside observable behavior changes, but not bitwise const, i.e. some internal member might change state.

The canonical example is the proxy pattern. Suppose you have created an image catalog application that shows all images in a long, scrolling list. This list could be modeled as:

Note that for the image class, bitwise const and logically const is the same: If m_data changes, the public function data returns different output.

At a given time, most of those images will not be shown, and might never be needed. To avoid having the user wait for a lot of data being loaded which might never be needed, the proxy pattern might be invoked:

Note that the image_proxy does not change observable state when <tt>data</tt> is invoked: it is logically constant. However, it is not bitwise constant since <tt>m_image</tt> changes the first time <tt>data</tt> is invoked. This is made possible by declaring <tt>m_image</tt> mutable. If it had not been declared mutable, the <tt>image_proxy::data</tt> would not compile, since <tt>m_image</tt> is assigned to within a constant function.

short
The <tt>short</tt> specifier can be applied to the <tt>int</tt> data type. It can decrease the number of bytes used by the variable, which decreases the range of numbers that the variable can represent. Typically, a <tt>short int</tt> is half the size of a regular <tt>int</tt> -- but this will be different depending on the compiler and the system that you use. When you use the <tt>short</tt> specifier, the <tt>int</tt> type is implicit. For example:

is equivalent to:

long
The <tt>long</tt> specifier can be applied to the <tt>int</tt> and <tt>double</tt> data types. It can increase the number of bytes used by the variable, which increases the range of numbers that the variable can represent. A <tt>long int</tt> is typically twice the size of an <tt>int</tt>, and a <tt>long double</tt> can represent larger numbers more precisely. When you use <tt>long</tt> by itself, the <tt>int</tt> type is implied. For example:

is equivalent to:

The shorter form, with the <tt>int</tt> implied rather than stated, is more idiomatic (i.e., seems more natural to experienced C++ programmers).

Use the <tt>long</tt> specifier when you need to store larger numbers in your variables. Be aware, however, that on some compilers and systems the long specifier may not increase the size of a variable. Indeed, most common 32-bit platforms (and one 64-bit platform) use 32 bits for <tt>int</tt> and also 32 bits for <tt>long int</tt>.

signed
The <tt>signed</tt> specifier makes a variable represent both positive and negative numbers. It can be applied only to the <tt>char</tt>, <tt>int</tt> and <tt>long</tt> data types. The <tt>signed</tt> specifier is applied by default for <tt>int</tt> and <tt>long</tt>, so you typically will never use it in your code.

Enumerated data type
In programming it is often necessary to deal with data types that describe a fixed set of alternatives. For example, when designing a program to play a card game it is necessary to keep track of the suit of an individual card.

One method for doing this may be to create unique constants to keep track of the suit. For example one could define

Unfortunately there are several problems with this method. The most minor problem is that this can be a bit cumbersome to write. A more serious problem is that this data is indistinguishable from integers. It becomes very easy to start using the associated numbers instead of the suits themselves. Such as:

...and worse to make mistakes that may be very difficult to catch such as a typo...

...which produces a valid expression in C++, but would be meaningless in representing the card's suit.

One way around these difficulty is to create a new data type specifically designed to keep track of the suit of the card, and restricts you to only use valid possibilities. We can accomplish this using an enumerated data type using the C++ keyword.

Type conversion
Type conversion or typecasting refers to changing an entity of one data type into another.

Implicit type conversion
Implicit type conversion, also known as coercion, is an automatic and temporary type conversion by the compiler. In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly.

For example:

As you can see,   and   belong to different data types, the compiler will then automatically and temporarily converted the original types to equal data types each time a comparison or assignment is executed.

Explicit type conversion
Explicit type conversion manually converts one type into another, and is used in cases where automatic type casting doesn't occur.

In this example, d would normally be a double and would be passed to the printf function as such. This would result in unexpected behavior, since printf would try to look for an int. The typecast in the example corrects this, and passes the integer to printf as expected.


text:
C++ Programming/Programming Languages/C++/Code/Statements/Variables/Type Casting

Type Conversion
Type conversion (often a result of type casting) refers to changing an entity of one data type, expression, function argument, or return value into another. This is done to take advantage of certain features of type hierarchies. For instance, values from a more limited set, such as integers, can be stored in a more compact format and later converted to a different format enabling operations not previously possible, such as division with several decimal places' worth of accuracy. In the object-oriented programming paradigm, type conversion allows programs also to treat objects of one type as one of another. One must do it carefully as type casting can lead to loss of data.

Automatic type conversion
Automatic type conversion (or standard conversion) happens whenever the compiler expects data of a particular type, but the data is given as a different type, leading to an automatic conversion by the compiler without an explicit indication by the programmer.

When an expression requires a given type that cannot be obtained through an implicit conversion or if more than one standard conversion creates an ambiguous situation, the programmer must explicitly specify the target type of the conversion. If the conversion is impossible it will result in an error or warning at compile time. Warnings may vary depending on the compiler used or compiler options.

This type of conversion is useful and relied upon to perform integral promotions, integral conversions, floating point conversions, floating-integral conversions, arithmetic conversions, pointer conversions.

In the example above, in the first case an expression of type float is given and automatically interpreted as an integer. In the second case (more subtle), an integer is given and automatically interpreted as a float.

There are two types of automatic type conversions between numeric types: promotion and conversion. Numeric promotion causes a simple type conversion whenever a value is used, while more complex numeric conversions can take place if the context of the expression requires it.

 * Any automatic type conversion is an implicit conversion if not done explicitly in the source code.

Automatic type conversions (implicit conversions) can also occur in the implicit "decay" from an array to a corresponding pointer type based or as a user defined behavior. We will cover that after we introduce classes (user defined types) as the automatic type conversions of references (derived class reference to base class reference) and pointer-to-member (from pointing to member of a base class to pointing to member of a derived class).

Promotion
A numeric promotion is the conversion of a value to a type with a wider range that happens whenever a value of a narrower type is used. Values of integral types narrower than  (,  ,  ,   and  ) will be promoted to   if possible, or   if   can't represent all the values of the source type. Values of  type will also be converted to , and in particular   will get promoted to 1 and   to 0.

In the code above, the values of  and   are both of type   and could be added and assigned as such. However, in C++ they will each be promoted to  before being added, and the result converted back to   afterwards. The reason for this is that the  type is designed to be the most natural integer representation on the machine architecture, so requiring that the compiler do its calculations with smaller types may cause an unnecessary performance hit.

Since the C++ standard guarantees only the minimum sizes of the data types, the sizes of the types commonly vary between one architecture and another (and may even vary between one compiler and another). This is the reason why the compiler is allowed the flexibility to promote to  or   as necessary.

Promotion works in a similar way on floating-point values: a  value will be promoted to a   value, leaving the value unchanged.

Since promotion happens in cases where the expression does not require type conversion in order to be compiled, it can cause unexpected effects, for example in overload resolution:

Since  is a , you might expect that the expression   would also be a  , but in fact   is promoted to  , and the   overload is selected.

Numeric conversion
After any numeric promotion has been applied, the value can then be converted to another numeric type if required, subject to various constraints.

A value of any integer type can be converted to any other integer type, and a value of an enumeration type can be converted to an integer type. This only gets complicated when overflow is possible, as in the case where you convert from a larger type to a smaller type. In the case of conversion to an unsigned type, overflow works in a nice predictable way: the result is the smallest unsigned integer congruent to the value being converted (modulo $$2^n$$, where $$n$$ is the number of bits in the destination type).

When converting to a signed integer type where overflow is possible, the result of the conversion depends on the compiler. Most modern compilers will generate a warning if a conversion occurs where overflow could happen. Should the loss of information be intended, the programmer may do explicit type casting to suppress the warning; bit masking may be a superior alternative.

Floating-point types can be converted between each other, but are even more prone to platform-dependence. If the value being converted can be represented exactly in the new type then the exact conversion will happen. Otherwise, if there are two values possible in the destination type and the source value lies between them, then one of the two values will be chosen. In all other cases the result is implementation-defined.

Floating-point types can be converted to integer types, with the fractional part being discarded.

A value of an integer type can be converted to a floating point type. The result is exact if possible, otherwise it is the next lowest or next highest representable value (depending on the compiler).

Explicit type conversion (casting)
Explicit type conversion (casting) is the use of direct and specific notation in the source code to request a conversion or to specify a member from an overloaded class. There are cases where no automatic type conversion can occur or where the compiler is unsure about what type to convert to, those cases require explicit instructions from the programmer or will result in error.

Specific type casts
The C++ language introduces several new casting operators to address the shortcomings of the old C-style casts such as a clearer syntax, improved semantics and type-safe conversions. All these casting operators share a similar syntax and are used in a manner similar to templates. With these new keywords casting becomes easier to understand, find, and maintain.

The basic explicit form of typecasting is the static cast.
 * The basic form of type cast

A static cast looks like this:

The compiler will try its best to interpret the expression as if it were of type type. This type of cast will not produce a warning, even if the type is demoted.

The cast can be used to suppress the warning as shown above. cannot do all conversions; for example, it cannot remove const qualifiers, and it cannot perform "cross-casts" within a class hierarchy. It can be used to perform most numeric conversions, including conversion from a integral value to an enumerated type.

Old C-style casts
Other common type casts exist, they are of the form type(expression) (a functional, or function-style, cast) or (type)expression (often known simply as a C-style cast). The format of (type)expression is more common in C (where it is the only cast notation). It has the basic form:

A C-style cast can, in a single line of source code, make two conversions. For instance remove a variable consteness and alter its type. In C++, the old C-style casts are retained for backwards compatibility.

There are several shortcomings in the old C-style casts:
 * 1) They allows casting practically any type to any other type, leading to lots of unnecessary trouble - even to creating source code that will compile but not to the intended result.
 * 2) The syntax is the same for every casting operation, making it impossible for the compiler and users to tell the intended purpose of the cast.
 * 3) Hard to identify in the source code.

The C++ specific cast keyword are more controlled. Some will make the code safer since they will enable to catch more errors at compile-time, and all are easier to search, identify and maintain in the source code. Performance-wise they are the same with the exception of, for which there is no C equivalent. This makes them generally preferred.


text:
Puzzles/Arithmetical puzzles/Hens and Eggs

Puzzles | Arithmetical puzzles

If $$1 \frac{1}{2}$$ hens lay $$1 \frac{1}{2}$$ eggs in $$1 \frac{1}{2}$$ days, how many eggs does one hen lay in one day?

solution


text:
Category:Hot Dog recipes

Recipes involving hot dogs.

title: Category:Hot Dog recipes


text:
C++ Programming/Operators/Operator Overloading

Operator overloading
Operator overloading (less commonly known as ad-hoc polymorphism) is a specific case of polymorphism (part of the OO nature of the language) in which some or all operators like +, = or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. Operator overloading is usually only syntactic sugar. It can easily be emulated using function calls.

Consider this operation:

Using operator overloading permits a more concise way of writing it, like this: a + b * c

(Assuming the * operator has higher precedence than +.)

Operator overloading can provide more than an aesthetic benefit, since the language allows operators to be invoked implicitly in some circumstances. Problems, and critics, to the use of operator overloading arise because it allows programmers to give operators completely free functionality, without an imposition of coherency that permits to consistently satisfy user/reader expectations. Usage of the  operator is an example of this problem.

Will return twice the value of a if a is an integer variable, but if a is an output stream instead this will write "1" to it. Because operator overloading allows the programmer to change the usual semantics of an operator, it is usually considered good practice to use operator overloading with care.

To overload an operator is to provide it with a new meaning for user-defined types. This is done in the same fashion as defining a function. The basic syntax follows (where @ represents a valid operator):

Not all operators may be overloaded, new operators cannot be created, and the precedence, associativity or arity of operators cannot be changed (for example ! cannot be overloaded as a binary operator). Most operators may be overloaded as either a member function or non-member function, some, however, must be defined as member functions. Operators should only be overloaded where their use would be natural and unambiguous, and they should perform as expected. For example, overloading + to add two complex numbers is a good use, whereas overloading * to push an object onto a vector would not be considered good style.

 * A simple Message Header

Operators as member functions
Aside from the operators which must be members, operators may be overloaded as member or non-member functions. The choice of whether or not to overload as a member is up to the programmer. Operators are generally overloaded as members when they:

 * 1) change the left-hand operand, or
 * 2) require direct access to the non-public parts of an object.

When an operator is defined as a member, the number of explicit parameters is reduced by one, as the calling object is implicitly supplied as an operand. Thus, binary operators take one explicit parameter and unary operators none. In the case of binary operators, the left hand operand is the calling object, and no type coercion will be done upon it. This is in contrast to non-member operators, where the left hand operand may be coerced.

Arithmetic operators

 * + (addition)
 * - (subtraction)
 * * (multiplication)
 * / (division)
 * % (modulus)

As binary operators, these involve two arguments which do not have to be the same type. These operators may be defined as member or non-member functions. An example illustrating overloading for the addition of a 2D mathematical vector type follows. It is good style to only overload these operators to perform their customary arithmetic operation. Because operator has been overloaded as member function, it can access private fields.

Bitwise operators

 * ^ (XOR)
 * | (OR)
 * & (AND)
 * ~ (complement)
 * << (shift left, insertion to stream)
 * >> (shift right, extraction from stream)

All of the bitwise operators are binary, except complement, which is unary. It should be noted that these operators have a lower precedence than the arithmetic operators, so if ^ were to be overloaded for exponentiation, x ^ y + z may not work as intended. Of special mention are the shift operators, < >. These have been overloaded in the standard library for interaction with streams. When overloading these operators to work with streams the rules below should be followed:

 * 1) overload < > as friends (so that it can access the private variables with the stream be passed in by references)
 * 2) (input/output modifies the stream, and copying is not allowed)
 * 3) the operator should return a reference to the stream it receives (to allow chaining, cout << 3 << 4 << 5)

 * An example using a 2D vector:

Assignment operator
The assignment operator, =, must be a member function, and is given default behavior for user-defined classes by the compiler, performing an assignment of every member using its assignment operator. This behavior is generally acceptable for simple classes which only contain variables. However, where a class contains references or pointers to outside resources, the assignment operator should be overloaded (as general rule, whenever a destructor and copy constructor are needed so is the assignment operator), otherwise, for example, two strings would share the same buffer and changing one would change the other.

In this case, an assignment operator should perform two duties:

 * 1) clean up the old contents of the object
 * 2) copy the resources of the other object

For classes which contain raw pointers, before doing the assignment, the assignment operator should check for self-assignment, which generally will not work (as when the old contents of the object are erased, they cannot be copied to refill the object). Self assignment is generally a sign of a coding error, and thus for classes without raw pointers, this check is often omitted, as while the action is wasteful of cpu cycles, it has no other effect on the code.

 * Example:

Another common use of overloading the assignment operator is to declare the overload in the private part of the class and not define it. Thus any code which attempts to do an assignment will fail on two accounts, first by referencing a private member function and second fail to link by not having a valid definition. This is done for classes where copying is to be prevented, and generally done with the addition of a privately declared copy constructor

 * Example:

Relational operators

 * == (equality)
 * != (inequality)
 * > (greater-than)
 * < (less-than)
 * >= (greater-than-or-equal-to)
 * <= (less-than-or-equal-to)

All relational operators are binary, and should return either true or false. Generally, all six operators can be based off a comparison function, or each other, although this is never done automatically (e.g. overloading > will not automatically overload < to give the opposite). There are, however, some templates defined in the header ; if this header is included, then it suffices to just overload operator== and operator<, and the other operators will be provided by the STL.

Logical operators

 * ! (NOT)
 * && (AND)
 * || (OR)

The logical operators AND are used when evaluating two expressions to obtain a single relational result.The operator corresponds to the boolean logical operation AND,which yields true if operands are true,and false otherwise.The following panel shows the result of operator evaluating the expression.

The ! operator is unary, && and || are binary. It should be noted that in normal use, && and || have "short-circuit" behavior, where the right operand may not be evaluated, depending on the left operand. When overloaded, these operators get function call precedence, and this short circuit behavior is lost. It is best to leave these operators alone.

If the result of Function1 is false, then Function2 is not called. Both Function3 and Function4 will be called no matter what the result of the call is to Function3 This is a waste of CPU processing, and worse, it could have surprising unintended consequences compared to the expected "short-circuit" behavior of the default operators. Consider:
 * Example:

Compound assignment operators

 * += (addition-assignment)
 * -= (subtraction-assignment)
 * *= (multiplication-assignment)
 * /= (division-assignment)
 * %= (modulus-assignment)
 * &= (AND-assignment)
 * |= (OR-assignment)
 * ^= (XOR-assignment)
 * <<= (shift-left-assignment)
 * >>= (shift-right-assignment)

Compound assignment operators should be overloaded as member functions, as they change the left-hand operand. Like all other operators (except basic assignment), compound assignment operators must be explicitly defined, they will not be automatically (e.g. overloading = and + will not automatically overload +=). A compound assignment operator should work as expected: A @= B should be equivalent to A = A @ B. An example of += for a two-dimensional mathematical vector type follows.

Increment and decrement operators

 * ++ (increment)
 * -- (decrement)

Increment and decrement have two forms, prefix (++i) and postfix (i++). To differentiate, the postfix version takes a dummy integer. Increment and decrement operators are most often member functions, as they generally need access to the private member data in the class. The prefix version in general should return a reference to the changed object. The postfix version should just return a copy of the original value. In a perfect world, A += 1, A = A + 1, A++, ++A should all leave A with the same value.

Often one operator is defined in terms of the other for ease in maintenance, especially if the function call is complex.
 * Example:

Subscript operator
The subscript operator, [ ], is an operator which can take in any number of arguments (much like a function call) but usually one. It also must be a member function (hence it make take only one explicit parameter, the index). The subscript operator is not limited to taking an integral index. For instance, the index for the subscript operator for the std::map template is the same as the type of the key, so it may be a string etc. The subscript operator is generally overloaded twice; as a non-constant function (for when elements are altered), and as a constant function (for when elements are only accessed).

Function call operator
The function call operator, , is generally overloaded to create objects which behave like functions, or for classes that have a primary operation. The function call operator must be a member function, but has no other restrictions - it may be overloaded with any number of parameters of any type, and may return any type. A class may also have several definitions for the function call operator.

Address of, Reference, and Pointer operators
These three operators, operator&, operator* and operator-> can be overloaded. In general these operators are only overloaded for smart pointers, or classes which attempt to mimic the behavior of a raw pointer. The pointer operator, operator-> has the additional requirement that the result of the call to that operator, must return a pointer, or a class with an overloaded operator->. In general A == *&A should be true.

Note that overloading operator& invokes undefined behavior:
 * ISO/IEC 14882:2003, Section 5.3.1
 * The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator& as a member function, then the behavior is undefined (and no diagnostic is required).

These are extremely simplified examples designed to show how the operators can be overloaded and not the full details of a SmartPointer or SmartReference class. In general you won't want to overload all three of these operators in the same class.
 * Example:

Comma operator
The comma operator, , can be overloaded. The language comma operator has left to right precedence, the operator, has function call precedence, so be aware that overloading the comma operator has many pitfalls.

For non overloaded comma operator, the order of execution will be Function1, Function2; With the overloaded comma operator, the compiler can call either Function1, or Function2 first.
 * Example:

Member Reference operators
The two member access operators, operator-> and operator->* can be overloaded. The most common use of overloading these operators is with defining expression template classes, which is not a common programming technique. Clearly by overloading these operators you can create some very unmaintainable code so overload these operators only with great care.

When the -> operator is applied to a pointer value of type (T *), the language dereferences the pointer and applies the. member access operator (so x->m is equivalent to (*x).m). However, when the -> operator is applied to a class instance, it is called as a unary postfix operator; it is expected to return a value to which the -> operator can again be applied. Typically, this will be a value of type (T *), as in the example under Address of, Reference, and Pointer operators above, but can also be a class instance with operator-> defined; the language will call operator-> as many times as necessary until it arrives at a value of type (T *).

Memory management operators

 * new (allocate memory for object)
 * new[ ] (allocate memory for array)
 * delete (deallocate memory for object)
 * delete[ ] (deallocate memory for array)

The memory management operators can be overloaded to customize allocation and deallocation (e.g. to insert pertinent memory headers). They should behave as expected, new should return a pointer to a newly allocated object on the heap, delete should deallocate memory, ignoring a NULL argument. To overload new, several rules must be followed:

 * new must be a member function
 * the return type must be void*
 * the first explicit parameter must be a size_t value

To overload delete there are also conditions:

 * delete must be a member function (and cannot be virtual)
 * the return type must be void
 * there are only two forms available for the parameter list, and only one of the forms may appear in a class:
 * void*
 * void*, size_t

Conversion operators
Conversion operators enable objects of a class to be either implicitly (coercion) or explicitly (casting) converted to another type. Conversion operators must be member functions, and should not change the object which is being converted, so should be flagged as constant functions. The basic syntax of a conversion operator declaration, and declaration for an int-conversion operator follows. Notice that the function is declared without a return-type, which can easily be inferred from the type of conversion. Including the return type in the function header for a conversion operator is a syntax error.

Operators which cannot be overloaded

 * ?: (conditional)
 * . (member selection)
 * .* (member selection with pointer-to-member)
 * :: (scope resolution)
 * (object size information)
 * typeid (object type information)
 * static_cast (casting operator)
 * const_cast (casting operator)
 * reinterpret_cast (casting operator)
 * dynamic_cast (casting operator)

To understand the reasons why the language doesn't permit these operators to be overloaded, read "Why can't I overload dot, ::,, etc.?" at the Bjarne Stroustrup's C++ Style and Technique FAQ ( http://www.stroustrup.com/bs_faq2.html#overload-dot ).


text:
C++ Programming/Code/IO/Streams/string

The string class
The string class is a part of the C++ standard library, used for convenient manipulation of sequences of characters, to replace the static, unsafe C method of handling strings. To use the string class in a program, the header must be included. The standard library string class can be accessed through the std namespace.

The basic template class is  and its standard specializations are   and.

Basic usage
Declaring a std string is done by using one of these two methods:

Text I/O
This section will deal only with keyboard and text input. There are many other inputs that can be read (mouse movements and button clicks, etc), but these will not be covered in this section, even reading the special keys of the keyboard will be excluded.

Perhaps the most basic use of the string class is for reading text from the user and writing it to the screen. In the header file iostream, C++ defines an object named cin that handles input in much the same way that cout handles output.

The >> operator will cause the execution to stop and will wait for the user to type something. If the user types a valid integer, it will be converted into an integer value and stored in x.

If the user types something other than an integer, the compiler will not report an error. Instead, it leaves the old content (a "random" meaningless value) in x and continues.

This can then be extended into the following program:

Although a string may hold a sequence containing any character—including spaces and nulls—when reading into a string using cin and the extraction operator (>>) only the characters before the first space will be stored. Alternatively, if an entire line of text is desired, the getline function may be used:

Getting user input
Fortunately, there is a way to check and see if an input statement succeeds. We can invoke the good function on cin to check what is called the stream state. good returns a bool: if true, then the last input statement succeeded. If not, we know that some previous operation failed, and also that the next operation will fail.

Thus, getting input from the user might look like this:

cin can also be used to input a string:

As with the scanf function from the Standard C Library, this statement only takes the first word of input, and leaves the rest for the next input statement. So, if you run this program and type your full name, it will only output your first name.

You may also notice the >> operator doesn't handle errors as expected (for example, if you accidentally typed your name in a prompt for a number.) Because of these issues, it may be more suitable to read a line of text, and using the line for input — this is performed using the function called getline.

The first argument to getline is cin, which is where the input is coming from. The second argument is the name of the string variable where you want the result to be stored.

getline reads the entire line until the user hits Return or Enter. This is useful for inputting strings that contain spaces.

In fact, getline is generally useful for getting input of any kind. For example, if you wanted the user to type an integer, you could input a string and then check to see if it is a valid integer. If so, you can convert it to an integer value. If not, you can print an error message and ask the user to try again.

To convert a string to an integer you can use the strtol function defined in the header file cstdlib. (Note that the older function atoi is less safe than strtol, as well as being less capable.)

If you still need the features of the >> operator, you will need to create a string stream as available from <sstream>. The use of this stream will be discussed in a later chapter.

More advanced string manipulation
We will be using this dummy string for some of our examples.

This invokes the default constructor with a  argument. Default constructor creates a string which contains nothing, i.e. no characters, not even a  (however std::string is not null terminated).

Will trigger the copy constructor. knows enough to make a deep copy of the characters it stores.

This will copy strings using assignment operator. Effect of this code is same as using copy constructor in example above.

Size
So for example one might do:

The methods  and   both return the size of the string object. There is no apparent difference. Remember that the last character in the string is  and not. Like in C-style strings, and arrays in general,  starts counting from 0.

I/O
The shift operators ( and  ) have been overloaded so you can perform I/O operations on   and   objects, most notably ,  , and filestreams. Thus you could just do console I/O like this:

Alternatively, if you want to read entire lines at a time, use. Note that this is not a member function. will retrieve characters from input stream  and assign them to   until   is reached or   is encountered. will reset the input string before appending data to it. can be set to any  value and acts as a general delimiter. Here is some example usage:

Because of the way  works (i.e. it returns the input stream), you can nest multiple   calls to get multiple strings; however this may significantly reduce readability.

Operators
in s can be accessed directly using the overloaded subscript  operator, like in   arrays:

prints "Hl".

supports casting from the older C string type. You can also assign or append a simple  to a string. Assigning a  to a   is as simple as

If you want to do it character by character, you can also use

Not surprisingly,  and   are also defined! You can append another, a   or a   to any string.

The comparison operators  all perform comparison operations on strings, similar to the C strcmp function. These return a true/false value.

Searching strings
You can use the  member function to find the first occurrence of a string inside another. will look for  inside   starting from position   and return the position of the first occurrence of the. For example:

Will simply print "4" which is the index of the first occurrence of "o" in. If we want the "o" in "World", we need to modify  to point past the first occurrence. would return 4, while  would give 7. If the substring isn't found,  returns  .This simple code searches a string for all occurrences of "wiki" and prints their positions:

The function  works similarly, except it returns the last occurrence of the passed string.

Inserting/erasing
You can use the  member function to insert another string into a string. For example:

Would return Hello Human World!

You can use  to remove a substring from a string. For example: Would return Hello!

You can use  to extract a substring from a string. For example: Would return World.

Backwards compatibility
For backwards compatibility with C/C++ functions which only accept  parameters, you can use the member functions   and   to return a temporary   string you can pass to a function. The difference between these two functions is that  returns a null-terminated string while   does not necessarily return a null-terminated string. So, if your legacy function requires a null-terminated string, use, otherwise use   (and presumably pass the length of the string in as well).

String Concatenation
Strings can be concatenated(appended) together by simply using the + operator Output here will be "Hello World"

Appending Strings
Another thing to note is that instead of the + operator or concatenation, the  class member function can be used to concatenate one string to another. The  object is permitted to be a string object or a C-string. This will add the string in the parenthesis to the string which is calling.

It should also be noted that the append function can be used to append a string at a specific character location in the string. If a programmer puts,   number of characters from position   in string   will be appended to the end of. For example, in the following code, there are two strings. 5 characters from the second string, starting with position 8 of  will be appended to the end of the first string,.

The code above will append the word  to the end of the first string, and then print   on the screen.

String Conversion to signed integer
Sometimes we want to convert strings into numbers. To do so we can use stoi function which takes a string as an argument and returns the value. To convert these strings to a number we save the stoi of the string variable in an integer variable. Output will be: Before stoi string :12023 and after stoi int: 12023 Before stoi string :1 and after stoi int: 1 Before stoi string :1232 and after stoi int: 1232

Integer Conversion to String
If we instead want to do the opposite and convert an integer to a string, we can use the to_string function, which takes an integer as an argument and returns the integer as a string. To convert this integer to a string, we call the to_string function. The integer variable is passed into the function as an argument. The function will then return that integer as a string, which can then be assigned to a string variable. Output will be: Before to_string int:12023 and after to_string string:12023

String Formatting
Strings can only be appended to other strings, but not to numbers or other datatypes, so something like  would not result in a string with the content. To convert other datatypes into string there exist the class, found in the include file. acts exactly like, the only difference is that the output doesn't go to the current standard output as provided by the operating system, but into an internal buffer, that buffer can be converted into a   via the   method.

title: C++ Programming/Code/IO/Streams/string