A

117
SKNCOE,Pune IT Department STES’s SMT. KASHIBAI NAVALE COLLGE OF ENGINEERING, PUNE –41 DEPARTMENT OF INFORMATION TECHNOLOGY LAB MANUAL CLASS: - S.E.I.T. (Div I & II) SUBJECT: - OOPCG Lab SEMESTER:- IInd SE (IT) (SEM-II) OOPCG Laboratory 1

Transcript of A

Page 1: A

SKNCOE,Pune IT Department

STES’sSMT. KASHIBAI NAVALE COLLGE OF ENGINEERING,

PUNE –41

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL

CLASS: - S.E.I.T. (Div I & II) SUBJECT: - OOPCG Lab

SEMESTER:- IInd

Staff In-charge

Mr. S. N. Gujar

Mr. R. S. Apre

Mr. N. S. More

SE (IT) (SEM-II) OOPCG Laboratory1

Page 2: A

SKNCOE,Pune IT Department

Experiment No 1 (a)

Title

Text and Graphics mode, initialization of graphics mode, graphics drivers, switching between text and graphics mode, error handling.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject CG

SE (IT) (SEM-II) OOPCG Laboratory2

Page 3: A

SKNCOE,Pune IT Department

AIM : Text and Graphics mode, initialization of graphics mode, graphics drivers, switching between text and graphics mode, error handling.

OBJECTIVE: To make user familiar with the graphics commands..

INITGRAPH: Purpose: - Initializes the graphics systemSyntax: -void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);Comments: - Initgraph() initializes the graphic system by loading a graphics driver from disk and putting the system into graphics modee.g. int gm, gd= DETECT; initgraph( &gm, &gd, “ “ ); where gm= Graph mode

gd= Graph driver

& graph driver : that specifies the graphics driver to be used.CGA, MDA, EGA, VGA etc.DETECT 0 (requests autodeclaration )CGA 1MCGA 2EGA 3EGA64 4 etc.

& graph mode: To provide palettes, colors & resolution If gd= DETECT , initgraph sets graph mode

to the highest resolution available for the detected driver.

Part to driver : directory path where BGI files are stored. It specifies the directory path where

initgraph looks for graphics drivers ( *.BGI) first. Here we are providing numeric values to graph driver & graph mode , hence

it is declared as integer. Turbo C has supplied graphics driver for 10 driver board which are given in

BGI files in our TC . Hence we have to include BGI files in our graphics s/w. Instead of writing MDA/ CGA/ VGA we can directly write DETECT , which

automatically detects graphics driver which is available.

DETECTGRAPH: Purpose: - Determines graphics driver and graphics mode to use by checking the hardware[h/w].Syntax: - void far detectgraph(int far *graphdriver, int far *graphmode);

SE (IT) (SEM-II) OOPCG Laboratory3

Page 4: A

SKNCOE,Pune IT Department

Comments: -detectgraph() detects your system graphics adapter and chooses the mode that provides the highest resolution for the adapter. The main reason to call detectgraph() directly is to override the graphics mode that detectgraph() recommends to initgraph().

RESTORECRTMODE: Purpose: - Restores screen mode to pre-initgraph settingSyntax: -void far restorecrtmode(void);Comments: -This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes.

SWITCHING BETWEEN TEXT AND GRAPHICS MODE: Restore CRT mode is used as switch between the text and graphics mode.Restore screen mode to pre initgraph setting.Declaration: Void for restore mode (void).Remark: Restart mode restores the original video mode directed by initgraph.

GRAPHICS ERROR: The graphics file contains the 0-18 graphics error code. Each graphics error code have graphics constant and error message string.

ERROR CODE GRAPHICS ERROR ERROR MSG STRING 0 gr ok No error-1 gr no initgraph BGI graphics not installed-2 gr not detected Graphics n/w not detected -3 gr file not found Device drive file not found-14 gr error Graphics error-12 gr to error Graphics to error-18 gr invalid version Invalid version.

GRAPHICS PRIMITIVES:1. PIXEL: Each position on the screen is referred to as a pixel. Its rows and columns

number can specify each pixel on the screen. Thus by specifying rows and column number, we can specify pixel position on the screen. Interesting range pixel depends on the capability of the raster system.

2. LINE: We can specify a point with an ordered pair of number (x,y) where x is the horizontal distance from the origin and y is the vertical distance. If the two points used to specify a line are (x1,y1) and (x2,y2) then one evaluation for line is given by y-y2/x-x2 = y2-y1/x2-x1

Program & Output :-

SE (IT) (SEM-II) OOPCG Laboratory4

Page 5: A

SKNCOE,Pune IT Department

Experiment No Introduction to OOPL

Title

Study of OOP Concept.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject CG

**No need to write down this assignment in file.

SE (IT) (SEM-II) OOPCG Laboratory5

Page 6: A

SKNCOE,Pune IT Department

Theory : OOP : (Definition ) is a programming language model organized around "objects" rather than "actions" and data rather than logic The first step in OOP is to identify all the objects you want to manipulate and how they relate to each other, an exercise often known as data modeling.

Object-oriented programming. Objects of the program interact by sending messages to each other.

Why Object Oriented Approch ?

Major factor in the invention of Object-Oriented approach is to remove some of the flaws encountered with the procedural approach. In OOP, data is treated as a critical element and does not allow it to flow freely. It bounds data closely to the functions that operate on it and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. A major advantage of OOP is code reusability.

Some important features of Object Oriented programming are as follows:

Emphasis on data rather than procedure Programs are divided into Objects Data is hidden and cannot be accessed by external functions Objects can communicate with each other through functions

SE (IT) (SEM-II) OOPCG Laboratory6

Page 7: A

SKNCOE,Pune IT Department

New data and functions can be easily added whenever necessary Follows bottom-up approach

Concepts of OOP:

Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism

Objects Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in terms of objects and nature of communication between them. When a program is executed, objects interact with each other by sending messages. Different objects can also interact with each other without knowing the details of their data or code.

Classes A class is a collection of objects of similar type. It is a user defined data type. An object is called variable of class type. Once a class is defined, any number of objects can be created which belong to that class.

class student { // attributes: char name, DOB;

//methods: Totol (); Avg(); Display();

};

Data Abstraction and Encapsulation : Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the outside world and only those functions which are stored in the class can access it.

Inheritance

SE (IT) (SEM-II) OOPCG Laboratory7

Page 8: A

SKNCOE,Pune IT Department

Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes.

Polymorphism

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

Advantages of OOP

Object-Oriented Programming has the following advantages over conventional approaches:

OOP provides a clear modular structure for programs which makes it good for defining abstract data types where implementation details are hidden and the unit has a clearly defined interface.

OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.

OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.

Here are the few things you will notice about C++ which you can not find in classis C Language.

1. Improved Comments Style in C++ 2. The Keywords const & volatile 3. The scope operator 4. The iostream library 5. File stream operations 6. Variable definitions 7. Definition AND Declaration

One of the first object-oriented computer languages was called Smalltalk. C++ and Java are the most popular object-oriented languages today.

Questions :

1. What are the main differences between object-oriented programming and the other programming techniques?

SE (IT) (SEM-II) OOPCG Laboratory8

Page 9: A

SKNCOE,Pune IT Department

2. What are the added features in C++ ? 3. Benefits of OOP 4. List OOP languages. 5. Application of OOP

Experiment No 1(OOPL)

Title

Constructor, Destructor

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject OOPCG

SE (IT) (SEM-II) OOPCG Laboratory9

Page 10: A

SKNCOE,Pune IT Department

Problem statement : : Create a class named weather report that holds a daily weather report with data members day_of_month, hightemp, lowtemp, amount_rain and amount_snow. The constructor initializes the fields with default values: 99 for day_of_month, 999 for hightemp, -999 for low temp and 0 for amount_rain and amount_snow. Include a function that prompts the user and sets values for each field so that you can override the default values. Write a program that creates a monthly report.

Theory :

Constructors

A constructor is a special member function whose task is to initialize the objects of it's class. This is the first method that is run when an instance of a type is created. A constructor is invoked whenever an object of it's associated class is created. If a class contains a constructor, then an object created by that class will be initialized automatically. We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object

Why you should define a constructor

Uninitialized member fields have garbage in them. This creates the possibility of a serious bug (eg, an uninitialized pointer, illegal values, inconsistent values, ...).

Characteristics of a constructor :

They should be declared in the public section They are invoked automatically when the objects are created. They can not be inherited They cannot be virtual

A constructor is similar to a function, but with the following differences. No return type. No return statement.

SE (IT) (SEM-II) OOPCG Laboratory10

Page 11: A

SKNCOE,Pune IT Department

Types of Constructor

Default Constructor Parameterized constructor Copy constructor Constructor wirh default arguments Dynamic constructor

Destructor

As a C programmer, you often think about the importance of initialization, but it’s rarer to think about cleanup. with libraries, just “letting go” of an object once you’re done with it is not so safe. What if it modifies some piece of hardware, or puts something on the screen, or allocates storage on the heap? If you just forget about it, your object never achieves closure upon its exit from this world. In C++, cleanup is as important as initialization and is therefore guaranteed with the destructor.The syntax for the destructor is similar to that for the constructor: The class name is used for the name of the function. However, the destructor is distinguished from the constructor by a leading tilde (~). In addition, the destructor never has any arguments because destruction never needs any options. Here’s the declaration for a destructor:

class Y

{public:~Y();};

The destructor is called automatically by the compiler when the object goes out of scope. You can see where the constructor gets called by the point of definition of the object, but the only evidence for a destructor call is the closing brace of the scope that surrounds the object. Yet the destructor is called, even when you use goto to jump out of a scope. (goto still exists in C++, for backward compatibility with C and for the times when it comes in handy.) You should note that a nonlocal goto, implemented by the Standard C library functions setjmp( ) and longjmp( ), doesn’t cause destructors to be called. (This is the specification, even if your compiler doesn’t implement it that way. Relying on a feature that isn’t in the specification means your code is nonportable.)

Questions :

1. Exaplin Destructors.2. Explain copy constructor

SE (IT) (SEM-II) OOPCG Laboratory11

Page 12: A

SKNCOE,Pune IT Department

