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

How many compiler in c plus plus?

They are completely unrelated. Java was designed as an attempt to improve C++, and C# was designed as an attempt to improve Java, so they have many things in common. They are not, however, the same language.

How do you write a program in C to swap two variables using a function?

#include<iostream>

void swap(int* x, int* x){

(*x)^=(*y)^=(*x)^=(*y);

}

int main()

{

int a, b;

a=10;

b=20;

std::cout<<"Before swap: a="<<a<<", b="<<b<<std::endl;

swap(&a,&b);

std::cout<<"After swap: a="<<a<<", b="<<b<<std::endl;

return(0);

}

How do you divide 2 numbers using c plus plus?

Basic code in C++ for division would be:

int a = 2;

int b = 2;

int c = a / b;

A more advanced application would be to allow the user to specify the variables:

#include <iostream>

int num1;

int num2;

std::cout << "What is the first number?";

std::cin >> num1;

std::cout << "What is the second number?";

std::cin >> num2;

std::cout << num1 / num2 << endl;

This program will not account for variables which are entered other than integers.

Define access specifiers in object oriented programming?

One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making them available only through its methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access modifiers. The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Access Modifiers

1. Private

2. Protected

3. Default

4. Public

Public is the most liberal access modifier and Private is the most restrictive access modifier. NB there is no such thing as an 'access specifier' in Java, only access modifiers.

When is it better to call by value vs. call by reference?

Call by value only when a function must modify a value, but you do not want those changes to be reflected in the original value. Passing by value creates a copy of the value which falls from scope when the function returns.

Note that in C++, call by value is the default. This is fine for all primitive data types, including pointer variables, but for complex objects you will generally want to pass by reference to avoid as much unnecessary copying as possible. Use the const keyword to enlist the compiler's help to ensure immutable members are not changed during a function call. Non-const references imply the function will alter the immutable members. That's fine when the changes are expected, but it's a good idea to provide a pass by value overload to cater for automatic copying whenever those changes are not wanted. You can also copy the object yourself and pass it by reference, but the copy remains in scope after the function call returns.

What is meant by private access in c plus plus?

It isn't. Private is the default access for class members. For struct members, the default access is public. Aside from default access, a class and a struct serve the same purpose; to define a class. As such, the following class definitions are equivalent:

class X {

int a;

};

struct Y {

private:

int b;

};

Typically, we use a struct to define simple data types with trivial construction and use class for more complex data types, often to encapsulate an invariant or to acquire a resource, hiding the implementation details from consumers using private access.

Write a c plus plus program using queue operation?

A queue is a first-in-first-out (FIFO) list of elements. In C++, you could implement a queue by designing a queue class that provided a constructor, destructor, add, and remove methods. The private implementation could use an array, with size specified in the constructor. It would have pointers or indicies that "follow each other" around the array. At boundary state, the queue::add() method would either throw a queue full exception, or it could dynamically adjust the array size, and the queue:remove() method would return null or throw a queue empty exception. Other implementations could be used, such as a singly or doubly linked list, but the "cost" of constantly allocating and deallocating elements would seem to overwhelm the simplicity of the array approach, even considering the possibility of (intermittantly) increasing the allocated size. No matter what approach is used, the public interface should be stable and well defined, so that various internal approachs could be tried and evaluated.

What is const pointer?

In computer science, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const keyword in those languages. The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwriteable. Rather, const-ness is a compile-time construct that indicates what a programmer may do, not necessarily what he or she can do. In addition, a class method can be declared as const, indicating that calling that method does not change the object. Such const methods can only call other const methods but cannot assign member variables. (In C++, a member variable can be declared as mutable, indicating that a const method can change its value. Mutable member variables can be used for caching and reference counting, where the logical meaning of the object is unchanged, but the object is not physically constant since its bitwise representation may change.) In C++, all data types, including those defined by the user, can be declared const, and all objects should be unless they need to be modified. Such proactive use of const makes values "easier to understand, track, and reason about," and thus, it increases the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it communicates something about a value's intended use. For simple data types, applying the const qualifier is straightforward. It can go on either side of the type for historical reasons (that is, const char foo = 'a'; is equivalent to char const foo = 'a';). On some implementations, using const on both sides of the type (for instance, const char const) generates a warning but not an error. For pointer and reference types, the syntax is slightly more subtle. A pointer object can be declared as a const pointer or a pointer to a const object (or both). A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee"). (Reference variables are thus an alternate syntax for const pointers.) A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object. A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object. The following code illustrates these subtleties: void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst ) { *ptr = 0; // OK: modifies the pointee ptr = 0; // OK: modifies the pointer *ptrToConst = 0; // Error! Cannot modify the pointee ptrToConst = 0; // OK: modifies the pointer *constPtr = 0; // OK: modifies the pointee constPtr = 0; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the pointee constPtrToConst = 0; // Error! Cannot modify the pointer To render the syntax for pointers more comprehensible, a rule of thumb is to read the declaration from right to left. Thus, everything before the star can be identified as the pointee type and everything to after are the pointer properties. (For instance, in our example above, constPtrToConst can be read as a const pointer that refers to a const int.) References follow similar rules. A declaration of a const reference is redundant since references can never be made to refer to another object: int i = 42; int const & refToConst = i; // OK int & const constRef = i; // Error the "const" is redundant Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to pointers. Generally speaking, these should be avoided or replaced with higher level structures because they are confusing and prone to error.

