answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

What are the advantages of using string in c plus plus?

I assume you mean std::string rather than strings in general. Programs that need to convey any information to the user will usually require many strings, and when retreiving input from the user, a string (in conjunction with a string stream) are the best way of checking that data before processing it. The std::string (and its wide-character counterpart, std::wstring) needn't be used for all strings, of course, but they are much easier to work with when strings need additional processing, such as when concatenating strings, or searching within strings. And if you need more functionality than is provided by std::string alone, you can always derive a new string object from std::string and embelish it as required. Of course, if you require less functionality than is provided by std::string then you have the option of creating your own lightweight string class from scratch. However, for most applications, std::string is lightweight enough, and if you use std::string at all, then there's little point in writing your own string class. Aside from re-inventing the wheel (one of the reasons the STL exists), it's only going to increase your code size. However, for new programmers, it can be an interesting excercise creating your own string class, if only to show how std::string works and why re-inventing wheels is rarely a good thing.

Why did c plus plus become more popular inspite of so many object oriented languages available?

All languages are interesting to some degree or another. Programming languages in particular allow us humans to communicate with and ultimately control computers, bending them to our will. However, some languages are better than others for certain tasks. C++ is a general purpose, cross-platform, high-level language that can produce highly-efficient machine code (the native language of the computer). What makes it interesting is subjective -- each programmer will have their own likes and dislikes -- but ultimately the language gives a high-degree of control over the hardware, exploiting specific features of the architecture.

The same kind of thing can be achieved using Assembly Language (a low-level language), and in many ways would be regarded as a more interesting language than C++. But it is extremely difficult to work with. Even if you have access to a vast library of pre-written routines, you still require intimate knowledge of the underlying hardware and must write programs in minute detail. C++ can achieve similar results, but the abstraction between the hardware and the code you write is such that you needn't concern yourself with the hardware quite so much. That is, a single instruction in C++ can easily generate dozens of assembly instructions.

C++ becomes more interesting when compared to languages that don;t provide the level of control, such as Java. This is an entirely object-oriented programming language, with a higher-degree of abstraction (with little or no interaction with the underlying architecture). Rather than producing machine code, Java produces byte code which can be run on any platform that supports the Java Virtual Machine. As such, it is more portable as programs need only be compiled once to run on any platform whereas C++ code must be compiled separately for each platform, and must include code to filter out code that is irrelevant to the current platform. However, since Java programs must run in a virtual machine, they are very much slower than equivalent C++ programs.

C++ is also more interesting in that you aren't restricted to using object-oriented programming principals. You can choose to mix C++ code with C-style code (which is a structured language) and also raw assembly routines, thus making it far more flexible than Java, which is entirely object-oriented.

Although there's little you can't do in C++, that doesn't make it the best language in every situation. For instance, if you have a deadline to meet, C++ might be too complex a language to meet that deadline, thus forcing you to use a more abstract language designed specifically for rapid application development (RAD). For instance, it's often useful to model algorithms and design concepts using a RAD before committing yourself to a more lengthy software development in C++. The feedback from the RAD can, in fact, reduce the overall development cycle as the models can often be incorporated into the final design with only minimal or trivial modification.

However, C++ comes into its own when high-performance is the main criteria, and raw Assembly Language would be far too costly to implement in a reasonable time-frame. Modern compilers can optimise the machine code in much the same way an Assembly Language programmer exploits hardware features to produce highly-efficient code, but there's often room for further improvement. However, C++ is flexible enough to allow the programmer to make these adjustments by hand. And, for me, that's where things can get really interesting.

What does c plus plus use call by value or call by reference?

When we call a function in C++ by passing the values as arguments, it is called call by value.

e.g

#include<iostream.h>

#include<conio.h>

int add(int,int);

int main()

{

int a,b,c;

cout<<"Enter numbers.";

cin>>a>>b;

c=add(a,b);

cout<<"Sum : "<<c;

return 0;

}

int add(int a,int b)

{

int c;

c=a+b;

return c;

}

What are the drawbacks of function overloading?

None whatsoever. There is always the chance you will end up creating overloaded functions that are never used, but your compiler should be able to eliminate these for you (unreachable code). Otherwise there is no harm in having them in your source code, especially if the code is intended to be re-usable. For those that are functionally the same, the only difference being the type of parameter, template functions are a far better solution to overloading for every conceivable type. The compiler will generate the overloads for you, on an as-required basis, and you only have the one function to maintain.

What is the problem of an array based queue?