3. Give Eg of a constructor with default values.4. Give pictorial representation of object from your program.5. Memory allocation for static members .6. Memory allocation for array of objects .7. Difference between class variables and static variables8. Pictorial representation of object from your program.

SE (IT) (SEM-II) OOPCG Laboratory12

Page 13: A

SKNCOE,Pune IT Department

AIM - 1 b &c ) Color, Color Palette, Aspect ratio, Text: fonts, alignment, size, orientation and justification Graphics Primitives :- Pixel, Line, Circle, Ellipse, Polygons, Line style, Bar graphs, Pie Charts, Histograms, filling a polygon, windowing.

OBJECTIVE: To make user familiar with the functions available in graphics librarary.

THEORY: Text Mode: The text mode uses to change screen mode (in text mode).Dellocation: Void text mode (int newmode).Remark: Text mode select specific text mode. You can give the text mode (the argument newmode) by a symbolic constant from the enumerated type.

LAST MODE -1 Previous text mode

SE (IT) (SEM-II) OOPCG Laboratory

Experiment No 1 (b) & 1 (c)

Title

Color, Color Palette, Aspect ratio, Text: fonts, alignment, size, orientation and justification Graphics Primitives :- Pixel, Line, Circle, Ellipse, Polygons, Line style, Bar graphs, Pie Charts, Histograms, filling a polygon, windowing.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject OOPCG

13

Page 14: A

SKNCOE,Pune IT Department

BW 40 0 Black & White 40 Column C40 1 Colour 40 ColumnB480 2 Black & White 80 ColumnC80 3 Colour 80 ColumnMONO 7 Monochrome 80 ColumnC4350 64 EQA & VGA 43 lines, 53 lines

When text mode is called, the current window is reset to the entire screen the current text attributes are reset to normal corresponding to a call to norm video.

GRAPHICS MODE: There are number of graphics modes defined in a graphics file. These graphics modes depends on different graphics driver user’s that can achieve highest resolution using graphics mode.

INITIALISE OF GRAPHICS MODE AND DRIVER: Initialisation of graphics mode and drivers can be done by initgraph library function.

Initialises the graphics system declarations.Void for initgraph(int *graphdriver, int *graphmode, char *path to driver).

REMARK: To start the graphics system you must first call initgraph. Initgraph initiates the graphics system by loading a graphics driver from disk then putting the system into graphics mode.

SETCOLOR: Purpose: -Sets the current drawing colorSyntax: -void far setcolor(int color);Comments: - The color parameter can take a value from 0 to 15. The current drawing color is the value which the pixel are set when lines, rectangles , etc are given or drawn.

GETBKCOLOR: Purpose: - Returns the current background color.Syntax: - int far getbkcolor(void);

GETCOLOR: Purpose: - Returns the current drawing color.

Syntax: - int far getcolor(void);Comments: -The drawing color is the value to which pixels are set when lines, rectangles etc are drawn.

GETIMAGE: Purpose: - Saves a bit image of the specified region in the memory.Syntax: - void far getimage(int left, int top, int right, int bottom, void far *bitmap);Comments: - Getimage() copies on image from the screen to memory left,top,right and bottom define area of the screen from which the rectangle is to be copied. Bitmap points to the area in the memory where the bit image is stored.

SE (IT) (SEM-II) OOPCG Laboratory14

Page 15: A

SKNCOE,Pune IT Department

GETMAXCOLOR: Purpose: - Returns maximum color value for the current graphics driver and mode that can be passed to the setcolor() function.Syntax: - int far getmaxcolor(void);

IMAGESIZE: Purpose: - Returns the number of bytes required to store a bit image.Syntax: -unsigned far imagesize(int left, int top, int right, int bottom);Comments: - If the size read for the selected image is greater than or equal to 64k bytes, imagesize() returns 0xFFFF(-1)

PUTIMAGE: Purpose: -outputs a bit image onto the screenSyntax: -void far putimage(int left, int top, void far *bitmap, int op);Comments: -putimage() puts the bit image previously saved with the getimage() back onto the screen, with the upper left corner of the image placed at (left, top)

PUTPIXEL:Purpose: - putpixel plots a pixel at a specified point in a specified color.Syntax: -void far putpixel(int x, int y, int color);

ARC:Purpose: - Draws a circular arc.Syntax: - void arc(int x, int y, int startangle, int endangle, int rad);Comments: - Arc draws a circular arc in the current drawing color centered at (x,y) with a radius given by radius. The arc is drawn from startangle to endangle. The linestyle parameter does not affect arcs and circles.

BAR: Purpose: - Draws a 2D bar.Syntax: - void bar(int left, int top, int right, int bottom);Comments: - This function draws a filled in rectangular, two dimensional bar. The bar is filled using the current fillpattern and fillcolor .bar () does not outline the bar. To draw an outlined two dimensional bar, use bar3d() with depth equal to 0 (zero).

BAR3D: Purpose: - Draws a 3D bar.Syntax: - void bar3d(int left, int top, int right, int bottom, int depth, int flag);Comments: - This function draws a 3Drectangular bar. The bar is filled using the current fillpattern and fillcolor. The 3D outline of the bar is drawn in the current line style and color.

CIRCLE: Purpose: - Draws a circle with specified center and radius.Syntax: - void bar3d(int left, int top, int right, int bottom, int depth, int flag);

SE (IT) (SEM-II) OOPCG Laboratory15

Page 16: A

SKNCOE,Pune IT Department

Comments: - This function draws a 3Drectangular bar. The bar is filled using the current fillpattern and fillcolor. The 3D outline of the bar is drawn in the current line style and color.

CLEARDEVICE: Purpose: - Clears the graphics screen and moves CP (current position) to home (0,0).Syntax: - void far cleardevice(void);

Comments: -cleardevice () erases (that is filled with the background color) the entire graphics screen.

CLEARVIEWPORT: Purpose: -Clears the current view port and moves the CP to(0,0)Syntax: - void far clearviewport(void);

CLOSEGRAPH: Purpose: -Shuts down the graphics system and deallocates all memory allocated by the graphics.Syntax: - void far closegraph(void);

DRAWPOLY: Purpose: - Draws the outline of the polygon. Syntax: - void far drawpoly(int numpoints, int far *polypoints);Comments: -Drawpoly() draws a polygon with numpoints, using the current line style and color. Polypoints points to a sequence of (num*2) integer.Each pair of integers gives the x and y co-ordinates of a point on the polygon. In order to draw a closed figure with n vertices. You must pass n+1 co-ordinates to drawpoly () where the n th co-ordinate is equal to 0th.

ELLIPSE: Purpose: - Draws an elliptical arc.Syntax: - void far ellipse(int x, int y, int startangle, int endangle, int xradius, int yradius);Comments: -Ellipse () draws an elliptical arc in the current drawing color with its center at (x,y) and the horizontal and vertical axes given by xradius and yradius. The ellipse travels from startangle to endangle. The linestyle parameter doesn’t affect an ellipse. Only the thickness parameter is used.

FILLPOLY: Purpose: - Draws and fills a polygon. Syntax: - void far fillpoly(int numpoints, int far *polypoints);Comments: - fillpoly() draws the outline of a polygon with num points in the current line style and color and then fills the polygon using the current fillpattern and fillcolor polypoints point to the sequence of (num*2) integers each pair of integers give the x and y co-ordinates of a point on the polygon.

SE (IT) (SEM-II) OOPCG Laboratory16

Page 17: A

SKNCOE,Pune IT Department

FLOODFILL: Purpose: - Flood-fills the bounded region.Syntax: - void far floodfill(int x, int y, int border);Comments: -(x, y) is a seed point within the enclosed area to be filled. The area bounded by the color border is flooded with fill pattern and filll color.

GETASPECTRATIO: Purpose: - Retrieves the current graphics mode’s aspect ratio. Syntax: - void far getaspectratio(int far *xasp, int far *yasp);Comments: -The y aspect factor , *yasp is normalized to 10,000 on all graphics adapter except the VGA; xasp (the x aspect factor) is less than *yasp because the pixels are faller than they are wide. On the VGA, which has “square” pixel, *asp equals *yasp.

GETLINESETTINGS: Purpose: - Gets the current line style, pattern, and thickness.Syntax: - void far getlinesettings(struct linesettingstype far *lineinfo);Comments: -getlinesetting() fills linesettings type structure pointed to by into with information about the current line style, pattern and thickness.

GETMAXX: Purpose: - Returns maximum x screen coordinate in the current modeSyntax: - int far getmaxx(void);

GETMAXY:Purpose: - Returns maximum y screen coordinate in the current modeSyntax: - int far getmaxy(void);

GETPIXEL: Purpose: - gets the color of a specified pixelSyntax: -unsigned far getpixel(int x, int y);

GETX: Purpose: - returns the current position's x coordinateSyntax: -int far getx(void);

GETY: Purpose: - gety returns the current position's y coordinateSyntax: -int far gety(void);

LINE: Purpose: - draws a line between two specified pointsSyntax: -void far line(int x1, int y1, int x2, int y2);

SE (IT) (SEM-II) OOPCG Laboratory17

Page 18: A

SKNCOE,Pune IT Department

Comments: -Line() draws a line in the current color using current line style and thickness.

LINEREL: Purpose: - Draws a line a relative distance from the current positionSyntax: -void far linerel(int dx, int dy);Comments: - Linerel() draws a line from the CP to a point that is a relative distance (dx,dy) from the CP. The CP is advanced by (da,dy).

LINETO: Purpose: - draws a line from the current position (CP) to (x,y)Syntax: -void far lineto(int x, int y);Comments: -After line drawing the CP is moved to (x,y)

MOVEREL: Purpose: - Moves the current position (CP) a relative distanceSyntax: -void far moverel(int dx, int dy);Comments: -Moverel() moves the current position [CP] dx pixel in the x direction and dy pixel in the y direction.

MOVETO: Purpose: - moves the CP to (x, y)Syntax: -void far moveto(int x, int y);

OUTTEXT:Purpose: - displays a string in the viewport (graphics mode)Syntax: -void far outtext(char far *textstring);Comments: -outtext() displays the string at the CP using the justification setting and the current font direction and size. This function will not work in text mode.