How do you compile the program in c plus plus program?

C++ programs consist of one or more translation units that must be compiled and linked to create an executable. Each translation unit is compiled separately to produce an object file. When all translation units are compiled, the object files are linked.

Translation units must be preprocessed before they can be compiled. That is, all macros must be expanded (replacing macro tokens with their expanded definitions) and all required include files are pulled in. The end result is an intermediate file which is the actual file processed by the compiler. During preprocessing of a translation unit, the include files for that unit are also preprocessed and expanded as necessary.

Not all translation units need to be compiled in every compilation. If a modification to the program has no effect upon a translation unit, the object file generated by a prior compilation can be used instead. This helps speed up the compilation process.

Headers that require little or no maintenance (such as standard library headers) can also be precompiled to help speed up the process even further.

Header files are often included in several translation units but can only be included once per compilation. To avoid unnecessary inclusions, headers typically use special macros known as inclusion guards of the following form:

// file: my_header.h

#ifndef _MY_HEADER_H_

#define _MY_HEADER_H_

// content goes here

#endif _MY_HEADER_H_

Inclusion guards typically use the file name as the basis for the macro definition and are deliberately ugly to avoid name clashes with other macros. The first time the header is processed, the macro will be undefined thus the content can be pulled into the intermediate file. All subsequent inclusions will see that the macro is already defined and will ignore the content.

What are the disadvantages of file systems?

1)Limited Security

2)limited Data Sharing

3)Data Redundancy

4)Integrity Problems

What is a stack in c plus plus?

You don't say which operation you wish to perform, however a stack has relatively few members:

construct: e.g. default and copy (C++11 includes move construct)

operator=: copy assignment (C++11 includes move assignment)

empty: test whether the stack is empty or not

pop: extract the top element from the stack

push: insert an element on top of the stack

size: return the size of the stack, count of elements

top (return the top element)

Additional members since C++11:

emplace: construct and push a new element from argument

swap: exchange elements with another stack

Non-member operator overloads are limited to the standard relational operators (e.g. ==, !=, <, <=, > and >=).

Stacks are typically used in backtracking algorithms because the last element pushed becomes the top element and is therefore the first element to be popped. Usually referred to as a LIFO (last in first out) sequence.

An example usage of a stack:

#include<iostream>

#include<stack>

#include<string>

#include<cassert>

int main ()

{

std::stack<std::string> mystack;

assert (mystack.empty());

mystack.push ("First element");

mystack.push ("Second element");

assert (mystack.size()==2);

std::cout << "mystack contains:\n";

while (!mystack.empty())

{

std::cout << mystack.top() << '\n';

mystack.pop();

}

}

Algorithm for implementation of stack using pointers?

#include<stdio.h>

#include<conio.h>

struct node

{

int data;

struct node *next;

};

typedef struct node NODE;

NODE* top = NULL;

void push()

{

NODE* temp;

int item;

temp = (NODE*)malloc (sizeof(NODE));

printf("Enter the item to be inserted-> ");

scanf("%d",&item);

temp->data = item;

temp->next = NULL;

if(top NULL)

{

printf("\n***Stack is empty***\n");

return;

}

else

{

temp = top;

printf("\nThe list is-> ");

while(temp != NULL)

{

printf("\t%d",temp->data);

temp = temp->next;

}

printf("\n");

}

}

int main()

{

int OP;

clrscr();

while(1)

{

printf("\n>>>CHOOSE OPTION<<<\n");

printf("\n 1.PUSH \n\n 2.POP \n\n 3.TRAVERSE \n\n 4.EXIT\n");

scanf("%d",&OP);

switch(OP)

{

case 1: push();

break;

case 2: pop();

break;

case 3: display();

break;

case 4: exit(1);

default:printf("\n\n\t<<WRONG OPTION PLEASE CHOOSE CORRECT OPTION>>\n\n");

break;

}

};

getch();

return 0;

}

What is variable in c plus plus programming?

You declare a variable by first defining its data type and then its name followed by a semi-colon. Here is an example:

int variable;

The example above declares an uninitialized integer variable. You can initialize the variable by giving it a value such as "int variable = 1;". It is important to initialize your variables, because you can get errors when executing your program that the variable does not have a value or is uninitialized. Variables that are uninitialized have whatever garbage value happens to be when the program is executed.

