Why C++ and not C?
C is a subset of C++; in other words, C++ compilers will
compile C programs. The rule is that any person who wants to learn C++ may need
to have a good grasp of C language and its complexities (data structures and
methods). The difference between C and
C++ is primarily in the degree of emphasis on types and structures. C puts the
burden on the programmer to manage both data and types to prevent untraceable
errors at run-time. For example, C programs
can work with any type of data (char, integer or float), but can produce
incorrect output. On the other hand,
C++ puts the burden on the programmer to create functional types (class and
Template). A functional type is a data
type that contains both the data and the related methods (methods) within one
object (variable). The type that the
programmer creates in C++ is an intelligent data type. To give an analogy of that, the programmer
has to create magic boxes that take simple commands and do numerous tasks. This might sound complicated but it is not;
it is a new way defining data and methods. Although it can be done, C++ is not
designed for developing small and simple programs. Actually, all Object-Oriented programming is designed for large
and complex programs. C++ helps with
the localization of data and with dynamic programming plus all the static
features the C language provides.
C++ provides the following:
1. Support
for Object-Oriented Programming.
2. Support
for Abstract Data Type, Encapsulation and Data Hiding.
3. The
power, speed, simplicity and libraries (tools) that C language provides.
4. Support
for strongly type C language.
Structural Approach:
As programs get larger and
more complex, it is harder to manage them. It is tough for the human mind to
keep track of several objects and their Functionality or purpose plus the fine
details that a large program Possesses.
Procedural programming or structured programming has
dealt with such complexity in a very positive way. The structured approach is to group functions and data under a
single logic unit (method) and localize the data to the logical unit as much as
possible. Each logical unit (function)
is designed to have only one entry and one exit and does only one thing.
C++ can do an even better
job, as the following information will demonstrate. C++ provides a data abstraction known as encapsulation, which is
data hiding. It is as follows:
1. Divide
the program into logical parts, which are called classes (abstraction = closed
box - what is in it?).
2. Each
part is totally independent of the rest of the program.
3. Each
part has its own data and methods enclosed within it (encapsulation).
4. Data
and methods within any part are hidden and cannot be modified by any code
outside the class (information hiding).
5. You
can use any of these parts (classes) by simply calling the part name and adding
the task (method) name to the part
(class_1.do_anything).
6. The
program has one "main()" method that manages the entire program.
WHAT IS AN OBJECT?
According to Kernighan and Ritchie (page 195 - 197) an
object is defined as follows:
"An object, sometimes called
variable, is a location in storage, and its interpretation depends on two
attributes, its storage class and its type. The storage class determines the
lifetime of the storage associated with the identified object; the type
determines the meaning of values found in the identified object"
This defines an object as a
region of storage that has:
1.
Scope
2. Type
SCOPE:
Scope means when and to whom
the object is visible or accessible (local or global scope - dynamic or static
scope).
TYPE:
A type is translated into the following:
1. What
does the storage look like: space =
number of bytes
2. What
values can be stored in that type
3. What
kind of operations can be performed on that type
See
Object Oriented Design tutorial for OO and OOD approach
C++ CLASS
C++ provides a new way of
declaring a user-defined data type that has functionality. This user-defined data type contains both
the data objects and the methods that perform certain tasks on them. The new type is known as C++ class. A class or an ABSTRACT data type is a way of
grouping logical data and the associated methods within one object (class). The definition of this logical entity is
called ENCAPSULATION. Note that the
class is also an object (variable).
class class_name
{
member data
object list - 0 or more
member method
list - 0 or more
};
A C++ class has the following:
1. Must
start with the reserved word "class"
2. Open
curly bracket "{"
3. A list
of the declarations of the data objects belonging to the class (Zero or more)
4. A list
of method declarations belonging to the class (zero or more)
5. Close
curly bracket "}"
6. The
ending Semicolon ";"
For example:
class numbers
{
int integer;
float real;
double dble;
char ch;
char char_array[10];
/* method declaration = prototype */
float add_2_numbers(float ,
float);
float subtract_2_numbers(float ,
float);
void print(void);
};
The above is a type declaration and not a definition, in
other words we are declaring a type and not setting storage for it yet. The member methods list is a list of the
prototype of the methods that belong to this class and the definition of these
methods will we done afterwards. Since
this is a declaration, no initialization is allowed.
A C++ class can be one of the following:
1. class - members are private by default
2. struct - members are public by default
3. union - members are public by default
Class Instantiation and Instance:
When a class is declared, no memory is allocated for this
class until a class definition or creating an object is done. Creation of an
object from a class is called “Instantiating an Object” and the object created
is called “an instance of that class”.
For example:
// Decaration
no memory space is allocated
class
ClassDeclaration
{
…
};
…
{
ClassDeclaration MyClass; // First Instance of a class
ClassDeclaration HisClass; // Second
Instance of a class
ClassDeclaration HerClass; // Third
Instance of a class
…
}
MORE CLASS DETAILS:
A C++ class is a very powerful object. We call it an INTELLIGENT object or a magic
box. For a data object (variable) to be
intelligent or magical, it must have flexibility and functionality’s. The class should not be a storage place that
is a sitting duck with someone else doing the work, but an object (variable)
that can do everything on its own. The
following information is a review of the C++ class. Details of each item that can be declared within the class will
be presented later in the text.
class
class_name
{
Member Data
Object List
1. Standard data type - int, char, float ....
2. Aggregated data type - arrays, structure, union
1. class
A. Pre-declared
classes
B. Forward
classes
C. The
class itself - pointer or object
/* self
calling object - be careful of recursion */
Enumeration { ...}
Member Methods List
/* can be
of the following types */
1)
Constructor
2)
Destructor
3)
Overloaded Member methods
4)
Inline
5)
Static
6)
Constant
7)
Virtual
8)
Volatile
9)
Friend
10) A method
- none of the above - regular
};
Once more the above is a declaration and not a
definition. A member data object of a
class can be any of the lists mentioned above.
For example, a member data object that is declared within a class can be
an integer type, a float, a double, an array or even an array of pre-declared
classes. A member method of a class can
be any of the type of method in the second list. These types basically give the programmer the flexibility to
create a host of member methods that perform tasks with specific and concrete
methods. The member method numbered 10
is a method that is distinct from all the type mentioned.
C++ gives the class another additional power or
flexibility by allowing the programmer to declare any of the members to be
private, public or protected.
PRIVATE:
class
my_private_stuff
{
int private_integer;
float private_float;
char private_array[12];
void private_method(void);
public:
int public_integer;
float public_float;
void
public_method(void);
private:
double private_double;
int private_subroutine(int);
};
"private" means that only members of the class
can access these private members, which are hidden from the rest of the
program. They cannot be accessed by any
one outside the class.
PUBLIC:
struct
public_stuff
{
int public_integer;
float public_float;
char public_array[12];
void public_method(void);
private:
int private_integer;
float private_float;
void private_method(void);
public:
double public_double;
int public_subroutine(int);
};
A C++ class can be a class, struct or union. "public" means that any one in the
program, member of the class or non-member can access to these public class
members. The struct members are public
by default.
DEFINITION OF MEMBER METHODS:
The above is a declaration of the class object and no
definition. Also, the class declaration
has the member method prototype. The
definition of class member methods must come after the class declaration. The following example declares and defines
two member methods:
class
my_class
{
...
public:
void method_1(void);
int method_2(int);
...
};
...
void
my_class::method_1(void)
{
...
}
int
my_class::method_2(int value)
{
...
}
The following program is an example of a C++ class with
private and public data objects. The
program has one member method that prints the values stored in the class data
objects. The private data object
"private_object" can be accessed only by the class. The public can be accessed by anyone with
the program. The prototype of the
method "print" is declared within the class and its definition is
done following the class's declaration.
Scope Resolution Operator: “::”
Scope means when and to whom
the object is visible or accessible (local or global scope - dynamic or static
scope). The Scope resolution operator “::” provides a direction of accessing
global, local and class variables or member methods.
A global variable is
guaranteed to be initialized to zero if it not is explicitly initialized. Local
variable with the same name as the global one will mast or hide the global
variable.
For the class the “::” scope
resolution operator allows a type, enumerator, an object, member method to be
accessed even if it is hidden within the class declaration. The following are a
list of cases where the scope operator is used.
1. Accessing
Global Vairable
Value =
::MyData;
2. Accessing
Local vaiable
Value =
MyData;
3. Class
Member
Value =
this->MyData; // within a class
definition
Value =
MyClass::MyData;
Value =
Myclass::MyMehtod(); // outside a class definition
4. Class
Method definition
void
MYClass::MyMethod(void);
5. Class
Inheritance
Value =
BaseClass::MyData;
Value =
BaseCalss_1::MyData;
Value =
BaseCalss_2::MyData;
//*******************************************************
#include <stdio.h>
#include <stdlib.h>
class data_object
{
int private_object;
public:
int
public_object;
void
print(void);
};
//*******************************************************
void data_object::print(void)
{
private_object =
10;
public_object +=
public_object;
cout <<
"\n private data \t“
<< private_object
<< \t\t public data "
<<
public_object
<< ‘\n’;
}
//*******************************************************
main()
{
data_object data;
data.public_object = 10;
data.print();
data.public_object = 100;
cout << "\n <<
data.public_object << ‘\n’;
data.print();
return(0);
}
The output of the above program is as follows:
private data 10 public data
20
100
private data 10 public data
200
Practice Case #1 -
RECTANGULAR PRISM
Write a program to calculate the volume, perimeter and
surface area of a rectangular prism. The program must prompt the user to enter
the length, width and height of the rectangular prism. The program must echo
(reprint) the input data. The program should print the volume, the perimeter
and surface area of the rectangular prism.
................................
. . .
................................
.
. length . .
. height . .
. . .
width
................................
Note:
Volume = length * width * height
perimeter = 4 * (length +
width + height)
surface area =
(2 * length *
width) + (2 * length * height)
+ (2 *
width * height)
INPUT DATA:
length 100
width 20
height 10
/************************************************************
* The RECTANGULAR
PRISM program. It illustrations of Simple class
************************************************************/
#include
<stdio.h>
#include
<stdlib.h>
#include
<iostream.h>
#define MINIMUM
0
class
rectang_prism
{
int
length, width, height; // class private data objects
public:
// a list of functions available to anyone in the program
rectang_prism(int, int, int);
int
perimeter();
float
volume();
float
surface();
};
/*********************
Fuctions defintions ******************/
rectang_prism::rectang_prism(int
passed_length = MINIMUM,
// default values
int passed_width = MINIMUM,
int passed_height = MINIMUM )
{
} // null statement
/*************************************************************/
int
rectang_prism::perimeter()
{
return( 4 * (length + width + height) );
}
/****************************************************************/
float
rectang_prism::volume()
{
return((float) (length * width * height));
}
/****************************************************************/
float
rectang_prism::surface()
{
return( (float)(2 * (length * width
+ length * height + width * height)));
}
/****************************************************************/
main()
{
int
m_length, m_width, m_height;
// local variables
char ch;
cout << setprecision(2)
<< setiosflags(ios::fixed);
cout << "\n\t\t RECTANGULAR
PRISM\n";
cout << "\n This program
calculates the following\n";
cout << "\n\t Perimeter\n";
cout << "\n\t Volume\n";
cout << "\n\t Surface\n";
cout << "\n Please
enter(integer) the length”
<< “, width and height";
cout << " then press return\n
=======> ";
cin >> m_length >> m_width
>> m_height;
if(
(m_length < MINIMUM)
&& (m_width < MINIMUM)
&&
(m_height < MINIMUM)
)
{
cout << "\n you can not have any of the”
<< “ dimenssion less than 0";
return(-1);
}
rectang_prism my_rectangle(m_length, m_width, m_height);
cout << "\n\t length = "
<< m_length << endl;
cout << "\t Width = " << m_width << endl;
cout << "\t Height = " << m_height << endl;
cout << "\n\t Perimeter = "
<<
my_rectangle.perimeter()
<< endl;
cout << "\n\t Volume = " <<
my_rectangle.volume()
<< endl;
cout << "\n\t Surface = "
<< my_rectangle.surface()
<< endl;
cin.get(ch);
return(0);
}
/*****************************************************************
RECTANGULAR PRISM
This program calculates the following
Perimeter
Volume
Surface
Please enter(integer) the length, width and
height then press return
=======>
length = 5
Width = 6 Height = 8
Perimeter = 76 Volume = 240.00
Surface = 236.00