OUTTEXTXY:Purpose: - outtextxy displays a string at the specified location (graphics mode)Syntax: -void far outtextxy(int x, int y, char far *textstring);Comments: - outtextxy() displays the string in the viewport of the given position (x, y) using the justification setting and the current font direction and size. This function will not work in text mode.

RECTANGLE:Purpose: - Draws a rectangle (graphics mode)Syntax: -void far rectangle(int left, int top, int right, int bottom);Comments: -rectangle draws a rectangle in the current line style, thickness, and drawing color.

SETBACKCOLOR:

SE (IT) (SEM-II) OOPCG Laboratory18

Page 19: A

SKNCOE,Pune IT Department

Purpose: -Sets the current background color using the paletteSyntax: - void far setbkcolor(int color);Comments: - The color parameter can take a value from 0 to 15. If you use an EGA or VGA and you change the palette colors.

SETFILLPATTERN: Purpose: - Selects a user-defined fill patternSyntax: -void far setfillpattern(char far *upattern, int color);

SETGRAPHMODE: Purpose: - Sets the system to graphics mode, clears the screenSyntax: -void far setgraphmode(int mode);

Comments: -setgraphmode selects a graphics mode different than the default one set by initgraph. It clears the screen and resets all graphics settings to their defaults.

SETLINESTYLE: Purpose: - Sets the current line style and width or patternSyntax: -void far setlinestyle(int linestyle, unsigned upattern, int thickness);Comments: -setlinestyle sets the style for all lines drawn by line, lineto, rectangle, drawpoly, etc.

SETTEXTJUSTIFICATION: Purpose: -Sets text justification for graphics modeSyntax: -void far settextjustify(int horiz, int vert);Comments: -Text output after a call to settextjustify is justified around the current position (CP) horizontally and vertically, as specified.

SETTEXTSTYLE: Purpose: - Sets the current text characteristicsSyntax: -void far settextstyle(int font, int direction, int charsize);Comments: -settextstyle sets the text font, the direction in which text is displayed, and the size of the characters.

SE (IT) (SEM-II) OOPCG Laboratory19

Page 20: A

SKNCOE,Pune IT Department

Program & Output of 1(b) :-

Program & Output of 1 (c) :-

SE (IT) (SEM-II) OOPCG Laboratory

Experiment No 2(oop)

TitleStatic member functions, friend class, this pointer,

inline code and dynamic memory allocation

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject OOPLCG

20

Page 21: A

SKNCOE,Pune IT Department

Problem statement : Develop an object oriented program in C++ to create a database of the personnel information system containing the following information: Name, Date of Birth, Blood group ,Height, Weight, Insurance Policy number, Contact address ,telephone number, driving license no. etc Construct the database with suitable member functions for initializing and destroying the data viz constructor, default constructor ,copy constructor, destructor, static member functions, friend class, this pointer, inline code and dynamic memory allocation operators-new and delete.

Theory :

Static members

A class can contain static members, either data or functions.

A static member variable has following properties : It is initialized to zero when the first object of its class is created . No other initialization is

permitted. Only one copy of that member is created for the entire class and is shared by all the objects

of that class.

SE (IT) (SEM-II) OOPCG Laboratory21

Page 22: A

SKNCOE,Pune IT Department

It is the visible only within the class but its lifetime is the entire program.

Static data members of a class are also known as "class variables", because there is only one unique value for all the objects of that same class. Their content is not different from one obje static members have the same properties as global variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). In order to initialize a static data-member we must include a formal definition outside the class, in the global scope of this class to another. Because it is a unique variable value for all the objects of the same class, it can be referred to as a member of any object of that class or even directly by the class name (of course this is only valid for static members.

A static member function has following properties

A static function can have access to only other static members (fun or var) declared in the same class

A static function can be called using the clas name instead of its object name

Class_name :: fun_name;

Static member functions are considered to have class scope. In contrast to nonstatic member functions, these functions have no implicit this argument; therefore, they can use only static data members, enumerators, or nested types directly. Static member functions can be accessed without using an object of the corresponding class type

the following restrictions apply to such static functions:

They cannot access nonstatic class member data using the member-selection

operators (. or –>).

They cannot be declared as virtual.

They cannot have the same name as a nonstatic function that has the same argument

types.

Eg. // static members in classesclass StaticTest {

private: static int x;

public: static int count()

{ return x;

}

};

int StaticTest::x = 9;

SE (IT) (SEM-II) OOPCG Laboratory22

Page 23: A

SKNCOE,Pune IT Department

int main()

{

printf_s("%d\n", StaticTest::count());

}

Output

9

Friend functions:

In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends. Friends are functions or classes declared as such. If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend.

Properties of friend function :

It is not in the scope of the class to which it has been declared as friend. Since it is not in the scope of the class , it cannot be called using the object of that class It can be invoked like a normal function w/o the help of any object. It can be declared in private or in the public part of the class. Unlike member functions , it cannot access the member names directly and has to use an

object name and dot operator with each member name.

// friend functions#include <iostream>using namespace std;

class CRectangle { int width, height; public: void set_values (int, int); int area () {return (width * height);} friend CRectangle duplicate (CRectangle);};

void CRectangle::set_values (int a, int b) { width = a; height = b;}

CRectangle duplicate (CRectangle rectparam){

24

SE (IT) (SEM-II) OOPCG Laboratory23

Page 24: A

SKNCOE,Pune IT Department

CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres);}

int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); return 0;}

The duplicate function is a friend of CRectangle. From within that function we have been able to access the members width and height of different objects of type CRectangle, which are private members. Notice that neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate a member of class CRectangle.

Friend classes

Just as we have the possibility to define a friend function, we can also define a class as friend of another one, granting that second class access to the protected and private members of the first one.

// friend class#include <iostream>using namespace std;

class CSquare;

class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a);};

class CSquare { private: int side; public:

SE (IT) (SEM-II) OOPCG Laboratory24

Page 25: A

SKNCOE,Pune IT Department

void set_side (int a) {side=a;} friend class CRectangle;};

void CRectangle::convert (CSquare a) { width = a.side; height = a.side;} int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0;}

In this example, we have declared CRectangle as a friend of CSquare so that CRectangle member functions could have access to the protected and private members of CSquare, more concretely to CSquare::side, which describes the side width of the square..

Pointers :

A pointer is a derived data type that refers to another data variable by storing the variables memory address rather than data.

Declaration of pointer variable is in the following form :

Eg int * ptr;

Here ptr is a pointer variable and points to an integer data type.

We can initialize pointer variable as follows

int a, *ptr; // declaration

ptr = &a //initialization

Pointers to objects :

Consider the following eg

item X; // where item is class and X is object

SE (IT) (SEM-II) OOPCG Laboratory25

Data_type * ptr_var;

Page 26: A

SKNCOE,Pune IT Department

Similarly we can define a pointer it_ptr of type item as follows

Item *it_ptr ;

Object pointers are useful in creating objects at runtime. We can also access public members of the class using pointers.

Eg item X;

item *ptr = &X;

the pointer ‘ptr ‘is initialized with address of X.

we can access the member functions and data using pointers as follows

ptr->getdata();

ptr->show();

this pointer :

c++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. This unique pointer is automatically passed to a member function when it is called .

important notes on this pointer: this pointer stores the address of the class instance, to enable pointer access of the members

to the member functions of the class. this pointer is not counted for calculating the size of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.

 

Conclusion:

SE (IT) (SEM-II) OOPCG Laboratory26

Page 27: A

SKNCOE,Pune IT Department

SE (IT) (SEM-II) OOPCG Laboratory

Experiment No 3(oopl)

TitleOperator overloading

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject OOPLCG

27

Page 28: A

SKNCOE,Pune IT Department

Problem statement : Design a Class ‘Complex ‘with data members for real and imaginary part. Provide default and parameterized constructors. Write a program to perform arithmetic operations of two complex numbers using operator overloading (using either member functions or friend functions).

Theory :

with C++ feature to overload operators, we can design classes able to perform operations using standard operators. Here is a list of all the operators that can be overloaded:

Overloadable operators

+ - * / = < > += -= *= /= << >><<= >>= == != <= >= ++ -- % & ^ ! |~ &= ^= |= && || %= [] () , ->* -> new

delete new[] delete[]

SE (IT) (SEM-II) OOPCG Laboratory28

Page 29: A

SKNCOE,Pune IT Department

To overload an operator in order to use it with classes we declare operator functions, which are regular functions whose names are the operator keyword followed by the operator sign that we want to overload. The format is:

type operator operator-symbol (parameters) { /*...*/ }

The operator keyword declares a function specifying what operator-symbol means when applied to

instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler

distinguishes between the different meanings of an operator by examining the types of its operands.

Rules for operator overloading://get it from Ebalagurusamy.

Experiment No 2

Title

Line generation using DDA and Bresenham's algorithm.

SE (IT) (SEM-II) OOPCG Laboratory29

Page 30: A

SKNCOE,Pune IT Department

Generation of circle using Bresenham's algorithm.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject Computer Graphics

SE (IT) (SEM-II) OOPCG Laboratory30

Page 31: A

SKNCOE,Pune IT Department

Problem Statement:

Write a program to implement following algorithms : DDA Line Drawing Algorithm Bresenham Line Drawing Algorithm Bresenham Circle Drawing Algorithm

Objective:

To understand the different algorithms for line & circle generation and their implementation.

Problem definition:

Rasterization : Process of determining which pixels provide the best approximation to a desired line on the screen.

Scan Conversion: Combination of rasterization and generating the picture in scan line order.

General requirements Straight lines must appear as straight lines. They must start and end accurately. Lines should have constant brightness along their length Lines should drawn rapidly.

Line drawing algorithm Programmer specifies (x,y) values of end pixels Need algorithm to figure out which intermediate pixels are on line path Pixel (x,y) values constrained to integer values Actual computed intermediate line values may be floats Rounding may be required. E.g. computed point (10.48, 20.51) rounded to (10, 21) Rounded pixel value is off actual line path. Sloped lines end up having jaggies Vertical, horizontal lines, no jaggies

SE (IT) (SEM-II) OOPCG Laboratory31

Page 32: A

SKNCOE,Pune IT Department

Digital Differential Analyzer (DDA)The differential equation of a straight line is given by:

The solution of the finite difference approximation is:

We need only compute m once, as the start of the scan-conversion.The DDA algorithm runs rather slowly because it requires real arithmetic (floating-point operations).

Digital Differential Analyzer (DDA): Line Drawing Algorithm

Walk through the line, starting at (x0,y0) Constrain x, y increments to values in [0,1] range Case a:

o x is incrementing faster (m < 1)o Step in x=1 increments, compute and round y

Case b: o y is incrementing faster (m > 1)o Step in y=1 increments, compute and round x

SE (IT) (SEM-II) OOPCG Laboratory32

Page 33: A

SKNCOE,Pune IT Department

Case a : (m < 1)

x = x0 , y = y0Illuminate pixel (x, round(y))x= x0 + 1 , y = y0 + 1 * mIlluminate pixel (x, round(y))x = x + 1 , y = y + 1 * mIlluminate pixel (x, round(y))…Until x == x1

Case b : (m > 1)

x = x0 , y = y0Illuminate pixel (round(x), y)y = y0 + 1, x = x0 + 1 * 1/mIlluminate pixel (round(x), y)y = y + 1 , x = x + 1 /mIlluminate pixel (round(x), y)…Until y == y1

DDA Line Drawing Algorithm Drawbacks DDA is the simplest line drawing algorithm

o Not very efficiento Round operation is expensive

Optimized algorithms typically used.o Integer DDAo E.g.Bresenham algorithm

Bresenham algorithmo Incremental algorithm: current value uses previous valueo Integers only: avoid floating point arithmetic

Bresenham’s algorithm

Bresenham's line algorithm is an algorithm that determines which points in an n-dimensional raster should be plotted in order to form a close approximation to a straight line between two given points. It is commonly used to draw lines on a computer screen, as it uses only integer addition, subtraction and bit shifting all of which are very cheap operations in standard computer architectures. It is one of the earliest algorithms developed in the field of computer graphics.

The basic algorithm works for lines which look like this:

SE (IT) (SEM-II) OOPCG Laboratory33

Page 34: A

SKNCOE,Pune IT Department

o------- | p1 -------- | deltay ------- p2 | -------o | ---------------------------------- deltax

where p1 = (x1,y1), p2 = (x2, y2), x and y are both increasing from p1 to p2, ∆x = x2 - x1, ∆y = y2 - y1 and ∆x >= ∆y.

All other types of lines can be derived from this type.

First you need to perform the following intialisation:

x = x1y = y1d = (2 * ∆y) - ∆x

x is the current x location, you will add 1 to this variable after every pixel you draw until all pixels have been drawn. y is the current y location. The decision variable is used to determine when to add 1 to this value. d is the decision variable which will be used to keep a track of what to do.

Now you loop across the screen from x1 to x2 and for each loop perform the following operations for each pixel :

PutPixel(x, y); { Draw a pixel at the current point }if d < 0 then d := d + (2 * ∆y)else begin d := d + 2 * (∆y - ∆x); y := y + 1; end;x := x + 1;

SE (IT) (SEM-II) OOPCG Laboratory34

Page 35: A

SKNCOE,Pune IT Department

Bresenham's Circle AlgorithmCircles have the property of being highly symmetrical, which is handy

when it comes to drawing them on a display screen.

We know that there are 360 degrees in a circle. First we see that a circle is symetrical about the x axis, so only the first 180 degrees need to be calculated. Next we see that it's also symetrical about the y axis, so now we only need to calculate the first 90 degrees. Finally we see that the circle is also symetrical about the 45 degree diagonal axis, so we only need to calculate the first 45 degrees.Bresenham's circle algorithm calculates the locations of the pixels in the first 45 degrees. It assumes that the circle is centered on the origin. So for every pixel (x,y) it calculates we draw a pixel in each of the 8 octants of the circle :

PutPixel(CenterX + X, Center Y + Y)PutPixel(CenterX + X, Center Y - Y)PutPixel(CenterX - X, Center Y + Y)PutPixel(CenterX - X, Center Y - Y)PutPixel(CenterX + Y, Center Y + X)PutPixel(CenterX + Y, Center Y - X)PutPixel(CenterX - Y, Center Y + X)PutPixel(CenterX - Y, Center Y - X)

Algorithm : Given a radius for the circle we perform this initialisation:

d := 3 - (2 * RADIUS)x := 0y := RADIUS

Now for each pixel we do the following operations until x = y : Draw the 8 circle pixelsif d < 0 then d := d + (4 * x) + 6else begin d := d + 4 * (x - y) + 10 y := y - 1;

SE (IT) (SEM-II) OOPCG Laboratory35

Page 36: A

SKNCOE,Pune IT Department

end;

Algorithms

Algorithm DDA:

Input to the algorithm (x1,y1) and (x2,y2) the end co-ordinates of a line.

Output of the algorithmBring on pixels closest to the line.

Data Variables (x1,y1) & (x2,y2) : are real numbers representing end co-ordinates of line segment. length : stores the length of line segment. dx, dy :stores increment in x and y direction. Sign : a function returning 1,0, -1 if argument to the function is > 0; = 0; < 0;

Algorithm DDAStep 1. StartStep 2. if |x2-x1| >= |y2-y1| then length = |x2-x1| else length = |y2-y1|Step 3. dx = (x2-x1) / length.Step 4. dy = (y2-y1) / length.Step 5. x = x1 + 0.5 * sign(dx) /*x1 assumed to be at the leftmost*/Step 6. y = y1 + 0.5 * sign(dy).Step 7. Let i = 1Step 8. if i > length then go to step no 14Step 9. Plot (trun(x), trunk(y))Step 10. x = x + dx;Step 11. y = y + dy;Step 12. Increment iStep 13. go to step no 8Step 14. Stop.

SE (IT) (SEM-II) OOPCG Laboratory36

Page 37: A

SKNCOE,Pune IT Department

Bresenham's line generation algorithm

Input to the algorithm : (x1,y1)and (x2,y2) the integer values of end co-ordinates of a line segment.

Output of the algorithm Turning on the pixels on the line or close to the line.

Data variables(X1Y1),(X2,y2) : are integer variables representing end co- ordinates.dx, dy : integers representing difference in x and y values of the co-ordinates respectively.C1, c2 : integers used to store value of expression 2* (dy - dx) and 2* dy before the iteration.x,y : integers used for plotting the pixelxend : integer set to highest of x value amongst x1 and x2 integer used as a decision variable.

Algorithm Bresenham line generationStep 1. StartStep 2. dx = |x2-x1| // dx is set to positive x differenceStep 3. dy = |y2-y1| // dy isset to positive y differenceStep 4. d = 2* dy - dx; {initialization of decision variable}Step 5. c1 = 2 * (dy - dx); {pre calculating first expression}Step 6. c2 = 2 * dy ; { pre calculating second expression}Step 7. if (x1> x2) then

{ x = x2 ; y = y2; xend = x1;}else{ x = x1; y = y1; xend = x2;}

Step 8. plot (x,y)Step 9. if (x>= xend) then go to step no 14.Step 10. x = x + 1; {increment x value by one pixel}Step 11. if (d > = 0) then {check decision variable}

{ y = y + 1; {increment y value}

SE (IT) (SEM-II) OOPCG Laboratory37

Page 38: A

SKNCOE,Pune IT Department

d = d + c1 ;}else{ d = d + c2 ; }

Step 12. plot (x,y);Step 13. go to step no 9Step 14. stop.

Bresenham's Circle Generation Algorithm

Input to the Algorithm (xc, yc) Integer Centre Co-ordinates and ‘r’ radius.

Output of the AlgorithmTurning ON the pixels on circular boundary.

Data Variables(xc,yc) : Integer, representing center co-ordinates.r : Integer, radius of the circled : Integer, decision variable.x,y : Integer, points used for turning ON the pixel.

Algorithm BresenhamCircleGen (xc,yc,r: Integer)Step 1. StartStep 2. x = 0Step 3. y = r; { Initial point on the circle}Step 4. d = 3 - 2 * r; { Initialise decision variable}Step 5. if (x > y ) go to step no 17Step 6. Plot(xc + x, yc +y);Step 7. Plot(xc - x, yc + y);Step 8. Plot(xc + x, yc - y);Step 9. Plot(xc - x, yc - y);Step 10. Plot(xc + y, yc + x);Step 11. Plot(xc - Y,yc + x);Step 12. Plot(xc +y, yc - x);Step 13. Plot(xc - Y,yc - x); { Plot eight symmetric points}Step 14. If (d > = 0) Then

{ d = d + 4 * (x - y) + 10; y = y-1;

}else{ d = d + 4 * x + 6;}

Step 15. x = x + 1Step 16. go to step no 5

SE (IT) (SEM-II) OOPCG Laboratory38

Page 39: A

SKNCOE,Pune IT Department

Step 17. stop.

Design experiment1. Write a program to draw a house.2. Modify the BRESENHAM algorithm so that it will create a dashed line

pattern.3. Implement the polyline function using the DDA algorithm.

SE (IT) (SEM-II) OOPCG Laboratory39

Page 40: A

SKNCOE,Pune IT Department

Experiment No 4(oopl)

Title

write a C++ program to perform String operations.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject Oopcg

SE (IT) (SEM-II) OOPCG Laboratory40

Page 41: A

SKNCOE,Pune IT Department

Problem statement : write a C++ program to perform following operations on the strings .

1. = Equality2. = = string copy3. + concatenation 4. << display a string 5. > > reverse string 6. function to determine whether a string is a palindrome7. to find occurrence of a substring

Theory :