Here are all of the data types that a variable can be:

*int - integer value

*char - character value

*bool - boolean value

Why in copy constructor in c you use pass by reference?

Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to make a new value, so we call the copy constructor, and so on...

(You would have infinite recursion because "to make a copy, you need to make a copy".)

What is the difference between binary file and text file?

The difference is that text files may only contain printable character codes, either from the ASCII character set or the UNICODE character set. That is, letters, digits, punctuation, space, tab and other symbols, including line feed or carriage return/line feed pairs. Non-printable characters, such as the null character '\0' (or '\0\0' in UNICODE), are not permitted in plain-text files, however UNICODE files permit a 16-bit endian marker at the start of the file to denote the byte order of the wide characters that follow.

Text files can be displayed in any plain-text editor or word processor (as unformatted text). The entire text can also be extracted as a string (memory permitting), or as a stream of printable characters in a string buffer.

Binary files, on the other hand, cannot be interpreted as plain-text (although they may contain plain text elements). Binary files may contain any combination of bytes, and require special handling in order to be interpreted correctly. The exact meaning of the order of the bytes is entirely dependent upon the program that created the binary files in the first place.

Can int value be assigned to char variable?

Yes, but the results may not be what you expect, depending on the relative sizes of an int and a char (in bytes), whether they are signed or unsigned, and whether they use big-endian notation or not.

By way of an example, in C++ an int is typically 4 bytes long while a char is 1 byte long. Both are signed by default. If you were to loop an integer from 0x80000000 to 0x7fffffff (-2147483648 to +2147483647) using big-endian notation and assign the value to a signed char, then the char would repeatedly cycle through the values 0 to 127, then -128 to 0. This is because the char takes on the value of the least-significant byte of the integer in big-endien notation (the bytes are effectively reversed in memory). However, if you cycle the int from 0xffffff80 to 0x7f (-128 to +127), then you get the expected behaviour (the char cycles from -128 to +127). However, if the char were unsigned, then the first loop would repeatedly cycle from 0 to 255 while the second would cycle from 128 to 255, and then from 0 to 127.

Thus to get the expected behaviour, both the int and char must both be signed or both must be unsigned, and the range of values must be within the range of the smaller of the two types (which will typically be the char), and the system must either use big-endian notation (reverse notation) or must otherwise compensate for little-endian notation.

What are uses of do while?

A do-while loop is only useful when you want the loop to execute at least once. This is because the conditional expression is evaluated at the end of each iteration, rather than before each each iteration as it is in a for and a while loop.

Write a program to solve a quadratic equation using the quadratic formula in c plus plus?

#include<stdio.h> #include<conio.h>

void main()

{

float a,b,c,z,d,x,y;

clrscr();

printf("Enter the value of a,b,c");

scanf("%f %f %f",&a,&b,&c);

d=((b*b)-(4*a*c));

z=sqrt(d);

x=(-b+z)/(2*a);

y=(-b+z)/(2*a);

printf("The Quadratic equation is x=%f and y=%f",x,y);

getch();

}

This answer does not think about imaginary roots. I am a beginner in C programming. There might be flaws in my code. But, it does well.

the code is

#include<stdio.h>

#include<math.h>

main()

