making and using objects

Upload: atul-garg

Post on 10-Oct-2015

17 views

Category:

Documents


0 download

DESCRIPTION

project

TRANSCRIPT

MaKING AND USING OBJECTS

Introduction to C++Making and Using Objects Intelizign Engineering Services Ltd.

ContentsPreface2Process of Compilation2Steps in Compilation Process2Type Checking3Declaration and Definition3Include Header File4Linking4Your First C++ Program5String Example5Input Output Example5Using STL: Vector Example6Reference:6Must Watch Videos6Exercise7String Example5Preface2Introduction to C++2Problems with Structured Programming3Unrestricted Access3Real-World Modeling4The Object-Oriented Approach5Real Life Example7Characteristics of Object-Oriented Languages8Abstraction8Encapsulation10Objects10Classes11Communication between classes12Inheritance13Re-usability14Creating New Data Types14Polymorphism14Compile time polymorphism:15Run time polymorphism:15Differences between C and C++.15Must Watch Videos17Exercise17

PrefaceThis chapter will introduce enough C++ syntax and program construction concepts to allow you to write and run some simple object-oriented programs.This chapter will introduce you to the basic concepts of object oriented programming (OOP). This chapter assume that you have had experience in a procedural programming language, although not necessarily C.

Classes that someone else has created are typically packaged into a library. This chapter uses several of the class libraries that come with all C++ implementations. This chapter also explains the tools used to build applications.Many people do not feel comfortable wading into object-oriented programming without understanding the big picture first. Thus, there are many concepts that are introduced here to give you a solid overview of OOP. However, many other people dont get the big picture concepts until theyve seen some of the mechanics first; these people may become bogged down and lost without some code to get their hands on. If youre part of this latter group and are eager to get to the specifics of the language, feel free to jump past this chapter skipping it at this point will not prevent you from writing programs or learning the language. However, you will want to come back here eventually to fill in your knowledge so you can understand why objects are important and how to design with them.

Process of CompilationIntroduction to C++Until Now we have been discussing about C language programming which is a structured language for programming and is procedural in nature. Mostly C is used in Assembly language programming where we need to drive hardware through OS modules. Basically it acts as a connecting tool between the hardware and software part of any Embedded or Personal computers range.

As we move to bigger picture and closer to real world our requirement increases and programming complexities also increases. In such cases a single list of instructions becomes unwieldy. Thus programmers start dividing programs in to functions and modules. Thus structured programming started losing the well-defined discipline of procedural paradigm The programmer writes source Code and is translated to machine instructions (see flow diagram given below).

CompilationExecutable FileC++ Code

Steps in Compilation ProcessProblems with Structured ProgrammingC++ preprocessor copies the contents of the included header files into the source code file, generates macro code, and replaces symbolic constants defined using #define with their values.

C++ Preprocessor

CompilerThe expanded source code file produced by the C++ preprocessor is compiled into the assembly language for the platform.

AssemblerThe assembler code generated by the compiler is assembled into the object code for the platform.

LinkerThe object code file generated by the assembler is linked together with the object code files for any library functions used to produce an executable file.

Type CheckingUnrestricted Access

The compiler also performs type checking during the first pass to prevent many kinds of programming errors. a) Static type checking means that type checking occurs at compile time. No type information is used at runtime in that case.b) Dynamic type checking occurs when type information is used at runtime. C++ uses a mechanism called RTTI (runtime type information) to implement this. The most common example where RTTI is used is the dynamic_cast operator which allows down casting of polymorphic types:// assuming that Circle derives from Shape...Shape *shape = new Circle(50);Circle *circle = dynamic_cast shape;