Strings in C++: Strings can be defines as class objects which can be then manipulated like a built in data types. Since the strings vary greatly in size , we use ‘new’ to allocate memory for each string and a pointer variable to point to the string array. Thus we must create string objects that can hold these two pieces of information , namely length and location which are necessary for string manipulations. A typical string class will look as Class string { Char *p; Int len; // length of string Public : ………….// mem fun to initialize and manipulate strings …………..};

Pointers are useful to allocate arrays dynamically ie we can decide the array size at run time.c++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example:

int a, b, c;a = b + c;

SE (IT) (SEM-II) OOPCG Laboratory41

Page 42: A

SKNCOE,Pune IT Department

This is obviously valid code in C++, since the different variables of the addition are all fundamental types. Nevertheless, it is not so obvious that we could perform an operation similar to the following one:

struct { string product; float price;} a, b, c;a = b + c;

In fact, this will cause a compilation error, since we have not defined the behavior our class should have with addition operations. However, thanks to the C++ feature to overload operators, we can design classes able to perform operations using standard operators. Here is a list of all the operators that can be overloaded:

Overloadable operators

+ - * / = < > += -= *= /= << >><<= >>= == != <= >= ++ -- % & ^ ! |~ &= ^= |= && || %= [] () , ->* -> new

delete new[] delete[]

To overload an operator in order to use it with classes we declare operator functions, which are regular functions whose names are the operator keyword followed by the operator sign that we want to overload. The format is:

type operator operator-symbol (parameters) { /*...*/ }

The operator keyword declares a function specifying what operator-symbol

means when applied to instances of a class. This gives the operator more than one

meaning, or "overloads" it. The compiler distinguishes between the different

meanings of an operator by examining the types of its operands.

Question :

1. Memory allocation for strings

2. Pointers in c++

3. Difference between ‘new’ and ‘malloc’

SE (IT) (SEM-II) OOPCG Laboratory42

Page 43: A

SKNCOE,Pune IT Department

Experiment No 3

Title

Polygon filling using scan line seed fill algorithm.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject Computer Graphics

SE (IT) (SEM-II) OOPCG Laboratory43

Page 44: A

SKNCOE,Pune IT Department

Problem Statement:

Write a program to implement Scanline Polygon filling algorithm. Objective:

To study and Implement Polygon filling algorithms.

Problem definition:

Polygon Filling Algorithms:1. Seed Fill Approaches

2 algorithms: Boundary Fill and Flood Fill works at the pixel level suitable for interactive painting applications

2. Scanline Fill Approaches works at the polygon level better performance

Seed Fill Algorithms: Connectedness• 4-connected region: From a given pixel, the region that you can get to by a

series of 4 way moves (N, S, E and W)• 8-connected region: From a given pixel, the region that you can get to by a

series of 8 way moves (N, S, E, W, NE, NW, SE, and SW)

Boundary Fill Algorithm• Start at a point inside a region• Paint the interior outward to the edge• The edge must be specified in a single color• Fill the 4-connected or 8-connected region• 4-connected fill is faster, but can have problems:

Boundary Fill Algorithm void BoundaryFill4(int x, int y, color newcolor, color edgecolor){ int current; current = ReadPixel(x, y); if(current != edgecolor && current != newcolor) { BoundaryFill4(x+1, y, newcolor, edgecolor);

SE (IT) (SEM-II) OOPCG Laboratory

4-connected 8-connected

44

Page 45: A

SKNCOE,Pune IT Department

BoundaryFill4(x-1, y, newcolor, edgecolor); BoundaryFill4(x, y+1, newcolor, edgecolor); BoundaryFill4(x, y-1, newcolor, edgecolor); }}

Flood Fill Algorithm• Used when an area defined with multiple color boundaries• Start at a point inside a region• Replace a specified interior color (old color) with fill color• Fill the 4-connected or 8-connected region until all interior points being

replaced

Flood Fill Algorithm void FloodFill4(int x, int y, color newcolor, color oldColor){ if(ReadPixel(x, y) == oldColor) { FloodFill4(x+1, y, newcolor, oldColor); FloodFill4(x-1, y, newcolor, oldColor); FloodFill4(x, y+1, newcolor, oldColor); FloodFill4(x, y-1, newcolor, oldColor); }}

Scanline Fill Algorithm• Intersect scanline with polygon edges• Fill between pairs of intersections• Basic algorithm:

For y = ymin to ymax1) intersect scanline y with each edge2) sort intersections by increasing x [p0,p1,p2,p3]3) fill pairwise (p0->p1, p2->p3, …)

Spacial Handling• Make sure we only fill the interior pixels.• Intersection has an integer X coordinate• Intersection is an edge end point

SE (IT) (SEM-II) OOPCG Laboratory45

Page 46: A

SKNCOE,Pune IT Department

In fact, if we compute the intersection of the scanline with edge e1 and e2 separately, we will get the intersection point p1 twice. Keep both of the p1.

However, in this case we don’t want to count p1 twice (p0,p1,p1,p2,p3), otherwise we will fill pixels between p1 and p2, which is wrong. Summary: If the intersection is the ymin of the edge’s endpoint, count it. Otherwise, don’t.

SE (IT) (SEM-II) OOPCG Laboratory

Case 1

Case 2

46

Page 47: A

SKNCOE,Pune IT Department

Scan-Fill Algorithm1. For each non-horizontal edge of the polygon boundary identify the upper

and lower endpoints,(xl;yl) and (xu;yu), such that yu > yl, and construct a record for each that contains yu, the y-coordinate at the upper endpoint x= xl, the current x-intersection w = 1/m = (xu − xl)/(yu − yl), the reciprocal of the slope of the edge

2. Set the AET (the active edge table) to be empty.3. Apply a bucket sort algorithm to sort the edges using the yl as the primary

key, and xl as the secondary, and w as the tertiary. N.B., Each bucket contains a list. The set of buckets is called the ET (edge table).

4. Set y equal to the smallest index in the ET that has a non empty bucket.5. Repeat until the ET and the AET are empty:

a. Move any edges from bucket y in the ET to the AET.b. Remove any edges from the AET that have a yu equal to y.c. Sort the AET according to x.d. Fill in the requisite pixels between the even and odd adjacent pairs of

intersections in the AET: round up, [x] the x-coordinate of “left” intersections, round down, [x − 1] that of the “right” intersections.

e. Increment y by one.f. Update x = x+ w for every nonvertical edge in the AET.

SE (IT) (SEM-II) OOPCG Laboratory47

Page 48: A

SKNCOE,Pune IT Department

Example :Polygon before filling

Polygon after filling

Design experiment

1. Set up an algorithm for converting any specified sphere or cylinder to a polygon mesh representation.

2. Write a program to display a bar graph in any selected screen area. Use the polyline function to draw the bar.

3. Write a program to scan converts the interior of the specified ellipse into a solid color.

SE (IT) (SEM-II) OOPCG Laboratory48

Page 49: A

SKNCOE,Pune IT Department

Experiment No 5(oopl)

Title Program on Inheritance

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject oopcg

SE (IT) (SEM-II) OOPCG Laboratory49

Page 50: A

SKNCOE,Pune IT Department

Problem statement: Design a base class with name, date of birth, blood group and another base class consisting of the data members such as height and weight. Design one more base class consisting of the insurance policy number and contact address. The derived class contains the data members telephone numbers and driving license number.Write a menu driven program to carry out the following things:i) Build a master table ii) Display iii) Insert a new entry

iv) Delete entry v) Edit vi) Search for a record

Theory: Inheritance Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes.

Types of Inheritance 1. Single inheritance2. Multiple inheritance3. Multilevel inheritance4. Hierarchial inheritance5. Hybrid Inheritance

There are three types of class inheritance: public, private and protected

The protected access specifier is similar to private. Its only difference occurs in fact with inheritance. When a class inherits from another one, the members of the derived class can access the protected members inherited from the base class, but not its private members.

Difference between public , private and protected

A member (either data member or member function) declared in a private section of a class can only be accessed by member functions and friends of that class

A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes

A member (either data member or member function) declared in a public section of a class can be accessed by anyone

The following table indicates how the attributes are inherited in the three different types of inheritance:

SE (IT) (SEM-II) OOPCG Laboratory50

Page 51: A

SKNCOE,Pune IT Department

Access specifiers in the base class

private Public protected

public inheritance The member is private. The member is public. The member is protected.

private inheritance The member is private. The member is private. The member is private.

protected inheritance The member is private. The member is protected. The member is protected.

access the protected members inherited from the base class, but not its private members.

What a derived class inherits Every data member defined in the parent class (although such members¤

may not always be accessible in the derived class!) Every ordinary member function of the parent class (although such

members¤ may not always be accessible in the derived class!) The same initial data layout as the base class

 

What a derived class doesn't inherit The base class's constructors and destructor The base class's assignment operator The base class's friends

What a derived class can add New data members  New member functions  New constructors and destructor  New friends

Eg Suppose that we want to declare a series of classes that describe polygons like our CRectangle, or like CTriangle. They have certain common properties, such as both can be described by means of only two sides: height and base. This could be represented in the world of classes with a class CPolygon from which we would derive the two other ones: CRectangle and CTriangle.

SE (IT) (SEM-II) OOPCG Laboratory51

Page 52: A

SKNCOE,Pune IT Department

The class CPolygon would contain members that are common for both types of polygon. In our case: width and height. And CRectangle and CTriangle would be its derived classes, with specific features that are different from one type of polygon to the other.

Classes that are derived from others inherit all the accessible members of the base class. That means that if a base class includes a member A and we derive it to another class with another member called B, the derived class will contain both members A and B.

In order to derive a class from another, we use a colon (:) in the declaration of the derived class using the following format:

class derived_class_name: public base_class_name{ /*...*/ };

Where derived_class_name is the name of the derived class and base_class_name is the name of the class on which it is based. The public access specifier may be replaced by any one of the other access specifiers protected and private. This access specifier describes the minimum access level for the members that are inherited from the base class.

// derived classes#include <iostream>using namespace std;

class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} };

class CRectangle: public CPolygon { public: int area () { return (width * height); }

2010

SE (IT) (SEM-II) OOPCG Laboratory52

Page 53: A

SKNCOE,Pune IT Department

};

class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}

The objects of the classes CRectangle and CTriangle each contain members inherited from CPolygon. These are: width, height and set_values().

Multiple inheritance

Allows you to create a derived class that inherits properties from more than one base class. Because a derived class inherits members from all its base classes, ambiguities can result. For example, if two base classes have a member with the same name, the derived class cannot implicitly differentiate between the two members.

In the following example, classes A, B, and C are direct base classes for the derived class X:

class A { /* ... */ };class B { /* ... */ };class C { /* ... */ };class X : public A, private B, public C { /* ... */ };

Questions :1. Explain protected mode 2. Diagram of multiple inheritance3. What's the difference between public, private, and protected?

Pictorial representation of object from your program.

SE (IT) (SEM-II) OOPCG Laboratory53

