Sie sind auf Seite 1von 8

1. Difference Between Structures in C and Classes in C++. What is the difference between class and structure?

Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

2. When You will make a Function As INLINE and How it differs from Macros?. C++ Inline Functions In this C++ tutorial, you will learn about Inline function, what is inline function, reason for the need of inline function, what happens when an inline function is written, general format of inline function explained with example. What is Inline Function? Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program. Reason for the need of Inline Function: Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call. These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called. This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called. The extra time needed and the process of saving is valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed. This type of function is best handled by the inline function. In this situation, the programmer may be wondering why not write the short code repeatedly inside the program wherever needed instead of going for inline function? Although this could accomplish the task, the problem lies in the loss of clarity of the program. If the programmer repeats the same code many times, there will be a loss of clarity in the program. The alternative approach is to allow inline functions to achieve the same purpose, with the concept of functions. What happens when an inline function is written? The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. The function is placed separately as inline function, thus adding readability to the source program. When the program is compiled, the code present in function body is replaced in the place of function call. General Format of inline Function: The general format of inline function is as follows: inline datatype function_name(arguments) The keyword inline specified in the above example, designates the function as inline function. For example, if a programmer wishes to have a function named exforsys with return value as integer and with no arguments as inline it is written as follows: inline int exforsys( )

Example: The concept of inline functions:

#include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ; cin>>x; cout<<\n The Output is: << exforsys(x); } inline int exforsys(int x1)

{ return 5*x1; }

The output of the above program is: Enter The Output is: 50 the Input Value: 10

The output would be the same even when the inline function is written solely as a function. The concept, however, is different. When the program is compiled, the code present in the inline function exforsys( ) is replaced in the place of function call in the calling program. The concept of inline function is used in this example because the function is a small line of code. The above example, when compiled, would have the structure as follows:

#include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ; cin>>x; //The exforsys(x) gets replaced with code return 5*x1; cout<<\n The Output is: << exforsys(x); }

When the above program is written as normal function the compiled code would look like below:

#include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ; cin>>x; //Call is made to the function exforsys cout<<\n The Output is: << exforsys(x); } int exforsys(int x1) { return 5*x1; }

A programmer must make wise choices when to use inline functions. Inline functions will save time and are useful if the function is very small. If the function is large, use of inline functions must be avoided. Inline Functions versus Macros Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:

Inline functions follow all the protocols of type safety enforced on normal functions. Inline functions are specified using the same syntax as any other function except that they include the inline keyword
in the function declaration.

Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as
arguments to macros can be evaluated more than once. Example The following example shows a macro that converts lowercase letters to uppercase: Copy // inline_functions_macro.c #include <stdio.h> #include <conio.h> #define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a)) int main() { char ch; printf_s("Enter a character: "); ch = toupper( getc(stdin) ); printf_s( "%c", ch ); } Sample Input: xyz Sample Output: Z The intent of the expression toupper(getc(stdin)) is that a character should be read from the console device (stdin) and, if necessary, converted to uppercase. Because of the implementation of the macro, getc is executed once to determine whether the character is greater than or equal to "a," and once to determine whether it is less than or equal to "z." If it is in that range, getc is executed again to convert the character to uppercase. This means the program waits for two or three characters when, ideally, it should wait for only one. Inline functions remedy the problem previously described: Copy // inline_functions_inline.cpp #include <stdio.h> #include <conio.h> inline char toupper( char a ) { return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a ); } int main() { printf_s("Enter a character: "); char ch = toupper( getc(stdin) ); printf_s( "%c", ch ); } Sample Input: a Sample Output: A 3. What is Friend Function? and What are the Merits and Demerits of Using it? What is a Friend Function? A friend function is a special function in c++ which inspite of not being member fuction of a class has privilege to access private and protected data of a class. A friend function is a non member function of a class, that is declared as a friend using the keyword "friend" inside the class. By declaring a function as a friend, all the access permissions are given to the function. A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. Need for Friend Function:

As discussed in the earlier sections on access specifiers, when a data is declared as private inside a class, then it is not accessible from outside the class. A function that is not a member or an external class will not be able to access the private data. A programmer may have a situation where he or she would need to access private data from non-member functions and external classes. For handling such cases, the concept of Friend functions is a useful tool. How to define and use Friend Function in C++: The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument. Some important points to note while using friend functions in C++: * The keyword friend is placed only in the function declaration of the friend function and not in the function definition. . * It is possible to declare a function as friend in any number of classes. . * When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend. . * A friend function, even though it is not a member function, would have the rights to access the private members of the class. . * It is possible to declare the friend function as either private or public. . * The function can be invoked without the use of an object. The friend function has its argument as objects, seen in example below. properties of friend function: 1. if a function to be made friend of a class than it should be declared within body of the class priciding with keyword friend. 2.freind function never breaks the security. 3.it should not be defined in name of class nor scope resolution operator is used in it's defination even the keyword freind is also not used while defining friend function. 4.when friend function is called nither name of object nor dot operator is used. however it may accept the object as argument who's value it want's to access. 5.it doen't matter in which section of the class we have declared a freind function. Example to understand the friend function: #include class exforsys { private: int a,b; public: void test() { a=100; b=200; } friend int compute(exforsys e1) //Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it }; int compute(exforsys e1) { //Friend Function Definition which has access to private data return int(e1.a+e2.b)-5; } main() {

exforsys e; e.test(); cout<<"The result is:"< //Calling of Friend Function with object as argument. } The output of the above program is The result is:295 The function compute() is a non-member function of the class exforsys. In order to make this function have access to the private data a and b of class exforsys , it is created as a friend function for the class exforsys. As a first step, the function compute() is declared as friend in the class exforsys as: friend int compute (exforsys e1) disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend, the friend function should call a hidden (usually protected:) virtual[20] member function. 4. Program

Banking Application in C++ Program ing m

5. Distinguish Between the Following 2 Statements : Time T2(T1), Time T2=T1 ; T1, T2 are Objects of Time

Class. * The First Statement : Time T2(T1), Creates the object itself from other object using Copy Constructor. * The Second Statement : Time T2=T1, Creates the object using Default Constructor and then calls the Assignment Operator (=) to Assign T1 to T2. 6. Whether a Friend Function Can't be used to Overload the Assignment Operator "=", Explain Why?
The language requires operator= to be a member. Because if it isn't declared by the user in the class definition, the compiler declares one automatically. If the operation modifies the state of the class object which it operates on, then it must be a member function, not a friend function. Thus all operators such as =, *=, +=, are naturally defined as member functions and not as friend functions. Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, then it does not have to be a member function. This is the reason why binary operators are often implemented asfriend functions sunch as + , *, -. 7. Program

Education System in C++ Program ing m

8. What is the Virtual Function. Why we need it? When do we make a virtual function Pure? C++ Virtual Functions What are Virtual Functions? Virtual, as the name implies, is something that exists in effect but not in reality. The concept of virtual function is the same as a function, but it does not really exist although it appears in needed places in a program. The object-oriented programming language C++ implements the concept of virtual function as a simple member function, like all member functions of the class.