A queue is a first-in, first-out (FIFO) structure. This means insertions occur at the end of the data sequence while extractions occur at the beginning of the sequence. Array-based queues are problematic for two reasons.

Inserting at the end of a sequence is fine when there are unused elements available (which you must keep track of), but when the queue is full the array must be resized in order to free up more unused elements. If there is insufficient memory to expand into the entire array must be reallocated to new memory which means the entire array must be copied. Copying arrays is an expensive operation as every element must be copied individually. An array of pointers (or resource handles with move semantics) rather than an array of objects would improve efficiency but for the duration of the copy process you will be consuming more than twice as much memory; one block for the original queue and another larger block for the new allocation.

However, the biggest problem is what to do when elements are extracted from the front. This will mean you have an unused element at the beginning of the array and the only way to eliminate it is by shunting all elements forward by one and that means copying them (again, pointers or resource handles would be more efficient). A better approach is to use a circular array such that you keep track of the unused elements at both the beginning and end of the sequence.

What are the various data types in C plus plus?

Data types specify how data is interpreted. All data in a binary computer is stored as a sequence of bits (binary digits), thus all data is represented by numeric values. The data type associated with that data determines how many bits the data occupies and how that data should be interpreted. For instance, an unsigned char data type occupies 8 bits (1 byte) which translate to a numeric value in the range 0 to 255. These values map to ASCII character codes in the current code page, thus if you were to output a char data type it would print the character associated with the character code rather than the numeric value of the code. Unicode character codes use 16 bits (2 bytes) to represent each character and are therefore unsigned short types, also known as wchar_t types.

The primitive data types include int, short and char, which are all integral data types used to store integers (whole numbers). Each may be further qualified with the signed or unsigned keywords, thus a signed char will represent values in the range -128 to +127.

Strings of characters are represented as an array of char types, typically terminated by a null character which has the value 0. Arrays are simply sequence containers containing one or more data elements of the same type. Since the length of each element is the same, it is trivial to locate any element within the array given the element's index where the first element can be found at index 0. Thus an array of n elements will have indices in the range 0 to n-1. Knowing the size of each element (as determined by its type) means that element x can be found at the memory address x*sizeof(element) bytes from the start of the array, using nothing more than simple pointer arithmetic. However, when you declare an array, the subscript operator can be used to specify the index of the element you wish to examine, while C++ does the pointer arithmetic in the background.

More complex data types can be declared using class or struct keywords. The declaration of these types determines how they are mapped in memory and ultimately how they are interpreted. Primitive data types act as the building blocks for these complex data types, but more complex data types can be composed from any combination of primitive and pre-existing complex data types to produce ever more highly complex data types.

Instances of a type are known as variables or constants, depending on whether the value of the instance can be changed or not. If the type is a complex data type, such as a class or struct, the instance is known as an object, which can also be variable or constant. Many new users regard classes and objects as being the same thing, however a class is the definition of a type while an object is an instance of the type, in the same way that a char is a type while a char variable is an instance of the type.

How do you write a c function to swap two variables without using a temporary variable?

You can swap values a and b without a temporary as follows:

a=a^b

b=a^b

a=a^b

(^ is the bitwise XOR operator)

To show how this works, let's consider the values a=180 and b=204. In binary, 180 is 10110100 while 204 is 11001100. Thus:

a = 10110100

b = 11001100

a^b means that we look at the corresponding bits in each input value and output a 1 if one and only one of the two input bits is set. Thus the output (o) is:

a = 10110100

b = 11001100

o = 01111000

In the expression a=a^b, the output of a^b is assigned to a, thus the values of a and b now look like this:

a = 01111000

b = 11001100

We then repeat the operation, a^b, this time assigning the output to b:

a = 01111000

b = 11001100

o = 10110100

So now we have:

a = 01111000

b = 10110100

We repeat the operation one more time, assigning the output value to a:

a = 01111000

b = 10110100

0 = 11001100

So now we have:

a = 11001100

b = 10110100

The two values have now been swapped.

To write this in C, we can use shorthand expressions using the compound XOR-ASSIGN operator (^=):

a^=b

b^=a

a^=b

These individual expressions can then be combined into a single expression:

a^=b^=a^=b

Finally, to use this expression in a C function, we need to pass a and b by reference (using pointer variables):

void swap (int* a, int* b) {

(*a)^=(*b)^=(*a)^=(*b);

}