Page 54: A

SKNCOE,Pune IT Department

Experiment No 4

Title

2D transformation

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

SE (IT) (SEM-II) OOPCG Laboratory54

Page 55: A

SKNCOE,Pune IT Department

Subject Computer Graphics

SE (IT) (SEM-II) OOPCG Laboratory55

Page 56: A

SKNCOE,Pune IT Department

Problem Statement:

Write a program to implement Basic Transformations and Compose Transformation on Polygons.

Objective:

To study and Implement set of basic transformations on polygons like scaling , translation, rotation, reflection, shearing, etc.

Problem definition:A process in which an image is stretched differentially so as to change its internal geometry is said to have undergone geometric transformation. In other words, transformation means moving objects relative to a stationary coordinate system.

Basic Transformation

Scaling : change image content size Rotation : change image content orientation

Reflection : flip over image contents

Translation : change image content position

Shearing : Distorting the shape of the object in x,y or both directions (cutting of edges).

Homogeneous coordinates

In mathematics, homogeneous coordinates, introduced by August Ferdinand Möbius, allow affine transformations to be easily represented by a matrix. Also they make calculations possible in projective space just as Cartesian coordinates do in Euclidean space. The homogeneous coordinates of a point of projective space of dimension n are usually written as (x : y : z : ... : w), a row vector of length n + 1, other than (0 : 0 : 0 : ... : 0). Two sets of coordinates that are proportional denote the same point of projective space: for any non-zero scalar c from the underlying field K, (cx : cy : cz : ... : cw) denotes the same point. Therefore this system of coordinates can be explained as follows: if the projective space is constructed from a vector space V of dimension n + 1, introduce coordinates in V by choosing a basis, and use these in P(V), the equivalence classes of proportional non-zero vectors in V.

Affine transformation

SE (IT) (SEM-II) OOPCG Laboratory56

Page 57: A

SKNCOE,Pune IT Department

In geometry, an affine transformation or affine map (from the Latin, affinis, "connected with") between two vector spaces (strictly speaking, two affine spaces) consists of a linear transformation followed by a translation:

In the finite-dimensional case each affine transformation is given by a matrix A and a vector b, which can be written as the matrix A with an extra column b.

Physically, an affine transform is one which preserves

1. Collinearity between points, ie. three points which lie on a line continue to be collinear after the transformation

2. Ratios of distances between any two points

In general, an affine transform is composed of translation, rotation, scaling and shear.

Point Representation P = (x,y)

1. Row Representation :

[ x y ]2. Column Representation :

In linear algebra, linear transformations can be represented by matrices.

A * T = B

A = Original Matrix in Row or Column Point Representation (of Order n x 3 or 3 x n)

T = Transformation Matrix (of order 3 for homogenous Systems)

B = Transformed Matrix

SE (IT) (SEM-II) OOPCG Laboratory57

Page 58: A

SKNCOE,Pune IT Department

Transformation Matrix :

1. Translation   

  1 0 0  

T =   0 1 0  

  tx ty 1     

2. Scaling   

  Sx 0 0  

S =   0 Sy 0  

  0 0 1     

3. Rotation        

  cosө sinө 0     cosө -sinө 0  

Raclk =   -sinө cosө 0  

Rclk =   sinө cosө 0  

  0 0 1     0 0 1  

       

4. Shearing   

  1 Ysh 0  

Sh =   Xsh 1 0  

SE (IT) (SEM-II) OOPCG Laboratory58

Page 59: A

SKNCOE,Pune IT Department

  0 0 1     

5. Reflection       

  1 0 0     -1 0 0  

Rx =   0 -1 0   Ry =   0 1 0  

  0 0 1     0 0 1         

   

  -1 0 0  

Ro =   0 -1 0  

  0 0 1     

Steps for Rotation by angle ө about an arbitrary Point (x,y)

Step 1 : Translate the Point to the origin (tx = -x, ty = -y)

Step 2 : Perform Rotation w.r.t to origin by angle ө

Step 3 : Retranslate the Point to its original position (tx = x , ty = y)

Eg. Find the transformation that rotates by an angle theta about a point P(x,y):

Let's choose to describe all transformations w.r.t. a fixed set of axes:

translate P to origin: trans(-2,-3,0) perform rotation: rot(z,90)

translate P back: trans(2,3,0)

T = trans(2,3,0) rot(z,90) trans(-2,-3,0)

SE (IT) (SEM-II) OOPCG Laboratory59

Page 60: A

SKNCOE,Pune IT Department

Steps for Reflection about an arbitrary line y = mx + c

Step 1 : Translation with ty = -c

Step 2 : Rotation with angle ө = tan-1m

Step 3 : Reflection about X-axis

Step 4 : Rotate Anticlockwise by angle ө

Step 5 : Retranslate to original place with ty = c;

Design experiment:

1. Write a program that applies any specified sequence of transformation to a displayed object. The program is to be designed so that a user selects the transformation sequence and associated parameters from displayed menus and the composite transformation is then calculated and used to transform the object. Display the original object and transformed object in different color.

2. Write a program which draws a house shaped, five sided polygon. Show this figure scaled .rotated, translated and under a combination of all three transformation .show this figure both filled and unfilled.

3. Write a program to continuously rotate an object about a pivot point.

SE (IT) (SEM-II) OOPCG Laboratory60

Page 61: A

SKNCOE,Pune IT Department

Experiment No 6(oopl)

Title Write a program in C++ using Templates

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject Computer Graphics

SE (IT) (SEM-II) OOPCG Laboratory61

Page 62: A

SKNCOE,Pune IT Department

Problem statement : Write a program in C++ using function template to read two matrices of different data types such as integers and floating point values and performsimple arithmetic operations on these matrices separately and display it.

Theory : C++ templates provide a way to re-use source code.  C++ provides two kinds of templates:

1. Class templates 2. Function templates.

Use function templates to write generic functions that can be used with arbitrary types. For example, one can write searching and sorting routines which can be used with any arbitrary type.C++ Function templates are those functions which can handle different data types without separate code for each of them. For a similar operation on several kinds of data types, a programmer need not write different versions by overloading a function. It is enough if he writes a C++ template based function. This will take care of all the data types.Class Templates A class template definition looks like a regular class definition, except it is prefixed by the keyword template. Once code is written as a C++ class template, it can support all data types.

Declaration of C++ class template should start with the keyword template. A parameter should be included inside angular brackets. The parameter inside the angular brackets, can be either the keyword class or typename. This is followed by the class body declaration with the member data and member functions.

.

SE (IT) (SEM-II) OOPCG Laboratory62

template <class T>

class class_name {        // class member specification

// with anonymous type T wherever appropriate

};

Page 63: A

SKNCOE,Pune IT Department

T is a type parameter and it can be any type. Defining member functions - C++ Class Templates:

If the functions are defined outside the template class body, they should always be defined with the full template definition. Other conventions of writing the function in C++ class templates are the same as writing normal c++ functions.

Advantages of C++ Class Templates:   One C++ Class Template can handle different types of parameters. Compiler generates classes for only the used types. If the template is

instantiated for int type, compiler generates only an int version for the c++ template class.

Templates reduce the effort on coding for different data types to a single set of code.

Testing and debugging efforts are reduced.

Function templates

There are lot of occasions, where we might need to write the same functions for different data types. A favorite example can be addition of two variables. The variable can be integer, float or double. The requirement will be to return the corresponding return type based on the input type. If we start writing one function for each of the data type, then we will end up with 4 to 5 different functions, which can be a night mare for maintenance.

C++ templates come to our rescue in such situations.  When we use C++ function templates, only one function signature needs to be created. The C++ compiler will automatically generate the required functions for handling the individual data types.

Eg : Add function.

   template<classT>   T Add(T a, T b) //C++ function template sample   {     return a+b;   }

This c++ function template definition will be enough. Now when the integer version of the function, the compiler generates an Add function compatible for integer data type and if float is called it generates float type and so on.   Here T is the typename. This is dynamically determined by the compiler according to the

SE (IT) (SEM-II) OOPCG Laboratory63

Page 64: A

SKNCOE,Pune IT Department

parameter passed. The keyword class means, the parameter can be of any type. It can even be a class.

Questions1. What are templates used for?

Experiment No 5

Title

Case study of any graphics tool

Animation using Flash,3D-Max,Maya.

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

SE (IT) (SEM-II) OOPCG Laboratory64

Page 65: A

SKNCOE,Pune IT Department

Date

Subject Computer Graphics

SE (IT) (SEM-II) OOPCG Laboratory65

Page 66: A

SKNCOE,Pune IT Department

Problem Statement:

Write a program to implement 2D Animation. Real Time Clock ,Rocket Launching PoolTable Game, Motion of a Pendulum. etc.

Objective:

To Implement a program with animation of objects (segments) obtained by scan conversion.

Problem definition:

Sequences of pictures at educate or explain may require images of 3D objects. Although animation uses graphics as much for art as for realism, it depends heavily on motions to substitute for realism of an individual image. Animation is done by photographing a sequence of drawings, each slightly different from the previous. This can be achieved by segmentation.

For eg., to show a person moving his arm, a series of drawings is photographed, each drawing showing the arm at a different poSKNCOEion. When the images are displayed one after another from the frame buffer, we perceive the arm as moving through the sequence.

Segmentation : Process of extracting and representing information from an image is to group pixels together into regions of similarity. This process is commonly called segmentation. In 2D we would group pixels together according to the rate of change of their intensity over a region. In 3D we group together pixels according to the rate of change of depth in the image, corresponding to pixels lying on the same surface such as a plane, cylinder, sphere etc. There are two main approaches to segmentation.

Region Splitting Region Growing Statistical Region Description Invariant Measures

Region Splitting

The basic idea of region splitting is to break the image into a set of disjoint regions which are coherent within themselves:

Initially take the image as a whole to be the area of interest. Look at the area of interest and decide if all pixels contained in the region

satisfy some similarity constraint.

If TRUE then the area of interest corresponds to a region in the image.

SE (IT) (SEM-II) OOPCG Laboratory66

Page 67: A

SKNCOE,Pune IT Department

If FALSE split the area of interest (usually into four equal sub-areas) and consider each of the sub-areas as the area of interest in turn.

