CS 1400
Classes, Objects,and Primitive Data
Version 1.1
Topics
Primitive data typesVariables and constantsDeclarations
AssignmentInput and output
Classes and objects
Style
Objectives
At the completion of this topic, students should be able to:
Create proper identifiers in a C++ programDescribe the difference between an object and primitive data
Describe the primitive data types in the C++ languageWrite C++ programs that correctly
* use declarations* use assignment statements* use literal data* use cin and cout* format simple floating point data
Describe the object model of programming
Describe the way that data is stored in the computer
In order to be able to refer to a piece of datain a program, we have to give that piece of data a name. These names are called identifiers.
IdentifiersThe name that you use to refer to a piece of dataor a function in C++ is called an identifier.
A C++ identifier must begin with either a letteror an underscore character. [a-zA-Z_]
The remaining characters may be letters, digits, orthe underscore character. All other characters areinvalid. [a-zA-Z_0-9]*
Identifiers can be of any length. Be reasonable!
Identifiers are case sensitive.
Some Valid Identifiers
xx1_abcsumdata2oldValue
It is common in C++ to run words togetherLike this. Just capitalize all words after the first.
Some Invalid Identifiers
123&change1_dollarmy-data
Keywords
C++ has a set of built in keywords that are considered tobe part of the language. You cannot use any of these asidentifiers in your program. A complete list can be foundin your book. Examples include
boolbreakcharclassconstdo…
A C++ program manages two general kinds of information
Primitive Datathe most basic forms of data - numbers and characters int, double, char, bool
Objectsmore complex data – usually composed ofmany pieces of primitive data cout, cin, string, DATA
Primitive Data
Primitive data elements all have a data type
The data type defines the possible set of valuesthat a primitive data element can have, and theoperations that can be performed on the data.
Numeric Data Types
Type Storage Max Value
short 16 bits -32,766 to 32,767int 32 bits - 2,147,483,646 to 2,147,483,647long 32 bits - 2,147,483,646 to 2,147,483,647float 32 bits over 1038
double64 bits over 10308
integertypes
realtypes
The amount of storage allocated to variousdata types is not defined by the C++ language,but is dependent upon the underlying hardware.The following are examples only, and may differon your computer.
there are unsigned version of each of integer types.
Integer NumbersIntegers are whole numbers they have nofractional part.
The most common integer data type is int
Integer operations includeadditionsubtractionmultiplicationdivisionremainderassignment
Examples of Integers
10-532729053011234567890L
Real NumbersReal numbers have fractional parts
Real numbers are often written in scientific format
The most common real data type is double
Operations on real numbers includeadditionsubtractiondivisionmultiplicationassignment
Examples of Real Numbers
10.5-5.02327.9812905301.0040.0000239897F-1.56E-4
Character Data
Different standards exist for encoding characters
The ASCII standard, finalized in 1968, uses 7 bits for each character.In the ASCII standard, 1000001 is interpreted as the character ‘A’.
7 bits only allows for the definition of 128 unique characters. Subsequentstandards (ISO8859 and ISO10646) define much larger, multi-nationalcharacter sets. However, both are supersets of ASCII.
Character data is defined by the keyword char
When interpreted as a character, certain bit patternsrepresent printable characters and control characters.
Control Characters
Control characters are characters that donot print, but cause some action, such as movingto a new line, to occur. In C++ we write control characters as a backslash, followed by a characterthat denotes the action to be taken.
\b backspace\t tab\n new-line\r carriage return\\ back slash
Boolean Data
A piece of Boolean data can only have oneof two values:
true ( none zero )false (0)
Boolean data is defined by the keyword bool
Variables and Constants
A variable is a name for a memory locationthat holds some piece of data. The valuestored in that location may change duringexecution of the program.
A constant is a name for a memory locationthat holds some piece of data, where thevalue of the data will not change duringexecution of the program.
Declarations
In C++, all variables and constants must be declared before they are used in a program.
C++ is what is known as a strongly typed language.This means that we must tell the compiler what thedata type is for every variable. The compiler thenchecks all operations to make sure that they arevalid for the given type of data.
Question . . .
Assume that you are able to peek into the memory of yourcomputer, and you see the bit pattern
00000000 00000000 00000000 01100010
What does this bit pattern mean?
The correct answer is that you don’t know.Unless you know what type of data you arelooking at, it is impossible to interpret thebits stored in memory without knowing itstype in storage.
Integer RepresentationIn modern digital computers, integer numbers are stored internally in a binary format. The number of bits used tostore an integer depends on the type of processor in the computer, but is typically 32 or 64 bits.
Example: the integer 5, when storedin a typical Intel class machine is
00000000 00000000 00000000 00000101
Floating Point Representation
Numbers that contain decimal points are stored internally in a very different format. The exact
format depends upon the processor used in the computer, but in general it looks like:
sign exponent Mantissa or Coefficient
for example, the number 6,045.03 (0.604503 x 104) would have an exponent of 4 and a
mantissa of .604503
The actual binary representation is beyond thescope of this course.
Character Representation
Characters are stored internally in a codedformat. For example, using the standardASCII code, the character ‘A’ would be stored as 0100 0001. Most modern computerlanguages support a multiple byte charactercode called Unicode.
The ASCII Code Table
Computer Instructions
Locations in memory can hold both dataand instructions. A special register, calledthe program counter points to the nextinstruction in memory to be executed. The computer fetches the next instruction from memory. The program counter moves to the next instruction. The computer thendecodes the instruction it just fetched.
Machine Language
We call the instructions stored in computer memory machine language instructions. They are defined by the chip manufacturer. For example, the machine instruction
00110011 00011010
might mean something like
take the byte stored in memory location 0024 and put it into register ‘A’.
Summary
Integers straight binary representation
Real Numbers split into sign, exponent and coefficient
Characters coded bytes – ASCII
Instructions coded words – machine language
Declaring a Variable
int someNumber;char firstLetter;bool theAnswer;
double density = 12.45;int hoursWorked = 14;char key = ‘g’;
this statement reservesspace in computer memoryfor an integer. We can then refer to the data in this location using the name “someNumber. ”
C++ does not initialize variables.
this statement reservesspace in computer memory for a character. The bit patternfor ‘g’ is then stored in thatlocation. We can now refer to thedata in this location using the name “key”
Declaring a Variable
int value1, value2, value3; //comma delimited list betterint value1;int value2;int value3;
This statement defines threevariables, all of which are ints.
Declaring a Variable
int value1= 12, value2= 4, value3= 21; betterint value1 = 12;int value2 = 4;int value3 = 21;
This statement defines threevariables, all of which are ints,and initializes them.
Declaring a Constant
const double PI = 3.1416;const int SCALE_VALUE = 14;
The keyword const means that this is a constant.You cannot change the value after it is declared.
We normally use all upper caseletters when writing the name of a constant.
Floating Point Constants
Consider the following declaration:
const float PI = 3.14159F;
the decimal signals that thisis a real number
the F signals that this literalvalue is a float data type andnot a double (the default).
Assignment
The easiest way to change the value of a variableis to use an assignment statement.
temperature = 68.4;
note that all statementsend with a semicolon.
the right hand side of the assignmentstatement may be a literal value, oran expression involving variables, literalvalues, and operators, or even functioncalls.
the expression on the rightside of the operator is evaluatedand the resulting value is storedin the storage location allocatedto the variable “temperature”
rvaluelvalue
Assignment Compatibility
In general, it is invalid to assign a variable of one typeto a variable of another. For example,
int a = 6.52;
The compiler will issue the warning
“conversion from 'double' to 'int', possible loss of data”
This means that the code will compile, but may not produce the results expected.
Assignment Compatibility
Note that you can do this assignment.
float a = 6;
The compiler will force a conversion to 6.0
The compiler will allow you to do Widening Conversions
float a = 3;
because no information is lost.
The compiler will warn you if you do Narrowing Conversion
int pi = 3.14159;
because information will be lost.
Un-initialized Data
In C++, no initialization is done when a data element isdeclared. The value of that data element will be basedon whatever bits happen to be in that storage locationwhen your program starts execution. It will likely besomething (bad) left over from another running program!
So …… always initialize data when it is declared.
Initializing Data
int numOne = 5, numTwo = 4, numThree = 17;
int numOne (5), numTwo (4), numThree (17);
int numOne = 5;int numTwo = 4;int numThree = 17;
Literal Data
In the statement sum = a + 5;
the value 5 is what is called literal data.
It is good programming practice to use constantsinstead of literal data in your program.
const int MAX = 5;...sum = a + MAX;
Exceptions are 1, -1 and 0
We use the term “Magic Numbers” to refer toliteral data that is written into an expressionin your program.
double avgTemperature = sumTemperature / 10;
This is a magic number
You do not want magic numbers in your programs.They make programs hard to maintain. You willLose points if I see magic numbers in your programs.
Objects and Classes
Object oriented languages give programmers theability to model real-world objects.
for example, a car has attributes (data)* it is black* it has a 200 hp engine* it has 2 doors* it was built in 1943* etc
it also has behaviors (functions)* when you turn the key it starts* when you press the brake it stops* when you push the horn it beeps* etc
object-oriented languagesencapsulate the data and thefunctions that operate on thatdata into an object.
size
color
getS
ize
( )
getColor( )
an object’s functionsmanage specific piecesof data inside the object.
External Function
functions outside ofthe object cannot see or manipulate the object’sdata, which is private.However, they can call public functions inside the object to accessthe data.
object
Classes
Later on, we will spend much more time talkingabout objects and classes. For now, just thinkof a class as a blueprint that the computer useswhen creating objects. When we write an objectoriented program, much of our time is devoted todesigning and writing classes. ostream (class) cout (object) istream (class) cin (object) string (class) stg (object)
Languages that primarily deal with objectsare called object-oriented languages.
Pure object oriented languages, like C# and Java,treat everything as an object.
C++ is sometimes called a hybrid language,because it has elements of a procedurallanguage and an object-oriented language.
The C Language
The C++ Language
The C language is a pureprocedural language. It wasdeveloped at AT&T’s Bell Labsin the 1970s by Brian Kernihan and Dennis Ritchie. It was firstused for writing and maintainingthe Unix operating system.
Bjarne Stroustrup of Bell Labsdeveloped the C++ languagein the early 1980’s by addingobject oriented capabilities toC (C with classes).
Some Convenient Objects
C++ has built in to it some objects that will make ourprogramming tasks much easier. The first of these wewill introduce are cin and cout
cin
cin an object of the istream class (#include <iostream>).This object represents the standard input stream. The cin object is created automatically for you.
keyboard buffercin program
keyboard buffer
cout an object of the ostream class (#include <iostream>). This object represents the standard output stream. It is also created automatically for you.
output buffercout program
cout
display buffer
a binary operator (it takes two operands)
the left hand operand must be an output stream
the right hand operand is converted into text the text data is then copied into the stream
The Stream Insertion Operator, <<
display buffer
int a = 5; a 0000 0000 0000 0101
the integer 5
0000 0000 0011 0101
the character 5
cout
cout << a;
5
multiple pieces of data are output bycascading the << operator …
cout << “The answer is “ << a;
special characters are added to the streamusing the escape character \
\t //tab\n //newlineetc …
cout << “The answer is “ << a << ‘\n’;
the endl stream manipulator can be added to the outputstream. It does two things:
It adds a new line to the stream.
It forces the buffer to be output
cout << “Hello” << endl;
Formatting Numbers
When outputting numbers with fractional partswe have to take care to make the output appearjust as we would like it. This does not happenautomatically.
To display a double or a float in standard decimal notation
cout.setf(ios::fixed);
setf( ) is a function in the cout object. It is responsible forsetting formatting flags. We will study these in much moredetail in a later section. In this case, we are setting theios::fixed flag. This makes the output appear as a normaldecimal number instead of in scientific notation.
cout.setf(ios::showpoint);
the ios::showpoint flag guarantees that a decimal pointwill be displayed in the output.
cout.precision(2);
the cout.precision( ) function determines how many digitswill be displayed after the decimal point.
The default formatting, is the“general” format. In this caseprecision defines the number ofdigits in total to be displayed
Example
double price = 78.5;cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precison(2);cout << “The price is $” << price << endl;
Also a binary operator
The left operand must be an input stream
Any initial white space is skipped, then the stream is read up to the
next white space character ( tab, space, new-line )
If necessary, the text just read is converted to match the type of the right operand. An error occurs if the conversion cannot be done.
The data is stored in the right operand
The stream extraction operator, >>
keyboard buffercin
int a;cin >> a;
a
0000 0000 0011 0101
the character 5
0000 0000 0000 0101
5 72 hello
reading stops when white space is encountered
you can also cascade the stream extraction operator:
cin >> a >> b;
You can control the size of an input field withthe setw( n ) stream manipulator.
cin >> setw(5) >> title;
cin.getThe get function of the istream class works similarto the stream extraction operator. With no parameter,it gets one character from the input stream.
cin.get( );
Reading a line into a string
This function is similar to cin.get( )except thatit reads an entire line of data, including spaces,and the data is stored in a string object. This isthe preferred way of reading in a line of data.
getline(cin, stringName);
cin.ignore( )
This function reads in a character and ignoresit. The character read in is discarded.
cin.ignore( );
cin.ignore( )
This version of the function reads in n charactersand ignores them.
cin.ignore(n);
This version of the function reads in n charactersor until it encounters the delimiter character,and ignores the characters read.
cin.ignore(n, ‘\n’);
cin.ignore( )
Why is this useful? Try the following code…
int numItems;string description;
cout << “\nenter the number of items and description: “;cin >> numItems;getline(cin, description);
When prompted, enter the data on two lines.
if(cin.rdbuf()->in_avail()!=0) cin.ignore(80,'\n');
Insure that the keyboard buffer is cleared!
Style
When writing programs in any programminglanguage, it is helpful to use a consistentstyle. Good software development organizationswill often dictate that programmers use a specificstyle. This makes it easier for everyone to maintainthe code that is being developed.
In this course, you are expected to follow certainstyle guidelines. They are available on the courseweb site.
Style - IdentifiersUse names that have meaning. Avoid single character, very short, or very long names.
Examples: Meaningful Names Baffling Names amount aisFinished xl
ConstantsAll upper case with words separated by an underscore
Example: SIZE Classes Title case (capitalization of the first letter in each word)
Example: class ImpleCalc{…}
Function names and VariablesLower case for the first word and title case for every word thereafter.
Example: makeDeposit( )
Style - Braces
Even though the C++ language does not always require braces for some statements it is good programming practice to provide them. Use braces liberally to visually delimit the beginning and end of code blocks. Including braces now avoids the possibility of errors creeping into your code when you add additional statements at the last minute.
Place the opening (left) brace { so that it lines up with the left side of class headers, function headers, conditional statements, or repetitive statements. Place the closing (right) brace } in the same column as the opening brace. Always enter braces in opening/closing pairs to avoid forgetting to add one or the other or both. For braces that span more than three to five lines, comment the ending brace to indicate its nature (e.g., //End if ).
Indentation
As you moved from block to block, indentat least three spaces. Indentation makes codemuch more readable.
Example
void reviewCode( ){ if ( meetsGuidelines ) { cout << “Proceed to the next assignment”; } else { cout << “Rework your documentation”; } //End if/else} //End reviewCode( )
Your Own Code Declaration
Every source code file must contain the followingdeclaration. Code that does not contain thisdeclaration will not be graded!
"I declare that the following source code was written solely by me. I understand that copying any source code, in whole or in part, constitutes cheating, and that I will receive a zero on this project if I am found in violation of this policy.
Magic Numbers
A magic number is any numeric literal other than 1, 0, or –1 used in your program. However if 1, 0 and –1 are used to represent something other than the integers 1, 0, or –1 they will be considered magic numbers. Unfortunately, most code you will see in C++ books or programming books in general will include magic numbers because it’s easier to code in the short run. In the long run, six months from today, you will be clueless as to what the number means. Therefore, DON’T USE MAGIC NUMBERS in your assignments.
Where are variables stored?
If a variable is declared inside of the curly bracketsthat define a function, then that variable is said to be local to the function. It is stored on the stack segment.
If a variable is declared outside of the curly brackets,that define a function, then that variable is said to be global and is stored in the data segment.
The code is stored in the code segement.
#include <iostream>using namespace std;
const float PI = 3.14149;
int main( ){ float radius;
cout << . . .
}
Declared inside ofcurly braces – stack seg
This is a local variable
Declared outside ofcurly braces – global (data seg)
#include <iostream>using namespace std;
const float PI = 3.14149;
int main( ){ float radius;
cout << . . .
}
Declared outside ofcurly braces – data segment
This is a global variable
Practice
Name the basic C++ data types.
Practice
Here is some data stored in the memory of thecomputer.
0000 0000 0000 1001
What is it’s value?
Practice
Suppose that you needed a Student objectin a course registration program.
What attributes might a Student have?
Practice
What kind of language is C++?
* Object Oriented * Procedural * Hybrid
Practice
In which part of computer storage iseach of the following stored?
* A global variable * A local variable
Practice
Name two objects that we have learned about in thislesson. To what class do they belong?
Name the classes that these objects are instantiedfrom. What is string?
Practice
Which operator is used to convert data into itscharacter representation and output it to thestandard output device?
Practice
Which operator is used to convert data from itscharacter representation and store it to in memoryin its binary representation?
Practice
Write a program that prints the message
“Hello, my name is Hal”.
Then the program will prompt the user for his or her full name. It then Will print
“Hello, users full name, how are you?”
Practice
Write a program that prints the message
“Hello, my name is Hal”.
Then the program will prompt the user for his or her name.It then Will print
“Hello, user name, how are you?”
Prompt the user to type in their age. Then print
“user name, you are n years old”
Practice
Write a program that prints the message
“Hello, my name is Hal”.
Then the program will prompt the user for his or her age.
Then prompt the user to type in their full name. Then print
“ Hello user name, you are n years old”
Practice
Write a program that prints the message
“C++ Rocks!”.
Inside a rectangle. Use |, +, and – to draw the rectangle.Your output should look like
+-------------+| C++ Rocks |+-------------+