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

Define protected access modifire in c plus plus?

The access privileges in c++ are

1.public

2.private

3.protected

and by default its private

Difference between Data Type and Abstract Data Type?

A data type tends to mean a primitive data type. Primitive data are built-in data types, such as integers, characters and Booleans. They are basic constructs of the language (that is, they are built into the language).

Primitive data also tends to be of a strict data type, meaning you can't treat characters like integers or Booleans like integers, etc., although some languages will support implicit casting of primitive data types (for example, will treat Booleans like integers if you use a Boolean in an arithmetic operation).

Abstract data types are generally constructed by the user or by a higher level language. For example, you might create a currency data type, which generally acts like a float but always has a precision of 2 decimal places and implements special rules about how to round off fractions of a cent.

Abstract data types also often contain the ability to either be treated as a specific type of primitive data in certain circumstances (for example, many languages allow you to treat strings as character arrays); or contain certain rules / methods to manipulate their data (such as a programming language allowing you to cast a float as an integer).

A data structure is a gathering together of many different data types. For example, objects and arrays are data structures. Data structures usually can contain information of many different types (such as strings, integers, Booleans) at the same time, and in more complex structures -- namely, classes -- can contain specific methods, properties and events to manipulate that data, change its type, etc.

What are the drawbacks of structured programming language over object oriented programming language and explain with suitable examples?

The main drawback to structured programming is that the data and the methods that operate upon that data are completely separate. This means that any code with access to the data can modify that data. In and of itself that is not a major problem, but it places the onus upon the programmer to ensure that all data is modified in a consistent and highly predictable manner, which may require additional verifications and assurances within the code to ensure that is always the case. For instance, if a variable must have a limited range of 0 to 100, then the programmer may be forced to ensure that is the case before he can use the data, and may need to perform that same check every time the data is used.

Object oriented programming combines the data and the methods that operate upon that data into a single entity, presenting the data to the outside world in a more abstract form, limiting its exposure and protecting its integrity. Mutators that modify the internal data act as gatekeepers, assuring that any and all modifications to the data are consistent. The programmer no longer needs to continually check the state of the data before using the data, as the onus is now upon the object to ensure that data integrity is maintained at all times.

By delegating the workload to the objects themselves, highly-complex data models can be created simply by embedding objects within objects, where each individual object is solely responsible for its own data integrity. The programmer can then manipulate these highly complex structures as a single entity, rather than through a series of separate functions and data that could very easily be corrupted by a single errant statement that would be difficult to trace.

Write a program to accept a character value from the user and sHow is its ASCII value?

You don't need to write a program to do this. Each character (char) is actually an int. If you want to see the ASCII value of a char you can simply:

char c = 'a';

System.out.print( (int)c );

C plus plus program to find factorial of given number using function overloading?

Use this function: long factorial(int N)

{

if (N == 0)

{

return 1;

}

else

{

return N*factorial(N-1);

}

}

Fibonacci c plus plus program?

#include<iostream>

int main()

{

int x=0, y=1;

std::cout<<x<<" ";

std::cout<<y<<" ";

while( y<1000000 )

{

std::cout<<(y+=x)<<" ";

x=y-x;

}

std::cout<<std::endl;

return(0);

}

Need of friend function in c plus plus?

Declaring a function to be a friend of a class allows the friend function to gain private (and protected) access to that class, just as it would if it were declared a static member function of the class. Most of the time you will want to use static functions rather than friend functions, but sometimes it is necessary for a member method of another class or an external function to be permitted private access. Although some will tell you this undermines the encapsulation of the class, it does not. If anything, it reinforces that encapsulation, by only allowing the specified function to gain private access. Although the friend function is not physically a member of the class, it automatically becomes tightly bound to the class. That is not necessarily a bad thing when you're only dealing with a limited number of friends, but a class that has many friends can often be an indication of poor class design. Thus it is important to limit friendship and to only use it when it is absolutely required, whenever possible.

By way of an example, suppose you have designed a parent and child class. Even without friend functions, the two are implicitly bound to each other: the parent object is a container for child objects, while child objects refer to their parents. All work is delegated and coordinated between the two classes accordingly; they work together as one. Most of the work can be encapsulated without the need to explicitly bind the classes together, however child objects typically refer to their parent object (via a member pointer) and might also be permitted to change their parent, but we wouldn't want to expose that pointer outside of the class, nor would we want to expose any mutators such as child::set_parent() outside of the class. But since the two classes are imlicitly bound to each other, we can declare specific methods of the parent class to be friends of the child class, such as parent::add_child(). In this way we can be sure that whenever we add a child to a parent, the parent not only attaches the child to itself, but also detaches the child from any existing parent beforehand. Far from undermining the encapsulation, this friendship reinforces it, assuring us that both classes are tightly bound.

Need of function overloading in c plus plus?

The need for function overloading is to allow the same function call to accept different parameter types and/or a different number of parameters. The function signature differentiates the functions. The return type is also part of the signature, and needn't be the same for every overload.

Where the function signature is largely the same, with the same count of parameters but a different parameter type and return type, template functions can provide an alternative method of creating the function overloads. The compiler generates the necessary code for you, on an as-required basis, so you only need to write the function once, rather than once for each type.

Explain types of inheritance in c plus plus?

There are essentially just two types of inheritance: single inheritance and multiple inheritance. Single inheritance simply means that one class derives directly from another class. Multiple inheritance means one class is directly derived from two or more classes.

However, since base classes can (and often are) be derived from other base classes, you can think of this type of inheritance as being multi-level. In addition, two or more base classes that share a common base class can use virtual inheritance. What this means is that the common base class becomes a direct base class of the most-derived class, and this one instance is shared, virtually, by all the base classes that would otherwise inherit directly from it. in other words, there is only one instance of the common base class, rather than one instance per class that inherits from it. This is useful in the so-called "dreaded diamond" formation, where a derived class inherits from two base classes, both of which inherit from a common base class.

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".)