This process continues until no further splitting occurs. In the worst case this happens when the areas are just one pixel in size.

This is a divide and conquer or top down method.

If only a splitting schedule is used then the final segmentation would probably contain many neighbouring regions that have identical or similar properties. Thus, a merging process is used after each split which compares adjacent regions and merges them if necessary. Algorithms of this nature are called split and merge algorithms. To illustrate the basic principle of these methods let us consider an imaginary image.

Let I denote the whole image shown in Fig (a). Not all the pixels in I are similar so the region is split as in Fig (b). Assume that all pixels within regions I1, I2 and I3 respectively are similar

but those in I4 are not. Therefore I4 is split next as in Fig (c). Now assume that all pixels within each region are similar with respect to

that region, and that after comparing the split regions, regions I43 and I44 are found to be identical.

These are thus merged together as in Fig (d).

Fig. Example of region splitting and merging

We can describe the splitting of the image using a tree structure, using a modified quadtree. Each non-terminal node in the tree has at most four descendants, although it may have less due to merging.  

SE (IT) (SEM-II) OOPCG Laboratory67

Page 68: A

SKNCOE,Pune IT Department

Fig. Region splitting and merging tree

Region GrowingRegion growing approach is the opposite of the split and merge approach:

An initial set of small areas are iteratively merged according to similarity constraints.

Start by choosing an arbitrary seed pixel and compare it with neighbouring pixels.

Region is grown from the seed pixel by adding in neighbouring pixels that are similar, increasing the size of the region.

When the growth of one region stops we simply choose another seed pixel which does not yet belong to any region and start again.

This whole process is continued until all pixels belong to some region. A bottom up method.

Region growing methods often give very good segmentations that correspond well to the observed edges.

SE (IT) (SEM-II) OOPCG Laboratory68

Page 69: A

SKNCOE,Pune IT Department

Fig. Example of region growing

However starting with a particular seed pixel and letting this region grow completely before trying other seeds biases the segmentation in favour of the regions which are segmented first.

This can have several undesirable effects:

Current region dominates the growth process -- ambiguities around edges of adjacent regions may not be resolved correctly.

Different choices of seeds may give different segmentation results. Problems can occur if the (arbitrarily chosen) seed point lies on an edge.

To counter the above problems, simultaneous region growing techniques have been developed.

Similarities of neighbouring regions are taken into account in the growing process.

No single region is allowed to completely dominate the proceedings. A number of regions are allowed to grow at the same time. similar regions will gradually coalesce into expanding regions. Control of these methods may be quite complicated but efficient methods

have been developed. Easy and efficient to implement on parallel computers.

Statistical Region Description The features used in segmentation so far have been geometric or intensity

SE (IT) (SEM-II) OOPCG Laboratory69

Page 70: A

SKNCOE,Pune IT Department

gradient based. Instead of trying to extract such high level features, another approach is to work directly with regions of pixels in the image, and to describe them by various statistical measures. Such measures are usually represented by a single value. These can be calculated as a simple by-product of the segmentation procedures previously described. Such statistical descriptions may be divided into two distinct classes. Examples of each class are given below:

Geometric descriptions: area, length, perimeter, elongation, compactness, moments of inertia.

Topological descriptions: connectivity and Euler number.

Example :

RTC Pendulum Rocket launching

Design Experiments

1. Design box which can include video.

2. Implement slide Sequence provider.

3. Provide various options for design of ppt.

SE (IT) (SEM-II) OOPCG Laboratory70

Page 71: A

SKNCOE,Pune IT Department

Problem Statement:

Create a Presentation or animation using authoring tool Flash.

Objective:

To understand the animation process in Macromedia Flash.

Problem definition:Flash 5 provide enhanced capabilities for creating artwork, streamlining

your workflow, and creating interactivity. Flash 5 also includes greatly expanded capabilities for creating actions with ActionScript.

Flash movies are graphics and animation for Web sits. They consist primarily of vector graphics, but they can also contain imported bitmap graphics and sounds. Flash movies can incorporate interactivity to permit input from viewers, and you can create nonlinear movies that can interact with other Web applications. Web designers use Flash to create navigation controls, animated logos, long-form animations with synchronized sound, and even complete, sensory-rich Web sites. Flash movies are compact, vector graphics, so they download rapidly and scale to the viewer's screen size

Creating artwork

Enhanced color controls, including the Mixer panel, Fill and Stroke panels, Swatches panel, and Fill and Stroke toolbox controls, provide expanded capabilities for painting artwork.

New selection highlights make it easy to identify selected lines, fills, and groups as well as the color of selected objects.

Draggable guides aid you in arranging objects on the Stage.

The Pen tool lets you create precise paths; it works like the Pen tool in Macromedia FreeHand or Macromedia Fireworks.

 Workflow

New panels for working with color, type, actions, frames, instances, and entire movies make it easy to access options for modifying elements in Flash movies.

Shared libraries let you link to library items as external assets. You can create font symbols to include in shared libraries, as well as buttons, graphics, movie clips, and sounds.

The Macromedia Dashboard provides a way for you to easily keep up with the latest information on using Flash.

SE (IT) (SEM-II) OOPCG Laboratory71

Page 72: A

SKNCOE,Pune IT Department

Custom shortcut keys allow you to create your own shortcuts for Flash commands and functions to customize your workflow.

Support for importing MP3 sound files lets you import sounds into Flash that are already compressed. This reduces the time required for publishing and exporting a movie with sound, since you don't have to compress the sounds during export. Using compressed sounds reduces the file size of completed movies and reduces memory requirements during authoring.

 

Interactivity

Expanded ActionScript provides greatly enhanced capabilities for creating interactivity in Flash using ActionScript.

The Movie Explorer lets you easily view the complete contents of the current movie and view the Properties panel for a selected item to modify it..

The Print action lets you assign actions for printing Flash movie frames from the Flash Player as vector or bitmap graphics.

Drawing in Flash

Flash provides various tools for drawing freeform or precise lines, shapes, and paths, and painting filled objects.

Drawing with the Pencil tool

SE (IT) (SEM-II) OOPCG Laboratory72

Page 73: A

SKNCOE,Pune IT Department

To draw lines and shapes, you use the Pencil tool, in much the same way that you would use a real pencil to draw. To apply smoothing or straightening to the lines and shapes as you draw, you select a drawing mode for the Pencil tool.

Using the Pen tool

To draw precise paths as straight lines or smooth, flowing curves, you can use the Pen tool. You can create straight or curved line segments and adjust the angle and length of straight segments and the slope of curved segments.

Drawing straight lines, ovals, and rectangles

You can use the Line, Oval, and Rectangle tools to easily create these basic geometric shapes. The Oval and Rectangle tools create stroked and filled shapes. You can use the Rectangle tool to create rectangles with square or rounded corners.

Painting with the Brush tool

The Brush tool draws brush like strokes, as if you were painting. It lets you create special effects, including calligraphic effects. On most pressure-sensitive tablets, you can vary the width of the brush stroke by varying pressure on the stylus.

Specifying stroke and fill attributes

To specify stroke or fill color, you can use the Stroke and Fill controls in the toolbox, the Ink Bottle and Paint Bucket tools, or the Stroke panel and Fill panel. To modify stroke style or line weight, you use the Stroke panel. To create or edit gradient fills or apply bitmap fills, you use the Fill panel.

When you create new objects with the drawing and painting tools, the objects are painted with the attributes specified in the tools' Stroke and Fill controls. You can also change the stroke and fill attributes of existing objects.

You can copy stroke or fill attributes from one object to another using the Eyedropper tool.

Reshaping lines and shape outlines

You can reshape lines and shape outlines created with the Pencil, Brush, Line, Oval, or Rectangle tools by dragging with the Arrow tool, or by optimizing their curves.

You can also use the Subselection tool to display points on lines and shape outlines and modify the lines and outlines by adjusting the points.

When grids are displayed in a movie, they appear as lines behind the artwork in all scenes. You can snap objects to the grid, and you can modify the grid size and grid line color.

When rulers are displayed, they appear along the top and left sides of the movie. You can select the unit of measure used in the rulers. When you move an element on the Stage with the rulers displayed, lines indicating the element's dimensions appear on the rulers.

You can drag horizontal and vertical guides from the rulers onto the Stage when the rulers are displayed. You can move guides, lock guides, hide guides, and

SE (IT) (SEM-II) OOPCG Laboratory73

Page 74: A

SKNCOE,Pune IT Department

remove guides. You can also snap objects to guides and change guide color. Draggable guides appear only in the Timeline in which they were created.

Erasing

Erasing with the Eraser tool removes strokes and fills. You can quickly erase everything on the Stage, erase individual stroke segments or filled areas, or erase by dragging.

You can customize the Eraser tool to erase only strokes, only filled areas, or only a single filled area. The Eraser tool can be either round or square, and it can have one of five sizes.

Snapping

To automatically align elements with one another, you can use snapping. Snapping can be turned on using the Snap modifier for the Arrow tool, or the Snap to Objects command in the View menu.

Using layers overview

Layers are like transparent sheets of acetate stacked on top of each other. When you create a new Flash movie, it contains one layer. You can add more layers to organize the artwork, animation, and other elements in your movie. You can draw and edit objects on one layer without affecting objects on another layer. Where there is nothing on a layer, you can see through it to the layers below.

The number of layers you can create is limited only by your computer's memory, and layers do not increase the file size of your published movie. You can hide layers, lock layers, or display layer contents as outlines. You can also change the order of layers.

In addition, you can use special guide layers to make drawing and editing easier, and mask layers to help you create sophisticated effects.

It's a good idea to use separate layers for sound files, actions, frame labels, and frame comments. This helps you find these items quickly when you need to edit them.

Creating animation overview

You create animation by changing the content of successive frames. You can make an object move across the Stage, increase or decrease its size, rotate, change color, fade in or out, or change shape. Changes can occur independently of, or in concert with, other changes. For example, you can make an object rotate and fade in as it moves across the Stage.

There are two methods for creating an animation sequence in Flash: frame-by-frame animation and tweened animation. In frame-by-frame animation you create the image in every frame. In tweened animation, you create starting and ending frames and let Flash create the frames in between. Flash varies the object's size, rotation, color, or other attributes evenly between the starting and ending frames to create the appearance of movement.

