Sei sulla pagina 1di 15

Spring 2012 Master of Computer Application (MCA) Semester III MC0074 Statistical And Numerical Methods Using C++

++ 4 Credits
(Book ID: B0812)

1. Distinguished between procedural language and OOP language. And Explain the key features of OOP. Ans. a. Distinguished between procedural language and OOP 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 have behavior, or a specific purpose, associated with them. Objects cannot directly access another objects data. Instead, a message must be sent requesting the data, just like people must ask one another for information; we cannot see inside each others heads. Benefits of Object-Oriented programming include: ability to simulate real-world event much more effectively code is reusable thus less code may have to be written data becomes active better able to create GUI (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 veteran programmer, by a factor of as much as 20 times compared with a procedural program).

b. Explain the key features of OOP.


Encapsulation Encapsulation is capturing data and keeping it safely and securely from outside interfaces. Inheritance- This is the process by which a class can be derived from a base class with all features of base class and some of its own. This increases code reusability. Polymorphism- This is the ability to exist in various forms. For example an operator can be overloaded so as to add two integer numbers and two floats.

Dinesh (521138580)
Abstraction- The ability to represent data at a very conceptual level without any details.

2. What is function overloading? implement a function overloaded. Ans a. What is function overloading

Write a c++ program to

C++ permits the use of two function with the same name. However such functions essentially have different argument list. The difference can be in terms of number or type of arguments or both. This process of using two or more functions with the same name but differing in the signature is called function overloading. But overloading of functions with different return types are not allowed. In overloaded functions , the function call determines which function definition will be executed. The biggest advantage of overloading is that it helps us to perform same operations on different datatypes without having the need to use separate names for each version.

b. Write a c++ program to implement a function overloaded.


#include<iostream> using namespace std;

int abslt(int ); long abslt(long ); float abslt(float ); double abslt(double ); int main() { int intgr=-5; long lng=34225; float flt=-5.56; double dbl=-45.6768; cout<<\" absoulte value cout<<\" absoulte value cout<<\" absoulte value cout<<\" absoulte value } int abslt(int num) { if(num>=0) return num; else

of of of of

\"<<intgr<<\" = \"<<abslt(intgr)<<endl; \"<<lng<<\" = \"<<abslt(lng)<<endl; \"<<flt<<\" = \"<<abslt(flt)<<endl; \"<<dbl<<\" = \"<<abslt(dbl)<<endl;

MC00066

Page 2

Dinesh (521138580)
return (-num); } long abslt(long num) { if(num>=0) return num; else return (-num); } float abslt(float num) { if(num>=0) return num; else return (-num); } double abslt(double num) { if(num>=0) return num; else return (-num); }

3. Discuss the constructors and Destructors with suitable example. Ans.