Furthermore, you can use the typeid operator to find out about the runtime type of objects. For example, you can use it to check whether the shape in the example is a circle or a rectangle.To Speed up compilation, C++ programs are created in small, manageable functions, which are in different files, thus enabling separate compilation. In a procedural program, there are two kinds of data. Local data, hidden inside a function and is used extensively by the function other are global data which can be accessed by any function in the program.Declaration and DefinitionPoints to be noted while wriinge code in files to speed up compilation. Declaration and Definition of function or Variable. Include HeadersExamples:// Declaration & definition examplesextern int i; // Declaration without definitionextern float f(float); // Function declarationfloat b; // Declaration & definitionfloat f(float a) { // Definitionreturn a + 1.0;}int i; // Definitionint h(int x) { // Declaration & definitionreturn x + 1;}

extern: It can mean the definition is external to the file, or that the definition occurs later in the file.

In a large program, there are many functions and many global data items. The problem with procedural paradigm is that this leads to an even larger number of potential connections. This large number of connections cause problems in several ways. It makes program's structure difficult to conceptualize. It also makes program difficult to modify. Any change made in global data item necessitate rewriting all the functions that access them.

RInclude Header File eal-World ModelingOld C style Format:

This one of the most important problems which procedural language face - its arrangement of separate data and functions does a poor job of modeling things in the real world. In the physical world we deal with objects such as people and cars. Such objects aren't like data and they aren't like functions. Complex real world objects have both attributes ( characteristics) and behavior( it is some thing a real world object does in response to some stimulus)#include #include New C++ style Format: #include #include Note: Youll usually have problems if you try to intermix the two forms in a single program..

The Object-Oriented ApproachLinkingThe fundamental idea behind object-oriented language is to combine into both data and the functions that operate on that data. Such a unit is called object. An object's functions, called member functions in c++. You cannotaccessthe data directly. The data is hidden, so it issafefrom accidental alteration. Data and its functions are said to be encapsulated into single entity. Data encapsulation and data hiding are key terms in the description of object-oriented languages . Linker links together the object modules (which often use file name extensions like .o or .obj generated by the compiler) and libraries.

Unresolved ReferencesWhen you make an external reference to a function or variable, the linker, looks if it has not already encountered the definition for the function or variable, it adds the identifier to its list of unresolved references. If the linker has already encountered the definition, the reference is resolved.Find Function or Variable Definition in Object Modules ( .o or .obj files )

Definition Found?

Resolve ReferenceSearch in Libraries

YesNo

Definition Found then link Object Module containing that function definition in that Lib, not entire lib and Resolve Reference.

Anad

Yes

No

Unresolved Reference

These behaviors represent a pure approach to object-oriented programming:

1. Everything is an object : Think of an object as a fancy variable; it stores data, but you can make requests to that object, asking it to perform operations on itself. In theory,you can take any conceptual component in the problem youre trying to solve (dogs, buildings, services, etc.) and represent it as an object in your program.

2. A program is a bunch of objects telling each other what to do by sending message to make a request of an object, you send a message to that object.More concretely, you can think of a message as a request to call a function that belongs to a particular object.

3. Each object has its own memory made up of other objects. Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity in a program while hiding it behind the simplicity of objects.

4. Every object has a type. Using the parlance, each object is an instance of a class, in which class is synonymous with type. The most important distinguishing characteristic of a class is What messages can you send to it?

5. All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type circle is also an object of type shape, a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handles anything that fits the description of a shape. This substitutability is one of the most powerful concepts in OOP.

Real LifeYour First C++ Program Example Lets take an example - think of objects as departments such as sales,accounting,personneland so on - in a company. Departments provide an important approach to corporate organization. Eachdepartmenthas its own personnel, with clearly assigned duties. It also has its own data: the accountingdepartmenthas payroll figures, the salesdepartmenthas sales figures, the personneldepartmentskeep records of each employee and so on. Eachdepartmentcontrol and operate on thatdepartment'sdata. Dividing thecompanyintodepartmentsmakes it easier to comprehend and control the company's activities. This view of corporateorganizationis shown in figure below.Create MyFirstSourceCodeFile.cpp

#include // Header file

using namespace std;// namespace

int main() {cout