SE (IT) (SEM-II) OOPCG Laboratory74

Page 75: A

SKNCOE,Pune IT Department

Tweened animation is an effective way to create movement and changes over time while minimizing file size. In tweened animation, Flash stores only the values for the changes between frames. In frame-by-frame animation, Flash stores the values for each complete frame.

Guidelines : Flash Basics

Find your way around the flash environment Be able to draw and modify simple graphics Create more complex graphics on a single layer Create transparent objects Understand grouping and stacking order

Symbols and Basic Animation Create graphics on multiple layers Understand and organize layers Work with different types of layers Create and use symbols Use non-flash graphics Create basic frame-by-frame animations

Motion and Shape Tweening Be able to animate with motion tweening Move, rotate, scale and create color effects for your graphics Move objects along a path you define Morph shapes into other shapes Create shapes that move as they change

More Complex Animations Understand how to create scenes Animate multiple tweens Reverse frames Use movie clip symbols Create animated masks Be able to create more complex animations

Basic Actions and Introduction to Buttons Understand the Actions panel Understand some of the basics and possibilities of actionscripting Add actions to frames Assign frame labels and comments Create named anchors Control movie playback Create basic buttons Assign actions to your buttons Create your own slideshow

Delivering your Movies and Conclusion

SE (IT) (SEM-II) OOPCG Laboratory75

Page 76: A

SKNCOE,Pune IT Department

Be able to deliver movies to your audience Control movie placement in your browser Work with flash player settings

Basic Animation in Macromedia Flash MX describe the Flash MX interface. describe how to design and publish a movie in Flash MX. recognize the drawing tools and work with graphics in Flash MX. import graphics, use text, and create masks in Flash MX. add text to a layer and realign it in Flash MX. work with libraries, symbols, and instances in Flash MX. create frame-by-frame animation in Flash MX. create a motion tween in Flash MX. use shape tweening and shape hints in Flash MX. add a motion tween and a motion guide using Flash MX. recognize the difference between graphic and button symbols in

Flash MX. use components in Flash MX to add interactivity to a movie and to

create a complete user interface for web forms. create and organize a navigation bar using symbols and libraries in

Flash MX.

Design Experiments

1. Design box which can include & video.

2. Implement slide Sequence provider.

SE (IT) (SEM-II) OOPCG Laboratory76

Page 77: A

SKNCOE,Pune IT Department

Experiment No 7(oopl)

Title Develop a program using Virtual functions & files

Roll No.

College SKNCOE , Pune

SE (IT) (SEM-II) OOPCG Laboratory77

Page 78: A

SKNCOE,Pune IT Department

Class S.E. (IT)

Date

Subject oopcg

Problem statement : : Design a base class consisting of the data members such as name of the student, roll number and subject. The derived class consists of the data members subject code, internal assessment and university examination marks. Construct a virtual base class for the item name of the student and roll number. The program should have the facilities.i) Build a master table ii) List a table iii) Insert a new entryiv) Delete old entry v) Edit an entry vi) Search for a record

Theory : C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. The whole function body can be replaced with a new set of implementation in the derived class. An iessensial property of the polymorphism is the ability to refer to objects w/o any regard to their classes. This necessitates the use of a single pointer variable to refer to the objects of different clases. Here we use pointers to the base class to refer to all the derived objects. But the base pointer , even when it is made to contain the address of a derived class , always executes the function in the base class. The compiler simply ignores the contents of the pointer and chooses the member function that matches the type of the pointer. This problem is solved by virtual function.

SE (IT) (SEM-II) OOPCG Laboratory78

Page 79: A

SKNCOE,Pune IT Department

C++ Virtual Function - Properties:   C++ virtual function is,

A member function of a class Declared with virtual keyword Usually has a different functionality in the derived class A function call is resolved at run-time

The difference between a non-virtual c++ member function and a virtual member function is, the non-virtual member functions are resolved at compile time. This mechanism is called static binding. Where as the c++ virtual member functions are resolved during run-time. This mechanism is known as dynamic binding.

C++ Virtual Function - Reasons:

The most prominent reason why a C++ virtual function will be used is to have a different functionality in the derived class.

Rules for virtual functions :

When virtual functions are created for implementing late binding , we should observe some basic rules that satisfy the compiler requirements.

1. The virtual functions must be member of the same class2. They can not be static members

3. They are accessed by using object pointers

4. A virtual function can be a friend of another class.

Input/Output with filesC++ provides the following classes to perform output and input of characters to/from files:

ofstream: Stream class to write on files

ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files

SE (IT) (SEM-II) OOPCG Laboratory79

Page 80: A

SKNCOE,Pune IT Department

Opening files using open() The function open() can be used to open multiple files that use same stream object .

Eg fstream inoutfile;Inoutfile.open(“book.dat”);

Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::ateSet the initial position at the end of the file.If this flag is not set to any value, the initial position is the beginning of the file.

ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():

ofstream myfile;myfile.open ("example.bin", ios::out | ios::app | ios::binary);

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectivelly assumed, even if a mode that does not include them is passed as second argument to the open() member function.

The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.

File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text

SE (IT) (SEM-II) OOPCG Laboratory80

File_stream_class stream _object ;Stream_object .open (“filename”,mode);

Page 81: A

SKNCOE,Pune IT Department

files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefor, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:

ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);

Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }

Closing a file

When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

myfile.close();

Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.

Checking state flagseof() Returns true if a file open for reading has reached the end. Binary filesIn binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).

File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member

SE (IT) (SEM-II) OOPCG Laboratory81

Page 82: A

SKNCOE,Pune IT Department

function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are:

write ( memory_block, size );read ( memory_block, size );

Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.

Text files

Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Data output operations on text files are performed in the same way we operated with cout:

Functions for manipulation of file pointers :

All the actions on the file pointers take place automatically by default. The file stream classes support following functions to manage file pointers manually.

tellg() and tellp()These two member functions have no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer (in the case of tellg) or the put stream pointer (in the case of tellp). seekg() and seekp()These functions allow us to change the position of the get and put stream pointers. Both functions are overloaded with two different prototypes. The first prototype is:

seekg ( position );seekp ( position );

Using this prototype the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is the same as the one returned by functions tellg and tellp: the member type pos_type, which is an integer value.

Questions :

SE (IT) (SEM-II) OOPCG Laboratory82

Page 83: A

SKNCOE,Pune IT Department

1. Opening files using constructors.2. Explain seekg(), seekp(), tellg(), tellp();3. Differentiate between ‘ate’ mode and ‘app’ mode.4. What is a virtual member function?5. What is a pure virtual member function?6. What's the difference between how virtual and non-virtual member

functions are called?

SE (IT) (SEM-II) OOPCG Laboratory83

Page 84: A

SKNCOE,Pune IT Department

Experiment No 8(oopl)

Title Write a program in C++ for Exception Handling

Roll No.

College SKNCOE , Pune

Class S.E. (IT)

Date

Subject oopcg

SE (IT) (SEM-II) OOPCG Laboratory84

Page 85: A

SKNCOE,Pune IT Department

Problem statement : Create a class named Television that has data members to hold the model number and the screen size in inches, and the price. Member functions include overloaded insertion and extraction operators. If more than four digits are entered for the model, if the screen size is smaller than 12 or greater than 70 inches, or if the price is negative or over $5000 then throw an integer. Write a main() function that instantiates a television object, allows user to enter data and displays the data members . If an exception is caught , replace all the data member values with zero values.

Theory :

One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected circumstance that the section of code containing the problem is not explicitly designed to handle. In C++, exception handling is useful bcause it makes it easy to separate the error handling code from the code written to handle the chores of the program. Doing so makes reading and writing the code easier.

Furthermore, exception handling in C++ propagates the exceptions up the stack; therefore, if there are several functions called, but only one function that needs to reliably deal with errors, the method C++ uses to handle exceptions means that it can easily handle those exceptions without any code in the intermediate functions. One consequence is that functions don't need to return error codes, freeing their return values for program logic.

When errors occur, the function generating the error can 'throw' an exception. For example, take a sample function that does division: const int DivideByZero = 10;//....double divide(double x, double y){ if(y==0) { throw DivideByZero; } return x/y;}

The function will throw DivideByZero as an exception that can then be caught by an exception-handling catch statement that catches exceptions of type int. The necessary construction for catching exceptions is a try catch system. If you wish to have your program check for exceptions, you must enclose the code that may have exceptions thrown in a try block. For example: try{ divide(10, 0);}catch(int i){ if(i==DivideByZero)

SE (IT) (SEM-II) OOPCG Laboratory85

Page 86: A

SKNCOE,Pune IT Department

{ cerr<<"Divide by zero error"; }}

The catch statement catches exceptions that are of the proper type. You can, for example, throw objects of a class to differentiate between several different exceptions. As well, once a catch statement is executed, the program continues to run from the end of the catch.

It is often more useful for you to create a class that stores information on exceptions as they occur. For example, it would be more useful if you had a class to handle exceptions. class DivideByZero{ public: double divisor; DivideByZero(double x);};DivideByZero::DivideByZero(double x) : divisor(x){}int divide(int x, int y){ if(y==0) { throw DivideByZero(x); }}try{ divide(12, 0);}catch (DivideByZero divZero){ cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";}

If you wish to catch more than one possible exception, you can specify separate catch blocks for each type of exception. It's also possible to have a general exception handler that will respond to any thrown exception. To use it, simply use catch(...) for the catch statement and print a general warning of some kind.

The handy thing to remember about exception handling is that the errors can be handled outside of the regular code. This means that it is easier to structure the program code, and it makes dealing with errors more centralized. Finally, because the exception is passed back up the stack of calling functions, you can handle errors at any place you choose.

In C, you might see some error handling code to free memory and close files repeated five or or six times, once for each possible error. A solution some programmers prefered was to use a goto statement that jumped all the way to the cleanup code. Now, you can just surround your code with a try-catch block and handle any cleanup following the catch (possibly with an additional copy of your

SE (IT) (SEM-II) OOPCG Laboratory86

Page 87: A

SKNCOE,Pune IT Department

cleanup routine inside the catch block if you intend to throw the exception again to alert the calling function of an error).

SE (IT) (SEM-II) OOPCG Laboratory87