Constructor function gets invoked when an object of a class is constructed (declared) and destructor function gets invoked when the object is destructed (goes out of scope). Use of Constructor and Destructor function of a class.Constructor function is used to initialize member variables to pre-defined values as soon as an object of a class is declared.Constructor function having parameters is used to initialize the data members to the values passed values, upon declarationGenerally, the destructor function is needed only when constructor has allocated dynamic memory. Example : constructor class myclass { private: int a; int b; public: myclass() { //here constructor function is used to //initialize data members to pre-def //values a=10; b=10; } int add(void) { return a+b; } };

MC00066

Page 3

Dinesh (521138580)
void main(void) { myclass a; cout<<a.add(); } Example Destructor //Example Program in C++ #include<iostream.h> class myclass { public: ~myclass() { cout<<"destructed\n"; } }; void main(void) { myclass obj; cout<<"inside main\n"; }

4. What do you mean by operator overloading? Illustrate with suitable example for overloading Unary operators. Ans.
Operator overloading is the ability to tell the compiler how to perform a certain operation when its corresponding operator is used on one or more variables. For example, the compiler acts differently with regards to the subtraction operator - depending on how the operator is being used. When it is placed on the left of a numeric value such as -48, the compiler considers the number a negative value. When used between two integral values, such as 80-712, the compiler applies the subtraction operation. When used between an integer and a double-precision number, such as 558-9.27, the compiler subtracts the left number from the right number; the operation produces a double-precision number. When the - symbol is doubled and placed on one side of a variable, such as --Variable or Variable--, the value of the variable needs to be decremented; in other words, the value 1 shall be subtracted from it. All of these operations work because the subtraction operator - has been reconfigured in various classes to act appropriately. Suppose you create a class named TCountry as follows: //---------------------------------------------------------------------------\ struct TCountry { string Name;

MC00066

Page 4

Dinesh (521138580)
double Population; long double Area; string Capital; char Government; }; //--------------------------------------------------------------------------Suppose you declare two TCountry variables such as: TCountry SriLanka, BanglaDesh; If you write an expression such as SriLanka + BanglaDesh and want to display the result, the compiler would need to know what you are trying to achieve. Do you want to add the names of the countries and create a new string name? Do you want to get the result of their combined populations, or the total or their areas? Operator overloading allows you to help the compiler perform this type of operation when it is applied on your object(s). Defaults Methods: A Review When studying constructors, we learned that, whenever you create an object, the compiler automatically creates some of its necessary methods. For example, you can create a TSquare class as follows: //--------------------------------------------------------------------------#include <iostream> #include <iomanip> using namespace std; //--------------------------------------------------------------------------struct TSquare { public: void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; }

MC00066

Page 5

Dinesh (521138580)

double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------void Properties(const TSquare& Carre) { cout << "Properties of the square"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nSide: " << Carre.getSide();

cout << "\nPerimeter: " << Carre.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare CupHolder; " << Carre.Area();

CupHolder.setSide(35.55); Properties(CupHolder);

return 0; } //---------------------------------------------------------------------------

MC00066

Page 6

Dinesh (521138580)
To start, if you do not create a constructor, the compiler would create one for you. This is called the default constructor. Otherwise, you can create your own: //--------------------------------------------------------------------------struct TSquare { public: TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------TSquare::TSquare() { } //--------------------------------------------------------------------------In 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: //--------------------------------------------------------------------------struct TSquare { public: TSquare();

MC00066

Page 7

Dinesh (521138580)
virtual ~TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------TSquare::TSquare() { } //--------------------------------------------------------------------------TSquare::~TSquare() { } //--------------------------------------------------------------------------To allow making copies of objects, the compiler also creates an appropriate constructor for you if you do not define one for your object. This is called the copy constructor. You can still explicitly create one as follows: //--------------------------------------------------------------------------struct TSquare { public: TSquare(); TSquare(const TSquare& Q);

MC00066

Page 8

Dinesh (521138580)
virtual ~TSquare(); void setSide(const double s) { Side = s; } double getSide() const { return Side; } double Perimeter() const { return 4 * Side; } double Area() const { return Side * Side; } private: double Side; }; //--------------------------------------------------------------------------TSquare::TSquare() { } //--------------------------------------------------------------------------TSquare::TSquare(const TSquare& Sq) : Side(Sq.Side) { } //--------------------------------------------------------------------------TSquare::~TSquare() { } //--------------------------------------------------------------------------In reality, there are four default functions that the compiler creates for you if you do not define them yourself. Besides the default constructor, the copy constructor, and the destructor, the compiler also create an overloaded assignment operator function for you. This can be easily seen on the code completion if you have not yet created this function for an object:

MC00066

Page 9

Dinesh (521138580)
So far, we have been able to assign a variable declared from a class to another variable of the same type. Here is an example: //--------------------------------------------------------------------------void Properties(const TSquare& Carre) { cout << "Properties of the square"; cout << setiosflags(ios::fixed) << setprecision(2); cout << "\nSide: " << Carre.getSide();

cout << "\nPerimeter: " << Carre.Perimeter(); cout << "\nArea: } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { TSquare Holder, Loop; " << Carre.Area();

Holder.setSide(35.55); Properties(Holder); cout << "\n\n";

Loop.setSide(18.04); TSquare Base(Loop); Properties(Base); cout << "\n\n";

TSquare Sink = Holder;

MC00066

Page 10

Dinesh (521138580)

Properties(Sink);

return 0; } //--------------------------------------------------------------------------This assignment operation is possible because the compiler is configured to take care of it, using its own default created overloaded assignment operator function.

5. Difference between a static member function and non-static member functions with appropriate example. Ans.
Okay. When we declare a member function to be static, we don't have to specify an object when we call the member function. Thus, we can refer to the static member function Today by its name followed by empty parentheses to indicate a function call. Within DatedStockItem member functions, writing "Today();" is sufficient. Of course, if Today were public, and we wanted to call it from a nonmember function, we would have to refer to it by its full name: DatedStockItem::Today(). 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.GetPrice();". That explains what the static modifier does, but why would we want to use it? Because some member functions don't apply to any particular object, it is convenient to be able to call such a function without needing an object with which to call it. In the case of the Today function, the value of today's date is not dependent on any DatedStockItem object; therefore, it makes sense to be able to call Today without referring to any object of the DatedStockItem class. At this point, Susan had a flash of insight about the utility of static member functions: :: ;;; Susan: I just realized 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 right? Steve Right. The 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). Susan So, is using this static thing like making it a default? Steve Sort of, because you don't have to specify an object for the function to act on. Of course, we could also avoid having to pass an object to the Today function by making it a global function. However, the advantages of using a static protected member function rather than a global one are much the same as the advantages of using private rather than public member variables. First, 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 DatedStockItem and any possible derived classes of that class, not by any function anywhere. Second, we