Note that a and b must be of an integral type (char, short, long, int, unsigned, etc). The example above only works on type int. If we wish to swap other types, or more complex types, we must treat those values as if they were an integral type. One way to achieve this is to treat those types as if they were an array of type char, supplying the length of the arrays through a separate argument:

void swap (char* a, char* b, size_t size) {

for (int i=0; i<size; ++i) {

a[i]^=b[i]^=a[i]^=b[i];

}

}

For example, to swap two doubles, we can use the following call:

int main (void) {

double a, b;

a = 3.14;

b = 1.1;

swap ((char*) &a, (char*) &b, sizeof (double));

assert (a==1.1);

assert (b==3.14);

return 0;

}

Note that a and b must of the same type.

What is a pure virtual member function in c plus plus?

Functions in C++ are separate procedures or subroutines within a program, that can be called as often as required and which can return values back to their callers. That is, when you make a function call, execution passes to the function and then returns to the caller.

Functions that are class members are also known as member functions, member methods, or simply methods. These work exactly the same as external functions except they are scoped to the class and have access to private members of the class.

What is the difference between linear and circular queue?

What is the difference between linear and circular queue? In: http://wiki.answers.com/Q/FAQ/2545-37 [Edit categories]


The Queue by Default is Linear, it would be termed as Circular if the Last Element of the Queue pointsto the first element of the List

When is it necessary to use member wise initialization list in c plus plus?

Initialization lists makes a difference when we have objects as members. Instead of using default initialization followed by assignment, the initialization list can initialize the object to its final value. This can actually be noticeably faster.

When you need to initialize constant member, references and pass parameters to base class constructors, initialization list is the only choice. if you have members of class type with no default constructor available, initialization is the only way to construct your class.

There is only one way to initialize base class instances and non-static member variables and that is using the initializer list.

If you don't specify a base or non-static member variable in your constructor's initializer list then that member or base will either be default-initialized (if the member/base is a non-POD class type or array of non-POD class types) or left uninitialized otherwise.

Once the constructor body is entered, all bases or members will have been initialized or left uninitialized (i.e. they will have an indeterminate value). There is no opportunity in the constructor body to influence how they should be initialized.

You may be able to assign new values to members in the constructor body but it is not possible to assign to const members or members of class type which have been made non-assignable and it is not possible to rebind references.

For built in types and some user-defined types, assigning in the constructor body may have exactly the same effect as initializing with the same value in the initializer list.

If you fail to name a member or base in an initializer list and that entity is a reference, has class type with no accessible user-declared default constructor, is const qualified and has POD type or is a POD class type or array of POD class type containing a const qualified member (directly or indirectly) then the program is ill-formed.

C code programming to reverse a number?

/*The coding style used in this source code is for convenience.

* It is widely used style of coding. */

#include <stdio.h>

void main() {

int number, modulus, reverse;

reverse = 0;

printf("Enter a number \n");

scanf("%d", &number);

while(number != 0) {

modulus = number % 10;

reverse = (reverse * 10) + modulus;

number =number / 10;

}

printf("The reversed number is %d", reverse);

getch();

}

How much does C plus plus cost?

The express edition of Microsoft Visual C++ is free. The non express editions range in price between a few hundred dollars US to tens of thousands of dollars US depending on team integration and technical support.

Is it necessary to implement all the methods of abstract classes in derived class?

An Abstract class is a way to organize inheritance, sometimes it makes no since to implement every method in a class (i.e. a predator class), it may implement some to pass to its children but some methods cannot be implemented without knowing what the class will do (i.e. eat() in a Tiger class). Therefore, abstract classes are templates for future specific classes.

A disadvantage is that abstract classes cannot be instantiated, but most of the time it is logical not to create a object of an abstract class. heloooooo

What is an abstract datatype?

Abstract data type

A mathematical entity consisting of a set of values (the carrier set) and a collection of operations that manipulate them. For example, the Integer abstract data type consists of a carrier set containing the positive and negative whole numbers and 0, and a collection of operations manipulating these values, such as addition, subtraction, multiplication, equality comparison, and order comparison.

Abstraction

To abstract is to ignore some details of a thing in favor of others. Abstraction is important in problem solving because it allows problem solvers to focus on essential details while ignoring the inessential, thus simplifying the problem and bringing to attention those aspects of the problem involved in its solution. Abstract data types are important in computer science because they provide a clear and precise way to specify what data a program must manipulate, and how the program must manipulate its data, without regard to details about how data are represented or how operations are implemented. Once an abstract data type is understood and documented, it serves as a specification that programmers can use to guide their choice of data representation and operation implementation, and as a standard for ensuring program correctness.

