Professional Documents
Culture Documents
Spring 2012 Master of Computer Application (MCA) - Semester III MC0074 - Statistical and Numerical Methods Using C++ - 4 Credits
Spring 2012 Master of Computer Application (MCA) - Semester III MC0074 - Statistical and Numerical Methods Using C++ - 4 Credits
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).
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.
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); ?
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();
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
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