Concept of object oriented programming?
Java is an object oriented programming language. The main concepts used in Java are:
Class
Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members.
Object
A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.
Instance
One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behaviour that's defined in the object's class.
Method
An object's abilities. In language, methods (sometimes referred to as "functions") are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking.
Message passing
"The process by which an object sends data to another object or asks the other object to invoke a method." Also known to some programming languages as interfacing. For example, the object called Breeder may tell the Lassie object to sit by passing a "sit" message which invokes Lassie's "sit" method. The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java, code-level message passing corresponds to "method calling". Some dynamic languages use double-dispatch or multi-dispatch to find and pass messages.
Inheritance
"Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationship between an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the object named Lassie has the methods from both classes Collie and Dog.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well.
Abstraction
Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets.
Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.
Encapsulation
Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface - those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member.
Polymorphism
Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.
Decoupling
Decoupling allows for the separation of object interactions from classes and inheritance into distinct layers of abstraction. A common use of decoupling is to polymorphically decouple the encapsulation, which is the practice of using reusable code to prevent discrete code modules from interacting with each other. However, in practice decoupling often involves trade-offs with regard to which patterns of change to favor. The science of measuring these trade-offs in respect to actual change in an objective way is still in its infancy.
Note: Not all of the above concepts are to be found in all object-oriented programming languages, and so object-oriented programming that uses classes is called sometimes class-based programming. In particular, prototype-based programming does not typically use classes. As a result, a significantly different yet analogous terminology is used to define the concepts of object and instance.
How do you install Turbo C plus plus on Windows XP?
Borland Turbo C++ is a 16-bit DOS implementation of C++. As such it cannot be run natively on 32-bit architecture, including Windows XP. Emulation programs such as Dosbox can be used to emulate a virtual 16-bit environment, however you will need to install a slightly modified version of Turbo C++ that is capable of running within this environment.
What is a header node in c plus plus?
A header node, or head node, is a node that marks the start of a series of nodes, usually as part of a list or queue structure. The head node is often a sentinal that holds no data of its own. Sentinels are used to simplify algorithms by ensuring that a list can never be empty, even when it has no data.
What is issue in throwing an exception in a destructor?
If a destructor throws an exception, the instance is left in an invalid state. When an exception is thrown, the destructor automatically terminates at the point of the throw, unwinding the call stack until an exception handler is found (if one is provided). However, any resources yet to be released by the destructor, including all the instance's base classes, cannot be destroyed.
When writing your own destructors, it is important to never throw an exception. If an exception could be thrown from within your destructor, you must catch it and handle it within the same destructor -- you must not rethrow the exception.
There isn't one; C is strictly non object oriented. Although C++ is often considered to be an object-oriented extension for C (it was originally called C with Classes), it would be more accurate to describe them as siblings. The two have evolved separately and while they still retain a high-level of compatibility through their common ancestry, they are not the same language.
What is the difference between compilers and interpreters in c plus plus in tabular form?
C-compiler translates the C-source into Assembly or machine code.
On the other hand, C-interpreter -- well, there is no such thing as C-interpreter.
What is difference between define and typedef in c plus plus?
defines are handled by a preprocessor (a program run before the actual c compiler) which works like replace all in you editor. Typedef is handled by the c compiler itself, and is an actual definition of a new type. The distinction given between #define and typedef has one significant error: typedef does not in fact create a new type. According to Kernighan & Richie, the authors of the authoritative and universally acclaimed book, "The C Programming Language": It must be emphasized that a typedef declaration does not create a new type in any sense; it merely adds a new name for some existing type. Nor are there any new semantics: variables declared this way have exactly the same properties as variables whose declarations are spelled out explicitly. In effect, typedef is like #define, except that since it is interpreted by the compiler, it can cope with textual substitutions that are beyond the capabilities of the preprocessor. There are some more subtleties though. The type defined with a typedef is exactly like its counterpart as far as its type declaring power is concerned BUT it cannot be modified like its counterpart. For example, let's say you define a synonim for the int type with: typedef int MYINT Now you can declare an int variable either with int a; or MYINT a; But you cannot declare an unsigned int (using the unsigned modifier) with unsigned MYINT a; although unsigned int a; would be perfectly acceptable. typedefs can correctly encode pointer types.where as #DEFINES are just replacements done by the preprocessor. For example, # typedef char *String_t; # #define String_d char * # String_t s1, s2; String_d s3, s4; s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention. typedef also allows to delcare arrays, # typedef char char_arr[]; # char_arr my_arr = "Hello World!\n"; This is equal to
# char my_arr[] = "Hello World!\n"; This may lead to obfuscated code when used too much, but when used correctly it is extremely useful to make code more compat and easier to read.
How can you calculate the c program running time through c plus plus coding?
This is a big question... but I'll try for a shortish answer. Try to do things in approximately the following order.
1) Use the right algorithms. Look into the Big O efficiency of any algorithms you are using, and make sure there aren't more efficient algorithms available.
2) Think about trading using more memory for a faster algorithm. Perhaps pre-computing tables of intermediate results.
3) Use a profiler to see where the bottle necks are and try improving them.
4) Optimize the inner most loops using assembly language to get the last little bit faster.
5) Run it on a faster computer.
6) Make it run in parallel across many computers or CPUs. This is especially good on the newer Intel chips where you have access to multiple CPUs on one chip. Distributed network computing sometimes is a good idea. Cloud computing is another possibility these days.
7) Make sure that C really is the right answer. It might not be in all cases.
A more specific question might yield a more specific answer.
When do you make class virtual?
Whenever a derived class requires direct inheritance from a base class, even if it inherits that base class indirectly. That is, if V is a base class from which B is derived, and D is derived from B, then D inherits from V indirectly (through B). But if B is virtually derived from V, then D will inherit directly from V.
This feature is commonly used in conjunction with multiple inheritance. Examine the following declarations:
class V{};
class B1: public V{};
class B2: public V{};
class M: public B1, public B2{};
Now suppose you have the following code:
M m; // Declare an instance of M.
V& v = m; // Ambiguous...
The problem with this is that M inherits V from both B1 and B2, and therefore inherits two separate instances of V. The compiler is unable to determine which instance of V you want to refer to. One solution to this would be to use static casts to indirectly refer to an explicit instance of V:
V& v = static_cast<B1&>(m);
or
V& v = static_cast<B2&>(m);
While this is certainly workable, it is an ugly approach that places far too much responsibility upon the programmer to ensure the correct instance of V is being referred to. However, unless there is a specific need to have two instances of V within M, the problem can be resolved with virtual inheritance.
By virtually deriving both B1 and B2 from V, M will directly inherit just one instance of V, which is then shared, virtually, between B1 and B2:
class V{};
class B1: public virtual V{};
class B2: public virtual V{};
class M: public B1, public B2{};
M m;
V& v = m; // No ambiguity.
Now M can access all the members of V directly, as can B1 and B2, because they now share the same instance of V.
Note that it doesn't matter whether the virtual keyword is placed before or after the access specifier (which is public in this case). "virtual public" and "public virtual" have the same meaning.
Write a program using c plus plus to whether the given square matrix is symmetric or not?
int sym_test (const int **a, int n) {
int i, j, sym;
i=1, j=0, sym=1;
while (sym && i
else if (j
}
return sym;
}
What is single inheritance in c plus plus?
Multiple inheritance occurs when a class is derived directly from two or more base classes.
class b1 {};
class b2 {};
class d: public b1, public b2 {}; // multiple inheritance class
Write a c plus plus programs for stack using arrays?
//Program on Stack ADT Using Arrays
#include<iostream.h>
#include<conio.h>
#define maxSize 10
#include<stdlib.h>
class stack
{
public:
stack(); // constructor call the display function
void pop(); //used to pop the value as per user demand
void push(); //used for push the value as per user demand
int empty(); //used to check the stack
int full(); //used to check the stack whether it is full as max limit is 80
void display(); //used to display menu for operations
void stackDisplay(); //used to display whole stack items
void operation(); //used to enter the user choice
private:
int top;
int item[maxSize];
};
stack::stack()
{
top = 0;
display();
}
void stack :: display()
{
cout << "STACK MAIN MENU GIVEN BELOW" << endl;
cout << "PRESS 1 FOR PUSH THE ITEM ON STACK" << endl;
cout << "PRESS 2 FOR POP THE ITEM ON STACK" << endl;
cout << "PRESS 3 FOR DISPLAY THE WHOLE STACK" << endl;
cout << "PRESS 4 FOR EXIT THE PROGRAM" << endl;
cout<<"ENTER YOUR CHOICE" << endl;
operation();
}
void stack :: operation()
{
int choice;
cin >> choice;
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
stackDisplay();
break;
case 4:
exit(4);
default:
cout << "PLZ ENTER VALID NUMBER" <<endl;
operation();
}
}
int stack::empty()
{
if( top 0)
{
cout<<"THE STACK IS EMPTY UNDERFLOW" << endl;
cin.get();
}
else
{
char ch;
cout<<"AS THE LAST ELEMENT IN STACK IS "<<item[top] << endl;
top = top-1;
cout<<"WANT TO POP OUT ANOTHER ELEMENT y/n" << endl;
cin>>ch;
if(ch=='y')
pop();
cin.get();
}
cout<<"PRESS ENTER TO GO TO MAIN MENU " << endl;
cin.get();
clrscr();
display();
}
void stack::stackDisplay()
{
cout<<"THE ELEMENTS IN STACK IS"<<endl;
for(int i = 1;i <= top; i++)
{
cout << item[i] << endl;
}
cin.get();
cout<<"PRESS ENTER FOR MAIN MENU " << endl;
cin.get();
clrscr();
display();
}
void main()
{
clrscr();
gotoxy(15,10);
cout<<"WELCOME TO THE PROGRAM OF STACK MADE BY SAURABH " << endl;
gotoxy(15,11);
cout<<"________________________________________________" << endl;
cin.get();
clrscr();
stack obj;
getch();
}
BY. SAURABH (GNDU RC JAL CSE 2nd YEAR)
Write a c program to print fibonacci series using do while loop?
#include<iostream>
using namespace std;
#define MIN 1
#define MAX 1000000
int main()
{
int num;
char c;
do
{
cout << "Enter a number from " << MIN << "-" << MAX << " (0 to quit): ";
cin >> num;
while(cin.fail() num < 0 num > MAX)
{
if( cin.fail() )
{
cin.clear();
cin >> c;
}
cout << "Invalid number, try again: ";
cin >> num;
}
if(num)
{
cout << "\nFibbonacci series for n, where 1 <= n <= " << num << ":\n\n";
int n = 1, x = 0, y = 0;
do
{
cout << n;
x = y;
y = n;
n = x + y;
if( n < num )
cout << ", ";
}while( n < num );
cout << endl << endl;
}
}while( num );
return( 0 );
}
Why is a destructor function required in C plus plus classes?
A destructor is not a function per-se. Functions have returns values but destructors do not (not even void). However, other than the lack of a return value, a destructor's body is no different to a function body.
Contrary to belief, destructors are not required by every class of object. Destructors are only required when we need to explicitly release a resource when an object of the class falls from scope, but not all resources need to be released explicitly. Consider the following class:
struct point {
int x, y;
};
This class does not require a destructor because it is self-contained. That is, all the resources consumed by an object of the class are contained within the object itself, thus when the object falls from scope, the memory it consumed is automatically released. There is nothing to destroy.
Now consider the following class:
class my_vector {
std::vector<int> v;
};
Again, this class requires no destructor. When objects of this class fall from scope, the vector's destructor is invoked, releasing its resources. Thus the only resource consumed by this class is the vector itself, and that's self-contained by the class.
Now let's consider a class that does require a destructor:
template<typename T>
class smart_pointer {
T* ptr;
// ...
};
Here, we have a class that encapsulates a "naked" pointer variable of some type T. That pointer could feasibly refer to any object of type T in memory. However, being a "smart pointer", the assumption is that objects of this class will "own" the memory they refer to. As the owner, it makes sense to yield ownership whenever object's of the class fall from scope. If we didn't provide a destructor, ptr would fall from scope, but the memory it referred to would not. So to ensure the memory is released, we must explicitly release it via the class destructor:
template<typename T> class smart_pointer {
T* ptr;
// ...
public:
~smart_pointer () { delete ptr; }
};
To summarise: a destructor is only required when an object acquires a non-shared resource that is not released automatically when objects of the class fall from scope. A vector is a resource handle, so when it falls from scope, its resources are released automatically. Similarly with smart pointers. However a "naked" pointer is not a resource handle, so if our class "owns" a resource by holding a pointer to it, then we must release that pointer when objects of the class are destroyed. Resources cover many things besides raw memory. If we hold a reference to an open file, it would be prudent to close the file before the reference falls from scope. With a resource handle we get that assurance. Thus if we use resource handles rather than "raw" resources, then we need never write any destructors.
There can be other reasons to require a destructor besides resource management, such as to write an entry in a log file upon destruction, however resource management and other "housekeeping" task are not a requirement of every class thus a destructor is not required by every class.
Why objects are not used to acces the static class members?
Static members are members of the class, not an instance of the class.
All instances of a class have access to all their static members. Derived classes have access to both protected and public statics, while public statics are fully accessible.
Think of static members as being global variables or functions, but scoped to the class rather than being globally accessible (and therefore publicly accessible).
Consider the following example. A private static member variable, count, is declared. Note that it must be initialised immediately after the class declaration, but outside of a code block. Were it declared public it could be initialised in a code block, but the class needs to maintain control over it, thus it is completely hidden from all outside influence.
The two constructors increment count while the destructor decrements count. Thus count maintains a running total of all the instances of the class (much like a reference counter). Note that all instances of the class have direct access to the static member. Note also that if other parametrised constructors are declared, each must increment countindependently.
The public static accessor method, GetCount(), returns the current value of count (returning by value, not by reference). There is no equivalent set mutator, thus countis a read-only variable -- it cannot be altered from outside of the class.
#include
class MyClass{
public:
MyClass(){ ++count; }
MyClass(const MyClass & copy){ ++count; }
~MyClass(){ --count; }
public:
static unsigned int GetCount(){ return( count ); }
private:
static unsigned int count;
};
// Initialise the static member:
unsigned int MyClass::count = 0;
void PrintCount()
{
printf( "There %s currently %u instance%s of MyClass.\n",
MyClass::GetCount() 1 ? "" : "s" );
}
int main()
{
MyClass * myClass[10];
// At this point there are no instances.
PrintCount();
printf( "\nCreating instances of MyClass...\n" );
for( int i=0; i<10; ++i )
{
myClass[i] = new MyClass();
PrintCount();
}
printf( "\nDestroying instances of MyClass...\n" );
for( int i=0; i<10; ++i )
{
delete( myClass[i] );
PrintCount();
}
return( 0 );
}
How do you compile and run C programs on the Macintosh?
The first step is to install the XCode developer tools that comes with OSX. You can do this by looking on your OSX install disc. There should be a folder for optional installs, and a package for XCode. This will automatically install gcc, a C compiler, on your machine. Next, find the Console in the Utilities folder. It opens a UNIX shell. Move to the directory that your c file is in (you can find more information about UNIX elsewhere if you need to). Let's say your C file is named myfile.c. To compile it, type: gcc myfile.c This will compile your program, and name the compiled program a.out. To run it, type: ./a.out I hope that helps. Brina
Who invented c plus plus and when?
C++ was originally called 'C With Classes' in 1978, and was renamed by its developer, Bjarne Stroustrup, in 1983. The new name literally meant 'the successor to C', although it should really have been called ++C (prefix increment) rather than C++ (postfix increment), since the former returns C+1 (the successor to C), while the latter returns C.
Write a c plus plus program of array to pointers?
#include
void
printarr(int
a[]);
void
printdetail(int
a[]);
main()
{
int
a[5];
for
(int
i = 0;i<5;i++)
{
a[i]=i;
}
printdetail(a);
}
void
printarr(int
a[])
{
for
(int
i = 0;i<5;i++)
{
printf("value in array %d\n"
,a[i]);
}
}
void
printdetail(int
a[])
{
for
(int
i = 0;i<5;i++)
{
printf("value in array %d and address is %8u\n"
,a[i],&a[i]);
}
}
void
print_usingptr(int
a[])
{
int
*b;
Explain term composition with example in c plus plus?
Composition relates to the way in which complex objects can be constructed from smaller, simpler objects. We refer to this as object composition. While simple objects typically contain one or more embedded primitive member attributes, such as int, char, float and so on, composite objects typically embed other objects (often in addition to other primitive attributes), and each of those objects may themselves be composite or they may be simple. This allows highly complex object models to be constructed such that each object within a composition is self-contained and ultimately operates no differently to how it would operate if it were a standalone object. The composite object effectively acts as an object coordinator, calling specific methods upon the simpler objects as required. In other words, the actual workload is delegated to the object or objects that are actually responsible for that workload, and they themselves may delegate to simpler objects, and they to theirs. The composite object's only real workload is in processing any relevant results of those delegations. In other words, a simple function call through a member method of the composite object can produce a cascade of member methods within the embedded objects, each of which works completely independently, but the results of which can be combined by the containing object in order to produce highly complex behaviour.
By way of an example, a motor car is built up from thousands of individual but ultimately simple components, such as nuts and bolts, switches, cogs, levers, wheels and so on. Some of those simple objects are combined to produce more complex objects, such as an engine, a transmission unit, a steering mechanism, door locks, and so, on. Ultimately, they all combine to produce a car. But no matter how complex a composite object is, the behaviour of their embedded objects does not change: a nut and bolt is still a nut and bolt whether it is holding a door hinge onto a chassis, or a suspension strut to a wheel hub. In other words, the job of physically holding one component to another is delegated to the nut and bolt, but is coordinated according to the object that embeds the nut and bolt, while that object is coordinated and delegated to by the object that contains it, and so on.
Selection Sort Program in c and c plus plus?
The following code demonstrates the implementations for bubble sort, insertion sort and selection sort, in C++.
#include<iostream>
#include<time.h>
#include<iomanip>
#include<string>
void swap(int& x, int& y)
{
x^=y^=x^=y;
}
void bubble_sort(int* A, int size)
{
while(size)
{
int n=0;
for(int i=1; i<size; ++i)
{
if(A[i-1]>A[i])
{
swap(A[i-1], A[i]);
n=i;
}
}
size=n;
}
}
void insertion_sort(int* A, int size)
{
for(int i=1; i<size; ++i)
{
int value=A[i];
int hole=i;
while( hole && value<A[hole-1] )
{
A[hole]=A[hole-1];
--hole;
}
A[hole]=value;
}
}
void selection_sort(int* A, int size)
{
for(int i=0; i<size-1; ++i)
{
int j=i;
for(int k=i+1; k<size; ++k)
if(A[k]<A[j])
j=k;
if( i!=j )
swap(A[i],A[j]);
}
}
void sort(int* A, int size, int sort_type)
{
switch(sort_type)
{
case(0): bubble_sort( A, size );
case(1): insertion_sort( A, size );
case(2): selection_sort( A, size );
}
}
int* copy_array(int* A, int size)
{
int* copy=new int[size];
memcpy(copy, A, size*sizeof(int));
return(copy);
}
void print_array(int* A, int size, char* prompt)
{
std::cout<<prompt<<"\t";
for(int i=0; i<size; ++i)
std::cout<<std::setw(2)<<A[i]<<" ";
std::cout<<std::endl;
}
int get_rand(int range_min=0, int range_max=RAND_MAX)
{
return((int) ((double)rand() / (RAND_MAX + 1) * ((range_max + 1) - range_min) + range_min));
}
int input_char(std::string prompt, std::string input)
{
char ch;
do
{
std::cout<<prompt<<": ";
std::cin>>ch;
}
while(input.find(ch)==std::string::npos);
return(input.find(ch)%(input.size()/2));
}
int main()
{
srand((unsigned) time(NULL));
int size = get_rand( 10, 80);
if( int* A = new int[size] )
{
for( int i=0; i<size; ++i )
A[i]=get_rand( 1, size );
int choice=input_char("Please select a sorting method:\n[B]ubble, [I]nsert, [S]election", "bisBIS");
std::cout<<"You chose ";
switch(choice)
{
case(0): std::cout<<"bubble"; break;
case(1): std::cout<<"insertion"; break;
case(2): std::cout<<"selection"; break;
}
std::cout<<" sort...\n"<<std::endl;
print_array( A, size, "Before sorting" );
sort(A, size, choice);
print_array( A, size, "After sorting" );
delete [] A;
}
return(0);
}
Why does C plus plus allows static binding and not dynamic binding?
Dynamic binding, or late binding, is when the object code for the class does not get loaded into memory until it is needed. This saves time at module load time, at the cost of delayed execution for the first invocation.
In c plus plus Who tells the compiler that a specific class will be declared later in the program?
A forward declaration. However forward declarations can only be used when the class is used as a pointer or reference prior to its definition, otherwise it must be defined before it is used.
class A; // forward declaration
class B {
A& data; // reference to class that has yet to be defined
};
class A {}; // definition
Data structure is important since it dictates the types of operations we can perform on the data and how efficiently they can be carried out. It also dictates how dynamic we can be in dealing with our data; for example it dictates if we can add additional data on the fly or if we need to know about all of the data up front. We determine which data structures to use to store our data only after we've carefully analyzed the problem and know at least what it is we hope to do with the data; for example if we'll require random access, or sequential access, or the ability to move both forward and backward through the data.
What is the if-else statement in c plus plus programming language?
The if-then-else inline command is shown below:
returnvalue = (condition) ? (truePart) : (falsePart);
-----------
According to the C standard, this command does exist in the C coding language in the same way as it exists in C++ and comparable languages.
http://users.ece.cmu.edu/~eno/coding/CCodingStandard.html
What is the difference between function prototyping and function overloading?
Function prototypes determine the return type, the name of the function, the argument types expected by the function, and the arity of the function. Function prototyping is used to separate interface from implementation. In C++ all functions must be declared before they are called, thus we use prototypes to provide forward declarations for those functions that have yet to be defined/implemented. We can also use forward declarations for incomplete types such as template functions and classes, however the definition/implementation must be visible to compiler before the function or class is used. In these cases the definitions are typically placed in the same header as the declarations.
It is important to note that a definition is also a declaration, and therefore both are also prototypes. The only real difference is that prototypes do not require names for the formal arguments. Even if you provide argument names in your prototypes, they will be ignored by the compiler. The argument names within the definition are the only names of any relevance.
Function overloading is where two or more functions share the same name within the same namespace, but have different signatures. The signature of a function is essentially the same as its prototype but excludes the return type, thus overloads cannot differ by return type alone. The compiler uses the function signature to differentiate between your overloads.
All function signatures within a namespace must be unambiguous, thus you cannot have two functions with the same name and arguments that are co-variant. For example, the following overloads are invalid because a size_t type is co-variant with unsigned int type, thus the compiler cannot differentiate them.
unsigned int max(unsigned int, unsigned int);
size_t max(size_t, size_t);