Above retrieved from Answers.com

Viper1

Static and dynamic memory allocation in c plus plus?

dynamic memory allocation is that type of memory which create to allocate the memory on running time or at compile time by the function of malloc , calloc , realloc and free.

dynamic memory allocation is give the best utilization of memory which gives the sufficient use of memory.

In C plus plus What symbol is used to denote the declaration of a dynamic array?

We don't generally use dynamic arrays in C++, we use vectors instead. The problem with dynamic arrays is that we must keep track of how many elements are allocated in the array, and must manually manage the memory allocated to the array, just as we do in C. Vectors do this automatically for us and allow us to pass dynamic arrays into functions by reference. This ultimately makes it much easier to use a dynamic array without having to worry about how it is physically implemented.

Write a c plus plus program of array of size 10 and print the maximum value from it?

#include<iostream>

template<class T>

T max(T a[], size_t size)

{

T max=a[0];

for(size_t index=1; index<size; ++index)

if( max<a[index] )

max=a[index];

return(max);

}

int main()

{

int a[10]={6,3,1,8,4,0,9,2,5,7};

int max = max(a, 10);

// assert(max == 9);

}

What is the C plus plus code to print all ASCII codes and the equivalent characters?

Although character data types such as char are intrinsically numeric, whenever you print a char you automatically print the symbol associated with the character code (the char's value), never the code. In order to print the code you must cast the character to a numeric data type, such as int.

char c = 'A'; // ASCII value 65 decimal (0x41)

std::cout << static_cast<int>(c); // puts the value 65 on std::cout

How to write an effective program using c plus plus?

Here is a simple program that will tell you how to make an algorithm:

int main();

{

int length;

int width;

int total;

printf("What is the width: ");

scanf("%d", &width);

printf("What is the length: ");

scanf("%d", &length);

total = width * 2 + 2 * length; /*Here is the algorithm for finding the perimeter of a square*/

printf("The perimeter is: %d", total);

return 0;

}

Output:

What is the width: 32

What is the length: 55

The perimeter is: 174

How do you print 1 to 10 numbers using while loop in C?

#include <iostream>

int main()

{

int i=0;

while( i<10 )

printf( "%d\n", ++i );

return( 0 );

}

What is the difference between null and void pointers?

A void pointer is a pointer that has no type information attached to it.

A null pointer is a pointer that points to "nothing". A null pointer can be of any type (void included, of course).

What is the difference between a class and a union in c plus plus?

The data members of a class are each allocated separate memory addresses. A union's members are all mapped to the same address. If you change the value of one union member, you change them all.

What is memory leakage in c plus plus?

Memory leakage occurs when you allocate memory dynamically but do not keep track of the allocation. If you lose track of an allocation then you cannot release the memory back to the system until the program terminates. If you continually allocate without releasing, you not only waste a lot of memory unnecessarily, you could easily run out of memory altogether. The following code demonstrates this:

#include <iostream>

int main()

{

int* p=NULL;

do {

p=(int*)malloc(sizeof(int));

} while(p);

return(0);

}

In the above code, p is continually allocated memory which is not released before the next allocation. The program will eventually exit when you run out of memory, releasing all memory back to the system, but you should never code like this. Always release memory as soon as it is no longer required.

#include <iostream>

int main()

{

int* p=(int*)malloc(sizeof(int));

while(p)

{

delete(p); // release memory

p=(int*)malloc(sizeof(int));

}

return(0);

}

This time the program will never terminate so long as p is non-NULL. Although the program may never exit, memory is no longer leaking.

Obviously these programs are merely demonstrations and not useful in any way (we're not actually using the memory we allocate). In real applications, however, you will always delete pointers as soon as you're finished with them and especially when you wish to re-use a pointer, as per the second example.

So long as you maintain at least one pointer to allocated memory you can return that memory back to the system as soon as it is no longer required. If you fail to keep track of allocated memory, leakage is only to be expected. Even if it doesn't cause any problems, as per the first example, it is bad programming practice to allow any pointer to allocated memory to fall from scope.

Why not you simply put the decimal integer into the original string as compared to the format specifier?

You can certainly do that ...

printf ("This is a number: 12345\n");

... but that does not have the same value as placing the value in a variable and converting the variable into a string ...

int i = 12345;

printf ("This is a number: %d\n", i);

That's the whole point of format specifiers - to initiate a conversion from one place to another.