The functionality of virtual functions can be over-ridden in its derived classes. The programmer must pay attention not to confuse this concept with function overloading. Function overloading is a different concept and will be explained in later sections of this tutorial. Virtual function is a mechanism to implement the concept of polymorphism (the ability to give different meanings to one function). Need for Virtual Function: The vital reason for having a virtual function is to implement a different functionality in the derived class. For example: a Make function in a class Vehicle may have to make a Vehicle with red color. A class called FourWheeler, derived or inherited from Vehicle, may have to use a blue background and 4 tires as wheels. For this scenario, the Make function for FourWheeler should now have a different functionality from the one at the class called Vehicle. This concept is called Virtual Function. Properties of Virtual Functions: Dynamic Binding Property: Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple member functions. The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during runtime or dynamic binding Virtual functions are member functions of a class. Virtual functions are declared with the keyword virtual, detailed in an example below. Virtual function takes a different functionality in the derived class. Declaration of Virtual Function: Virtual functions are member functions declared with the keyword virtual. For example, the general syntax to declare a Virtual Function uses: class classname //This denotes the base class of C++ virtual function { public: virtual void memberfunctionname() //This denotes the C++ virtual function { ............. ............ } }; To achieve the concept of dynamic binding in C++, the compiler creates a v-table each time a virtual function is declared. This v-table contains classes and pointers to the functions from each of the objects of the derived class. This is used by the compiler whenever a virtual function is needed. When do we make pure? Purpose of a Pure Virtual Function is to make a Class to Abstract Class. Often in a design, you want the base class to present only an interface for its derived classes. That is, you dont want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. This is accomplished by making that class abstract, which happens if you give it at least one pure virtual function. You can recognize a pure virtual function because it uses the virtual keyword and is followed by = 0. If anyone tries to make an object of an abstract class, the compiler prevents them. This is a tool that allows you to enforce a particular design. When an abstract class is inherited, all pure virtual functions must be implemented, or the inherited class becomes abstract as well. Creating a pure virtual function allows you to put a member function in an interface without being forced to provide a possibly meaningless body of code for that member function. At the same time, a pure virtual function forces inherited classes to provide a definition for it. 9. What are the steps involved in using a file in a c++ program and describe the various classes available

for file operation.


Steps involved: Open the file, read/write/save data, close the file
Syntax Declaration:

ifstream inFile; // object for reading from a file ofstream outFile; // object for writing to a file

Details of some useful classes : filebuf Its purpose is to set the file buffer to read and write. Contains openprot constant used in the open() of the filestream classes. Also contains close() and open() as member functions. fstreambase Provides operations common to the file streams. Serves as a base for fstream, ifstream and ofstream classes. Contains open() and close() functions. ifstream Provides input operations. Contains open() with default input mode. Inherits the functions get(), getline(), read(), seekg() and tellg() functions from istream. ofstream Provides output operations. Contains open() with default output mode. Inherits put(), seekp(), tellp(), and write() functions from ostream. fstream Provides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream. 10. Life Cycle of A Thread When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesnt mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed. Different states of a thread are :

New state After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. Running state A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. Different states implementing Multiple-Threads are:

As we have seen different states that may be occur with the single thread. A running thread can enter to any non-runnable state, depending on the circumstances. A thread cannot enters directly to the running state from non-runnable state, firstly it goes to runnable state. Now lets understand the some non-runnable states which may be occur handling the multithreads. Sleeping On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread. static void sleep(long millisecond) throws InterruptedException Waiting for Notification A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread. final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException Blocked on I/O The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources. Blocked for joint completion The thread can come on this state because of waiting the completion of another thread. Blocked for lock acquisition The thread can come on this state because of waiting to acquire the lock of an object. Methods that can be applied apply on a Thread: Some Important Methods defined in java.lang.Thread are shown in the table: Method Return Type Description currentThread( ) Thread Returns an object reference to the thread in which it is invoked. getName( ) String Retrieve the name of the thread object or instance. start( ) void Start the thread by calling its run method. This method is the entry point to execute thread, like the main method for run( ) void applications. sleep( ) void Suspends a thread for a specified amount of time (in milliseconds). isAlive( ) boolean This method is used to determine the thread is running or not. This method returns the number of active threads in a particular thread group activeCount( ) int and all its subgroups. interrupt( ) void The method interrupt the threads on which it is invoked. By invoking this method the current thread pause its execution temporarily and yield( ) void allow other threads to execute. This method and join(long millisec) Throws InterruptedException. These two join( ) void methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.

Das könnte Ihnen auch gefallen