MC00066

Page 11

Dinesh (521138580)
don't have 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. The full name of this function, DatedStockItem::Today(), is sufficient to distinguish it from any other Today functions that belong to other classes, or even from a global function of that name, should another programmer be so inconsiderate as to write one! There's one other thing here that we haven't seen before: Today is a protected member function, which means that it is accessible only to member functions of DatedStockItem and its descendants, just as a protected member variable is. We want to keep this function from being called by application programs for the same reason that we protect member variables by restricting access: to reserve the right to change its name, return value, or argument types. Application code can't access this function and therefore can't depend on its interface. Susan had some questions about changing the Today function as well as about the more general idea of many programmers working on the same program. Susan: Why would we want to change the Today function? It seems like it would work fine the way it is. Steve Well, we might decide to make it return a number rather than a string, if we changed the way we implemented our date comparisons. But the point is more general the fewer people who know about a particular function, the easier it will be to make changes to its interface. Susan Who are these other people you're always talking about? I thought a programmer wrote his own programs. Steve That all depends. Some small projects are done by a single programmer, which might seem to make access specifiers redundant. But they really aren't, even in that case, because a lone programmer puts on different "hats" while writing a significant program. Sometimes he's a class designer and sometimes an application programmer. But where these design considerations are really important is in big projects, which may be written by dozens or even hundreds of programmers. In such cases, the result of letting everyone access every variable or function can be summed up in one word chaos. Such free-for-alls have led to a lot of buggy software.

6. Writer C++ program to demonstrate implementation of class template stack. Ans


// basics/stack1.hpp #include <vector> #include <stdexcept> template <typename T> class Stack { private: std::vector<T> elems;

the

complete

// elements

MC00066

Page 12

Dinesh (521138580)

public: void push(T const&); // push element void pop(); // pop element T top() const; // return top element bool empty() const { // return whether the stack is empty return elems.empty(); } }; template <typename T> void Stack<T>::push (T const& elem) { elems.push_back(elem); // append copy of passed elem } template<typename T> void Stack<T>::pop () { if (elems.empty()) { throw std::out_of_range("Stack<>::pop(): empty stack"); } elems.pop_back(); // remove last element } template <typename T> T Stack<T>::top () const { if (elems.empty()) { throw std::out_of_range("Stack<>::top(): empty stack"); } return elems.back(); // return copy of last element }

7. What is template specialization? Describe a scenario in which template class partial specialization is considered appropriate Ans.
In many cases when working with templates, you'll write one generic version for all possible data types and leave it at that--every vector may be implemented in exactly the same way. The idea of template specialization is to override the default template implementation to handle a particular type in a different way. For instance, while most vectors might be implemented as arrays of the given type, you might decide to save some memory and implement vectors of bools as a vector of integers with each bit corresponding to one entry in the vector. So you might have two separate vector classes. The first class would look like this. template <typename T> class vector { // accessor functions and so forth private: T* vec_data; // we'll store the data as block of dynamically allocated // memory int length; // number of elements used int vec_size; // actual size of vec_data

MC00066

Page 13

Dinesh (521138580)
}; But when it comes to bools, you might not really want to do this because most systems are going to use 16 or 32 bits for each boolean type even though all that's required is a single bit. So we might make our boolean vector look a little bit different by representing the data as an array of integers whose bits we manually manipulate. (For more on manipulating bits directly, see bitwise operators and bit manipulations in C and C++.) To do this, we still need to specify that we're working with something akin to a template, but this time the list of template parameters will be empty: template <> class vector <bool> { // interface private: unsigned int *vector_data; int length; int size; }; Note that it would be perfectly reasonable if the specialized version of the vector class had a different interface (set of public methods) than the generic vector class--although they're both vector templates, they don't share any interface or any code. It's worth pointing out that the salient reason for the specialization 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. For instance, you might have a vector of doubles with a method that returns the noninteger component of each element although you might think prefer inheritance in this case. There isn't a particular reason to prevent the existence of a vector of doubles without those extra features. If, however, you felt strongly about the issue and wanted to prevent it, you could do so using template specialization. Another time when you might want to specialize certain templates could be if you have a template type that relies on some behavior that was not implemented in a collection of classes you'd like to store in that template. For example, if you had a templated sortedVector type that required the > operator to be defined, and a set of classes written by someone else that didn't include any overloaded operators but did include a function for comparison, you might specialize your template to handle these classes separately.

MC00066

Page 14

Dinesh (521138580)

MC00066

Page 15

Potrebbero piacerti anche