You are on page 1of 14

Spring 2012 Master of Computer Application (MCA) Semester III MC0074 Statistical And Numerical Met ods !

!sing C"" 4 Credits


(#oo$ I%& #0'12)

1( %istinguis ed )et*een procedural language and ++, language( And -.plain t e $e/ features of ++,( Ans( a. %istinguis ed )et*een procedural language and ++, language
Procedural programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. Procedural programming also focuses on the idea that all algorithms are executed with functions and data that the programmer has access to and is able to change. Object-Oriented programming is much more similar to the way the real world works; it is analogous to the human brain. Each program is made up of many entities called objects. Objects become the fundamental units and ha e beha ior! or a specific purpose! associated with them. Objects cannot directly access another object"s data. #nstead! a message must be sent requesting the data! just like people must ask one another for information; we cannot see inside each other"s heads. $enefits of ObjectOriented programming include% ability to simulate real-world e ent much more effecti ely code is reusable thus less code may ha e to be written data becomes acti e better able to create &'# (graphical user interface) applications programmers are able to reach their goals faster Programmers are able to produce faster! more accurate and better-written applications (in the case of a eteran programmer! by a factor of as much as *+ times compared with a procedural program).

)( -.plain t e $e/ features of ++,(


-ncapsulation , Encapsulation is capturing data and keeping it safely and securely from outside interfaces. In eritance- -his is the process by which a class can be deri ed from a base class with all features of base class and some of its own. -his increases code reusability. ,ol/morp ism- -his is the ability to exist in arious forms. .or example an operator can be o erloaded so as to add two integer numbers and two floats. A)straction- -he ability to represent data at a ery conceptual le el without any details.

Dinesh (521138580) 2( 0 at is function o1erloading2 0rite a c"" program to implement a function o1erloaded( Ans a( 0 at is function o1erloading
/00 permits the use of two function with the same name. 1owe er such functions essentially ha e different argument list. -he difference can be in terms of number or type of arguments or both. -his process of using two or more functions with the same name but differing in the signature is called function o erloading. $ut o erloading of functions with different return types are not allowed. #n o erloaded functions ! the function call determines which function definition will be executed. -he biggest ad antage of o erloading is that it helps us to perform same operations on different datatypes without ha ing the need to use separate names for each ersion.

)( 0rite a c"" program to implement a function o1erloaded(


2include3iostream4 using namespace std; int abslt(int ); long abslt(long ); float abslt(float ); double abslt(double ); int main() 5 int intgr6-7; long lng689**7; float flt6-7.7:; double dbl6-97.:;:<; cout33=> absoulte alue of =>33intgr33=> 6 =>33abslt(intgr)33endl; cout33=> absoulte alue of =>33lng33=> 6 =>33abslt(lng)33endl; cout33=> absoulte alue of =>33flt33=> 6 =>33abslt(flt)33endl; cout33=> absoulte alue of =>33dbl33=> 6 =>33abslt(dbl)33endl; ? int abslt(int num) 5 if(num46+) return num; else return (-num); ? long abslt(long num) 5 if(num46+)

MC00066

Page 2

Dinesh (521138580)
return num; else return (-num); ? float abslt(float num) 5 if(num46+) return num; else return (-num); ? double abslt(double num) 5 if(num46+) return num; else return (-num); ?

3( %iscuss t e constructors and %estructors *it suita)le e.ample( Ans(


/onstructor function gets in oked when an object of a class is constructed (declared) and destructor function gets in oked when the object is destructed (goes out of scope). 'se of /onstructor and @estructor function of a class./onstructor function is used to initialiAe member ariables to pre-defined alues as soon as an object of a class is declared./onstructor function ha ing parameters is used to initialiAe the data members to the alues passed alues! upon declaration&enerally! the destructor function is needed only when constructor has allocated dynamic memory. Example % constructor class myclass 5 pri ate% int a; int b; public% myclass() 5 BBhere constructor function is used to BBinitialiAe data members to pre-def BB alues a6C+; b6C+; ? int add( oid) 5 return a0b; ? ?; oid main( oid) 5 myclass a; cout33a.add(); ?

MC00066

Page 3

Dinesh (521138580)
Example @estructor BBExample Program in /00 2include3iostream.h4 class myclass 5 public% Dmyclass() 5 cout33>destructed=n>; ? ?; oid main( oid) 5 myclass obj; cout33>inside main=n>; ?

4( 0 at do /ou mean )/ operator o1erloading2 Illustrate *it suita)le e.ample for o1erloading !nar/ operators( Ans(
Operator o erloading is the ability to tell the compiler how to perform a certain operation when its corresponding operator is used on one or more ariables. .or example! the compiler acts differently with regards to the subtraction operator E-E depending on how the operator is being used. Fhen it is placed on the left of a numeric alue such as -9<! the compiler considers the number a negati e alue. Fhen used between two integral alues! such as <+-;C*! the compiler applies the subtraction operation. Fhen used between an integer and a doubleprecision number! such as 77<-G.*;! the compiler subtracts the left number from the right number; the operation produces a double-precision number. Fhen the - symbol is doubled and placed on one side of a ariable! such as --Hariable or Hariable--! the alue of the ariable needs to be decremented; in other words! the alue C shall be subtracted from it. Ill of these operations work because the subtraction operator E-J has been reconfigured in arious classes to act appropriately. Kuppose you create a class named -/ountry as follows% BB---------------------------------------------------------------------------= struct -/ountry 5 string Lame; double Population; long double Irea; string /apital; char &o ernment;

MC00066

Page 4

Dinesh (521138580)

?; BB--------------------------------------------------------------------------Kuppose you declare two -/ountry ariables such as% -/ountry KriManka! $angla@esh; #f you write an expression such as KriManka 0 $angla@esh and want to display the result! the compiler would need to know what you are trying to achie e. @o you want to add the names of the countries and create a new string nameN @o you want to get the result of their combined populations! or the total or their areasN Operator o erloading allows you to help the compiler perform this type of operation when it is applied on your object(s). @efaults Oethods% I Pe iew Fhen studying constructors! we learned that! whene er you create an object! the compiler automatically creates some of its necessary methods. .or example! you can create a -Kquare class as follows% BB--------------------------------------------------------------------------2include 3iostream4 2include 3iomanip4 using namespace std; BB--------------------------------------------------------------------------struct -Kquare 5 public% oid setKide(const double s) 5 Kide 6 s; ? double getKide() const 5 return Kide; ? double Perimeter() const 5 return 9 Q Kide; ? double Irea() const 5 return Kide Q Kide; ? pri ate% double Kide; ?;

MC00066

Page 5

Dinesh (521138580)
BB--------------------------------------------------------------------------oid Properties(const -KquareR /arre) 5 cout 33 >Properties of the square>; cout 33 setiosflags(ios%%fixed) 33 setprecision(*); cout 33 >=nKide% > 33 /arre.getKide();

cout 33 >=nPerimeter% > 33 /arre.Perimeter(); cout 33 >=nIrea% ? BB--------------------------------------------------------------------------int main(int argc! charQ arg ST) 5 -Kquare /up1older; > 33 /arre.Irea();

/up1older.setKide(87.77); Properties(/up1older);

return +; ? BB---------------------------------------------------------------------------o start! if you do not create a constructor! the compiler would create one for you. -his is called the default constructor. Otherwise! you can create your own% BB--------------------------------------------------------------------------struct -Kquare 5 public%

MC00066

Page 6

Dinesh (521138580)
-Kquare(); oid setKide(const double s) 5 Kide 6 s; ? double getKide() const 5 return Kide; ? double Perimeter() const 5 return 9 Q Kide; ? double Irea() const 5 return Kide Q Kide; ? pri ate% double Kide; ?; BB---------------------------------------------------------------------------Kquare%%-Kquare() 5 ? BB--------------------------------------------------------------------------#n the same way! if you do not create a destructor! the compiler would also create one for you. Otherwise! you can create your own destructor% BB--------------------------------------------------------------------------struct -Kquare 5 public% -Kquare(); irtual D-Kquare(); oid setKide(const double s) 5 Kide 6 s; ? double getKide() const 5 return Kide; ? double Perimeter() const 5 return 9 Q Kide; ? double Irea() const 5 return Kide Q Kide; ? pri ate%

MC00066

Page 7

Dinesh (521138580)
double Kide; ?; BB---------------------------------------------------------------------------Kquare%%-Kquare() 5 ? BB---------------------------------------------------------------------------Kquare%%D-Kquare() 5 ? BB---------------------------------------------------------------------------o allow making copies of objects! the compiler also creates an appropriate constructor for you if you do not define one for your object. -his is called the copy constructor. Uou can still explicitly create one as follows% BB--------------------------------------------------------------------------struct -Kquare 5 public% -Kquare(); -Kquare(const -KquareR V); irtual D-Kquare(); oid setKide(const double s) 5 Kide 6 s; ? double getKide() const 5 return Kide; ? double Perimeter() const 5 return 9 Q Kide; ? double Irea() const 5 return Kide Q Kide; ? pri ate% double Kide;

MC00066

Page 8

Dinesh (521138580)

?; BB---------------------------------------------------------------------------Kquare%%-Kquare() 5 ? BB---------------------------------------------------------------------------Kquare%%-Kquare(const -KquareR Kq) % Kide(Kq.Kide) 5 ? BB---------------------------------------------------------------------------Kquare%%D-Kquare() 5 ? BB--------------------------------------------------------------------------#n reality! there are four default functions that the compiler creates for you if you do not define them yourself. $esides the default constructor! the copy constructor! and the destructor! the compiler also create an o erloaded assignment operator function for you. -his can be easily seen on the code completion if you ha e not yet created this function for an object% Ko far! we ha e been able to assign a ariable declared from a class to another ariable of the same type. 1ere is an example% BB--------------------------------------------------------------------------oid Properties(const -KquareR /arre) 5 cout 33 >Properties of the square>; cout 33 setiosflags(ios%%fixed) 33 setprecision(*); cout 33 >=nKide% > 33 /arre.getKide();

MC00066

Page 9

Dinesh (521138580)
cout 33 >=nPerimeter% > 33 /arre.Perimeter(); cout 33 >=nIrea% ? BB--------------------------------------------------------------------------int main(int argc! charQ arg ST) 5 -Kquare 1older! Moop; > 33 /arre.Irea();

1older.setKide(87.77); Properties(1older); cout 33 >=n=n>;

Moop.setKide(C<.+9); -Kquare $ase(Moop); Properties($ase); cout 33 >=n=n>;

-Kquare Kink 6 1older; Properties(Kink);

return +; ? BB---------------------------------------------------------------------------his assignment operation is possible because the compiler is configured to take care of it! using its own default created o erloaded assignment operator function.

4( %ifference )et*een a static mem)er function and non5static mem)er functions *it appropriate e.ample( MC00066 Page 10

Dinesh (521138580) Ans(


Okay. Fhen we declare a member function to be static! we donWt ha e to specify an object when we call the member function. -hus! we can refer to the static member function -oday by its name followed by empty parentheses to indicate a function call. Fithin @atedKtock#tem member functions! writing >-oday();> is sufficient. Of course! if -oday were public! and we wanted to call it from a nonmember function! we would ha e to refer to it by its full name% @atedKtock#tem%%-oday(). Either of these calls differs from the normal use of a member function! where we specify the function along with the object to which it applies - for example! in the expression >soup.&etPrice();>. -hat explains what the static modifier does! but why would we want to use itN $ecause some member functions donWt apply to any particular object! it is con enient to be able to call such a function without needing an object with which to call it. #n the case of the -oday function! the alue of todayWs date is not dependent on any @atedKtock#tem object; therefore! it makes sense to be able to call -oday without referring to any object of the @atedKtock#tem class. It this point! Kusan had a flash of insight about the utility of static member functions% %% ;;; Kusan% # just realiAed that this way of writing functions is sort of like writing a path; it tells the compiler where to go to find things - is that rightN Kte e Pight. -he reason that we make this a member function is to control access to it and to allow it to be used by this class! not because it works on a particular class object (as is the case with non-static member functions). Kusan Ko! is using this static thing like making it a defaultN Kte e Kort of! because you donWt ha e to specify an object for the function to act on. Of course! we could also a oid ha ing to pass an object to the -oday function by making it a global function. 1owe er! the ad antages of using a static protected member function rather than a global one are much the same as the ad antages of using pri ate rather than public member ariables. .irst! we can change the interface of this function more easily than that of a global function! as we know that it can be accessed only by member functions of @atedKtock#tem and any possible deri ed classes of that class! not by any function anywhere. Kecond! we donWt ha e to worry that someone else might want to define a different function with the same signature! which could be a problem with a global function. -he full name of this function! @atedKtock#tem%%-oday()! is sufficient to distinguish it from any other -oday functions that belong to other classes! or e en from a global function of that name! should another programmer be so inconsiderate as to write oneX -hereWs one other thing here that we ha enWt seen before% -oday is a protected member function! which means that it is accessible only to member functions of @atedKtock#tem and its descendants! just as a protected member ariable is. Fe want to keep this function from being called by application programs for the same reason that we protect member ariables by restricting access% to reser e the right to change its name! return alue! or argument types. Ipplication code canWt access this function and therefore canWt depend on its interface. Kusan had some questions about changing the -oday function as well as about the more general idea of many programmers working on the same program. Kusan% Fhy would we want to change the -oday functionN #t seems like it would work fine the way it is. Kte e Fell! we might decide to make it return a number rather than a string! if we changed the way we implemented our date comparisons. $ut the point is more general

MC00066

Page 11

Dinesh (521138580)

the fewer people who know about a particular function! the easier it will be to make changes to its interface. Kusan Fho are these other people youWre always talking aboutN # thought a programmer wrote his own programs. Kte e -hat all depends. Kome small projects are done by a single programmer! which might seem to make access specifiers redundant. $ut they really arenWt! e en in that case! because a lone programmer puts on different >hats> while writing a significant program. Kometimes heWs a class designer and sometimes an application programmer. $ut where these design considerations are really important is in big projects! which may be written by doAens or e en hundreds of programmers. #n such cases! the result of letting e eryone access e ery ariable or function can be summed up in one word chaos. Kuch freefor-alls ha e led to a lot of buggy software.

6( 0riter C"" program to demonstrate t e complete implementation of class template stac$( Ans
BB basicsBstackC.hpp 2include 3 ector4 2include 3stdexcept4 template 3typename -4 class Ktack 5 pri ate% std%% ector3-4 elems;

BB elements

public% oid push(- constR); BB push element oid pop(); BB pop element - top() const; BB return top element bool empty() const 5 BB return whether the stack is empty return elems.empty(); ? ?; template 3typename -4 oid Ktack3-4%%push (- constR elem) 5 elems.pushYback(elem); BB append copy of passed elem ? template3typename -4 oid Ktack3-4%%pop () 5 if (elems.empty()) 5 throw std%%outYofYrange(>Ktack34%%pop()% empty stack>); ? elems.popYback(); BB remo e last element ? template 3typename -4 - Ktack3-4%%top () const 5 if (elems.empty()) 5 throw std%%outYofYrange(>Ktack34%%top()% empty stack>); ? return elems.back(); BB return copy of last element ?

MC00066

Page 12

Dinesh (521138580)

7( 0 at is template speciali7ation2 %escri)e a scenario in * ic template class partial speciali7ation is considered appropriate Ans(
#n many cases when working with templates! youWll write one generic ersion for all possible data types and lea e it at that--e ery ector may be implemented in exactly the same way. -he idea of template specialiAation is to o erride the default template implementation to handle a particular type in a different way. .or instance! while most ectors might be implemented as arrays of the gi en type! you might decide to sa e some memory and implement ectors of bools as a ector of integers with each bit corresponding to one entry in the ector. Ko you might ha e two separate ector classes. -he first class would look like this. template 3typename -4 class ector 5 BB accessor functions and so forth pri ate% -Q ecYdata; BB weWll store the data as block of dynamically allocated BB memory int length; BB number of elements used int ecYsiAe; BB actual siAe of ecYdata ?; $ut when it comes to bools! you might not really want to do this because most systems are going to use C: or 8* bits for each boolean type e en though all thatWs required is a single bit. Ko we might make our boolean ector look a little bit different by representing the data as an array of integers whose bits we manually manipulate. (.or more on manipulating bits directly! see bitwise operators and bit manipulations in / and /00.) -o do this! we still need to specify that weWre working with something akin to a template! but this time the list of template parameters will be empty% template 34 class ector 3bool4 5 BB interface pri ate% unsigned int Q ectorYdata; int length; int siAe; ?; Lote that it would be perfectly reasonable if the specialiAed ersion of the ector class had a different interface (set of public methods) than the generic ector class--although theyWre both ector templates! they donWt share any interface or any code.

MC00066

Page 13

Dinesh (521138580)
#tWs worth pointing out that the salient reason for the specialiAation in this case was to allow for a more space-efficient implementation! but you could think of other reasons why this might come in handy--for instance! if you wanted to add extra methods to one templated class based on its type! but not to other templates. .or instance! you might ha e a ector of doubles with a method that returns the non-integer component of each element although you might think prefer inheritance in this case. -here isnWt a particular reason to pre ent the existence of a ector of doubles without those extra features. #f! howe er! you felt strongly about the issue and wanted to pre ent it! you could do so using template specialiAation. Inother time when you might want to specialiAe certain templates could be if you ha e a template type that relies on some beha ior that was not implemented in a collection of classes youWd like to store in that template. .or example! if you had a templated sortedHector type that required the 4 operator to be defined! and a set of classes written by someone else that didnWt include any o erloaded operators but did include a function for comparison! you might specialiAe your template to handle these classes separately.

MC00066

Page 14

You might also like