{

float a, b, c;

float dis, sqdis, real, imag, root1, root2;

printf("This program calculates two roots of quadratic equation of the form ax2+bx+c=0.\n");

printf("\n");

printf(" please type the coefficients a, b and c\n");

printf("\n");

printf("a = ");

scanf("%f", &a);

printf("\n");

printf("b = ");

scanf("%f", &b);

printf("\n");

printf("c = ");

scanf("%f", &c);

printf("\n");

dis = (b*b-4*a*c);

if(dis < 0)

{

sqdis = sqrt(-dis);

real = -b/(2*a);

imag = sqdis/(2*a);

printf(" The roots of the quadratic equations are \n x1\t=\t %f + %f i\n x2\t=\t %f -

%f i\n", real, imag, real, imag);

}

else

{

sqdis = sqrt(dis);

root1 = -b/(2*a)+sqdis/(2*a);

root2 = -b/(2*a)-sqdis/(2*a);

printf("The two roots of the quadratic equations are %f and %f.\n", root1, root2);

}

system("pause");

}

What is the advantage and disadvantage of constructor in c plus plus?

Objects allow you to establish invariants and limit the type of operations that can be performed upon the internal representation of the object, exposing only as much as is needed to use the object -- no more and no less. This greatly reduces the chances of the programmer making an error, creating more robust code more easily and with fewer runtime checks and much greater efficiency.

What is dangling pointer reference?

Whenever memory that was in use, and was referred to by a pointer variable, is freed, and the pointer variable is not updated accordingly (setting it to NULL, for example), the pointer variable is considerred to be a dangling pointer reference.

What are the advantages of the recursion in c plus plus?

Any problem that can be solved by dividing the problem into smaller problems of the same type is a good candidate for recursion. However, there are actually very few applications that cannot be resolved more efficiently with an iterative loop. It therefore pays to know when recursion is unavoidable and when it is optional.

The main benefit to recursion is that each instance of the function maintains its own set of non-static local variables completely independently of all other instances. But if these variables are of no use to the function when a recursive call returns, then an iterative implementation would be more efficient. Function calls are expensive in terms of memory consumption and performance, so the fewer we make, the better.

A classic example of recursive application is the quicksort algorithm. In simple terms, quicksort is a function that accepts a subset of data. The data is usually stored in an array and the function accepts the left and right index of the subset to be sorted. Initially this will be lower and upper bounds of the entire array, but if the indices indicate a subset with fewer than 2 items, the function immediately exits. This effectively defines the return path from the recursions.

Assuming there are 2 or more items, the function selects one of the items (the pivot) and then sorts the array such that items less than the pivot are placed to its left, and items greater or equal to its right. This moves the pivot into its final position, but the items on either side may still be unsorted. Thus the function calls itself twice, once for each of these subsets, which gradually reduces the problem down into smaller and smaller subsets until a subset has fewer than 2 items, at which point the recursion unwinds to the previous instance.

Recursion is required because when the first recursive call returns, the subset to the left of the pivot is guaranteed to be sorted, but the subset to the right is not. This means we must maintain local variables in order to determine the lower and upper bounds of that subset.

Although quicksort is an elegant application of recursion, there is still room for improvement. Firstly, it is better to make a recursive call upon the smaller of the two subsets. The smaller the subset, the fewer recursions that will be incurred sorting it.

Secondly, since the second recursion is also the last statement in the function, there is no need to maintain the local variables when it returns. Thus the second recursion can be implemented as a tail call. This effectively means we modify the existing local variables to suit and then recall the same instance (with a goto). This reduces the depth of recursion by one function call per recursion which will quickly add up to a significant boost in efficiency.

In a header file whether functions are declared or defined?

Ideally, functions should only be declared in a header and defined in a translation unit (source file) that includes the header. However, trivial functions are often defined in a header as they are usually good candidates for inline expansion, but you must remember to declare the function inline. Often it is better to forward declare inline functions so that maintainers are not distracted by the implementation details which can be placed towards the end of the header, out of the way. However, a definition is also a declaration, so forward declaring an inline function is not a requirement unless there is a cyclic dependency issue where a forward declaration is necessary to break the cycle.

In c plus plus Write a program that takes a decimal number input from the user and displays its binary number?

The following code will convert any number in any base to any other base, from binary to hexadecimal, and everything inbetween.

#include<iostream>

#include<string>

#include<sstream>

typedef unsigned long long ull;

typedef unsigned long ul;

const std::string symbols="0123456789abcdef";

std::string inputvalue(ul base)

{

using namespace std;

string value;

while(1)

{

cout<<"Enter a positive value : ";

string s;

getline(cin,s);

if(s.size())

{

for(string::iterator i=s.begin();i!=s.end();++i)

if(*i>='A' && *i<='Z')

*i+=32;

string actual = symbols.substr(0,base);

if(s.find_first_not_of(actual)!=string::npos)

{

cout<<"The value you entered is invalid for the base.\n"

<<"Please enter another value.\n"<<endl;

continue;

}

value=s;

break;

}

}

return(value);

}

ul inputbase(std::string prompt)

{

using namespace std;

ul result=0, min=2, max=16;

while(1)

{

cout<<prompt.c_str()<<" ["<<min<<".."<<max<<"] : ";

string s;

getline(cin,s);

if(s.size())

result=stoul(s,0,10);

if(result<min result>max)

cout<<"The base must be in the range "

<<min<<".."<<max<<"\n"

<<"Please enter another base.\n"<<endl;

else

break;

}

return(result);

}

ull base2dec(std::string value,ul base)

{

ull col=1, num=0;

for(std::string::reverse_iterator i=value.rbegin(); i!=value.rend(); ++i)

{

num+=symbols.find(*i,0)*col;

col*=base;

}

return(num);

}

std::string dec2base(ull dec,ul base)

{

using namespace std;

int len=1;

ull tmp=dec;

while(tmp/=base)

++len;

string value("0",len);

while(dec)

{

value[--len]=symbols[dec%base];

dec/=base;

}

return(value);

}

int main()

{

using namespace std;

ul base=inputbase("Enter the base of the value");

string value=inputvalue(base);

ul newbase=inputbase("Enter the base to convert to");

value=dec2base(base2dec(value,base),newbase);

cout<<"New value:\t"<<value.c_str()<<endl;

return(0);

}