
Chapter Two
Data Types in C++
Data types available in C++ be broadly classified into: (a) Fundamental data types, (b) Derived data types, (c) User defined data types.
(a) Fundamental Data Types
The primitive data types are: Integers, Floats, and Characters. Each of these again comes in several varieties, occupying different amounts of memory.
Integers:
They store whole numbers (positive / negative). They may be short, int or long. They may be signed or unsigned. Unsigned type cannot store negatives.
Floats & Doubles:
They store fractional numbers. They may be float for single-precision and double for double precision real numbers.
Characters: They store a single character of 1 byte. A Character literal (also called a Character constant) is enclosed in single quotes, (e. g. ‘A’ or ‘+’).
Characters are internally stored as integers, and they are inter-convertible, subject to the limitation imposed by a character being of size 1 byte, whereas an integer is of 2 bytes.
The actual memory size of the data types may vary from one implementation to another, and is hardware dependent. The particular sizes for a given system may be obtained by using sizeof(int), sizeof(double), etc.
(b) Derived Data Types:
These are Arrays, Pointers, Reference (alias names), and constants.
Arrays are collections of homogenous data elements, (such as a set of 10 integers or characters or floats) known by a common name (such as A) and each element referred to by using a subscript (e.g., A[4]). The subscript of the first element is 0.
Thus we may have an integer array, character array, etc.
eg. int a[4] = {2, 3, 5, 1}; cout << a[0];
Output: 2
Strings are regarded as character arrays terminated by ‘\0’ (null). Strings are a sequence of characters, defined within double quotes. Thus, ‘a’ is a character, but "a" is a string. "Computer" and "Hello! How are you?" are also strings (sometimes called string literals or string constants).
Example:
Char s[] = "This is a string"; cout << s;
Output: This is a string
Pointers are variables that hold the memory addresses. Thus int *ptr (asterisk marks it as a pointer) means ptr points to the memory location or address that stores an integer. The memory location of a variable is accessed using address-of (ampersand) operator.
Try the following code:
#include <iostream.h>
void main()
{
int a = 5;
int *ip = &a;// &ip is a pointer; address-of(&) operator
cout << a << endl; //endl for new linefeed
cout << ip << endl; //print the address
cout << *ip << endl; //value-of (*) operator
}
Output:5 //this is the value of a
0x4ba723e8 (or something similar) //the address of a in hex using & operator5 //the value stored at ip using *operator
Reference or alias names are introduced by the ampersand (&) sign. Thus int total; int &sum = total; means that sum is an alternative name for total; one cannot be changed without changing the other as well since they refer to the same memory location.
Constants or named constants that cannot be changed at runtime. A constant must be preceded by the keyword const and initialized at the time of declaration
eg. const float pi = 3.14f;
const interest_rate = 8;
Being constants, statements like pi= pi*2 or pi = 4.2 or interest_rate++ are not permitted.
[The chief use of const data types is to facilitate easy editing. If the interest rate changes to 7, only this line needs to be replaced. Otherwise every occurrence of 8 as interest rate would have to be replaced by 7 through the entire program - a tedious and time-consuming drudgery.]
C++ also permits the old C style: #define pi 3.14f to be written above main() and all sub-functions, immediately after #include <iostream.h>
(c) User defined data types:Classes consist of the features and methods (called member variables and member functions or methods) as a template for all Objects of the Class.
An overview of a class declaration is given below:
Class Student
{
int a, b; //member variables
void getdata(); //member functions
void add();
void display();
}
//now define the function bodies (i.e write codes for the functions)
Structures are collections of different types of variables under one name.
[Herein lies the distinction between ARRAY and STRUCTURE. The former is homogenous, all values should be of same type (integer, character, etc.) whereas structure admits of heterogeneous data types (a combinaton of character, integers, floats, etc.]
struct student //keyword struct for structure
{
char name[];
float height;
int rollnumber;
};
The chief difference between Class and Structure is that a Structure consists of variables only, but a Class gives rise to Objects that encapsulate variables along with related functions.
Unions: The same memory location is shared by different variables at different times of program run, thus:
union alpha
{
int i;
char c;
};
Enumeration: This creates alternative names for integer constants, thus:
enum {red, blue, green};
is same as:
const int red =0; const int blue = 1; const int green = 2;
Although by default the first value is assigned 0, we can change it thus:
enum {red = 10, blue, green = 15, orange, violet};
This would mean:
const int red = 10; const int blue = 11; const int green = 15; const int orange = 16; const int violet = 17;
VARIABLES: Every named variable (or symbolic variable) has a value (rvalue) and a memory-address (lvalue). Pointers are used to access lvalues.
TYPE CASTING: The explicit user defined conversion of an operand to a specific type is called type casting, thus:
int a = 12;
int b = (int) a/10; //b = 1
What are Tokens? These are the smallest building blocks in a program, corresponding to the idea of atoms in Chemistry.
KEYWORDS: They convey a special meaning to the compiler (e.g. case, class, do, for, goto, if, long, new, short, switch, void, while, etc.) These are reserved words and should not be used as variable names.
IDENTIFIERS: An arbitrary sequence of valid characters used as names (alphabets, numerals, underscore, etc.). It is case sensitive. For example, My_file, File_29_13, rate_of_int, etc.)
LITERALS (Constants) are data items whose value cannot change during runtime. They may be numeric (integer/decimal like 35, -28.5, etc.), character constants (like ‘a’, ‘A’, etc.), string literals (e.g., "Enter a number…"), Punctuations /Separators (e.g., [], //, etc.) or Operators (e.g., +, -, <, >=, etc.)
SPECIAL CHARACTERS (escape sequences): A backslash followed by a character or characters (such as \n) forms what is treated by the compiler as a single-character-equivalent; e.g., \f represents form feed, \b represents backspace, \t represents horizontal tab, \v represents vertical tab, \n represents new-line-feed, \’ and \" represent quotes, \r represents carriage return, \0 represents null, etc. The symbolic constant endl is equivalent to \n and is used to force a line break in output.
For example:
cout << "abc" << " " << "def"
Output:
abc def
cout << "abc" << endl << "def"
Output:
abc
def
Expressions: An Expression is a meaningful combination of signs of operations and variable or constant operands. In addition to +, -, *, / for the fundamental operations, % is used as modulus operator to get the remainder of an integer division. Also, ++ and -- are used as increment and decrement operators.
A unary operator takes one operand (e.g. count++) whereas a binary operand takes two operands (e. g. a * b).
Precedence of Operators:
In an expression, the precedence is as follows-
(i) ++, -- (Increment / Decrement)
(ii) exponentiation
(iii) *, /, % (Multiplication, Division, Modulus)
(iv) +, - (Addition, Subtraction)
Thus ++a * --b will be interpreted as (++a) * (--b). Similarly, a + b * c will be evaluated as (a) + (b * c). To get the sum of a, b first and then multiply the result by c, we write it as (a + b) * c.
Also note that L is used to declare a number as long and f is used to declare a number as float; e. g.
long a = 45L; float b = 3.5f
C++ Shorthand:
If n is a numeric variable, the following notations are valid:
n+=10 means n=n+10; n*=2 means n=n*2; etc.
In addition, n++ (or ++n) and n-- (or --n) stand for n=n+1 and n=n-1. The distinction between pre- and post- increment / decrement is discussed later.
C++ library and header files: C++ library has a rich collection of ready-to-use pre-written, pre-compiled codes to accomplish commonly required tasks. They are just object files. Examples are:
toupper (), tolower () [to change case of characters];
log (), abs () pow () [mathematical functions];
sin (r), cos (r), tan (r) [for trigonometric calculations];
strlen (), strcmp (), strcat (), strcpy () [for string manipulations];
and others.
As we shall see, all functions should be declared before use. The necessary function declaration (function prototype or signature) are contained in header files, which is included using the pre-processor directive #include <file_name.h>
The header files are simply text files, and are inserted into the code before compilation. The external modules are linked, and only then is the object file ready for execution. Some useful header files and their applications are given below:
<iostream.h> : for cin / cout (input / output)
<math.h> : for math functions like powers, sq roots, sin, tan, log
<stdlib.h> : for conversions, search / sort, etc.
<string.h> for string functions (strlen, strcat, strcpy, strcmp)
<conio.h> : console I / O, including clrscr()
<ctype.h> for isalpha, isdigit, toupper, tolower, islower, isupper, etc.
General Concepts and Features of OOP:
DATA ABSTRACTION: It refers to the act of representing essential features without the background details. We focus on WHAT aspect rather than HOW aspect of the program.
DATA ENCAPSULATION: Data and functions (i. e. state and behavior) of the object are wrapped up as a cohesive unit, insulated against accidental corruption. Encapsulation is a way to ensure data abstraction.
MODULARITY: The act of simplifying a program into smaller components is called modularity. Each module may be written, compiled and tested separately.
INHERITANCE: A derived class automatically inherits the properties of the base or parent class. Thus, Class Boy may be derived from Class Humans. Every characteristic of Human (such as, a height, a weight, etc.) will be inherited by the Class Boy. However, it may have some extra features of its own (e. g. school-name, marks-obtained, etc.)
POLYMORPHISM: A message or data may be processed in different forms by different objects according to their specific features and behavior. For example, both Cat and Man fall under Mammals. To a message ‘VISION’ they behave differently - Man has color vision whereas Cat sees only in black and white.
you have covered the datatypes, inheritence and polymorphism basics very well. keep posting and it might be helpful to others. My dear freind, please visit my blog as well...
thanks. yes i will post more
good post
MOKSHA
thanks dear. do keep on with +ve opinions
You have given a brief concepts on C++
yes niti, do follow more posts. i will cover c++ full.